"""
Automate registration of conda build artifacts to EMBL GitLab;
assumes API access token is recorded in ~/.pypirc shell configuration file
"""
from configparser import ConfigParser
import json
from pathlib import Path
import requests

id = '5668'
proj = 'model_server'
root = Path('../conda-bld/')

# get authentication info from local config file
cfg = ConfigParser()
cfg.read(Path.home() / '.pypirc')
user = cfg['gitlab-model-server']['username']
pwd = cfg['gitlab-model-server']['password']

with open(root / 'channeldata.json', 'r') as fh:
    chdata = json.load(fh)

# upload to GitLab API
res = {}
for sd in ['noarch', 'win-64']:
    with open(root / sd / 'repodata.json', 'r') as fh:
        dd = json.load(fh)
    pkgname = f'conda_{sd}'

    if len(dd['packages']) == 0:
        continue

    # put each .tar.bz2
    for fn in dd['packages'].keys():
        ver = dd['packages'][fn]['version']
        stem = fn.split('.tar.bz2')[0]
        res[(sd, fn)] = requests.put(
            f'https://git.embl.de/api/v4/projects/{id}/packages/generic/{pkgname}/{ver}/{fn}?status=default',
            files={'file': open(root / sd / fn, 'rb')},
            headers={'PRIVATE-TOKEN': pwd},
        )

    # put requirements.yml
    fn = 'requirements.yml'
    res[(sd, fn)] = requests.put(
        f'https://git.embl.de/api/v4/projects/{id}/packages/generic/{pkgname}/{ver}/{fn}?status=default',
        files={'file': open(root.parent / fn, 'r')},
        headers={'PRIVATE-TOKEN': pwd, 'Content-Type': 'text/html'},
    )
print('Finished')
print(res)