#!/usr/bin/env python3


import html.parser
import os
import sys
import urllib.request


"""
Download Windows product keys from MicroSoft
"""

key_page_url = "https://docs.microsoft.com/en-us/windows-server/get-started/kms-client-activation-keys"


def usage():
    script = os.path.basename(sys.argv[0])
    message = f"""Usage: {script} [windows-version]

To specify the version of Windows you'd like, pass a string that matches the
name of the operating system you'd like to download. Case doesn't matter, so
you can use "windows 10" or "Windows 10".

e.g.

    {script} "Windows 10"
    {script} "enterprise"

"""
    print(message, file=sys.stderr)
    sys.exit(0)


def download_page(url):
    response = urllib.request.urlopen(url)
    return response.read().decode("utf-8")


class WindowsKeyPageParser(html.parser.HTMLParser):
    def __init__(self, *, convert_charrefs=True):
        super().__init__(convert_charrefs=True)
        self.product_keys = {}
        self.parsing_os = False

    def handle_starttag(self, tag, attrs):
        self.parsing_os = tag == "td"

    def handle_endtag(self, tag):
        self.parsing_os = False

    def handle_data(self, data):
        if self.parsing_os:
            self.stash_table_cell(data)

    def stash_table_cell(self, data):
        if "Windows" in data:
            self.current_os = data
        else:
            product_key = data
            self.product_keys[self.current_os] = product_key


def find_keys_for_all_versions(markup):
    parser = WindowsKeyPageParser()
    parser.feed(markup)
    return parser.product_keys


if __name__ == "__main__":
    try:
        arg = sys.argv[1]
    except IndexError:
        windows_version = ""
    else:
        if arg in ["-h", "--help"]:
            usage()
        windows_version = arg

    markup = download_page(key_page_url)
    product_keys = find_keys_for_all_versions(markup)

    for os_name, product_key in product_keys.items():
        if windows_version.lower() in os_name.lower():
            print(f"{os_name}: {product_key}")
