#!/usr/bin/env python3

import json
import sys

import urllib3

if len(sys.argv) < 3:
    print(f'Usage: {sys.argv[0]} user/repo output-file')
    sys.exit(1)

url = "https://api.github.com/repos/{}/releases/latest"
url = url.format(sys.argv[1])
output_file = sys.argv[2]
print('GET', url)

try:
    pool = urllib3.PoolManager(headers={'User-Agent': "curl/7.68.0"})
    response = pool.request('GET', url)
    assets = json.loads(response.data.decode('utf-8')).get('assets')
    if not assets:
        print('Nothing to download')
        sys.exit(1)

    for index, asset in enumerate(assets):
        print(f'#{index}', asset['name'])

    asset = None
    while not asset:
        index_or_key = input('Download (index or key): ').lower()
        try:
            asset = assets[int(index_or_key)]
        except ValueError:
            asset = None
            for asset_ in assets:
                if index_or_key in asset_['name'].lower():
                    asset = asset_
                    break

    url = asset['browser_download_url']
    print('GET', url)

    response = pool.request('GET', url, preload_content=False)
    total = int(response.getheader('Content-Length'))
    current = 0
    with open(output_file, 'wb') as fp:
        for chunk in response.stream(total // 100):
            fp.write(chunk)
            current += len(chunk)
            print(f'{current}/{total} {current / total * 100:.1f}%', end='\r')
        print()
except Exception as err:
    print('Failed:', err)
    sys.exit(1)
