import sys
import re
try:
    from urllib.request import urlopen
except ImportError: # python2
    from urllib2 import urlopen

def getHashes(data):
    hashTables = re.findall(r'<table class="table table--hashes">(.*?)</table>', data, re.DOTALL)
    hashes = {}
    for table in hashTables:
        sha, blake = [re.findall(r'<tr>.*?%s.*?<code>(.*?)</code>' % algo, table, re.DOTALL)[0] for algo in ('SHA256', 'BLAKE2-256')]
        hashes[blake] = sha
    return hashes

def getLinks(data):
    return re.findall(r'(https://files\.pythonhosted\.org/packages/[^"]+)', data)

def parseLink(lnk, hashes):
    parts = lnk.split('/')
    blake = ''.join(parts[4:7])
    fn = parts[-1]
    pyver = re.findall(r'-cp(\d\d)-', fn)[0]
    plat = fn.split('-')[-1]
    for p in ('linux', 'win', 'osx'):
        if p in plat:
            plat = p
            break
    else:
        raise ValueError('Unknown platform: %s' % plat)
    return hashes[blake], pyver, plat

def parse(data):
    hashes = getHashes(data)
    links = getLinks(data)
    items = []
    for link in links:
        items.append((link, parseLink(link, hashes)))
    items.sort(key=lambda item: (item[1][1], item[1][2]))
    curPyver = None
    for link, (sha, pyver, plat) in items:
        if curPyver != pyver:
            curPyver = pyver
            print('  # python == %s' % '.'.join(pyver))
        print('  url: %s # [%s and py == %s]' % (link, plat, pyver))
        print('  sha256: %s # [%s and py == %s]' % (sha, plat, pyver))

def main(url):
    inp = urlopen(url)
    try:
        data = inp.read().decode('utf8')
    finally:
        inp.close()
    parse(data)

if __name__ == '__main__':
    try:
        fn = sys.argv[1]
    except IndexError:
        sys.exit('Usage: %s https://url-path-to-pypi-page' % sys.argv[0])
    sys.exit(main(fn))

