#!/usr/bin/env python3
import argparse
import io
import json
import os.path
import re
import urllib.request
import zipfile

DEFINITION_RE = re.compile(
    r'https://dev.azure.com/(?P<org>[^/]+)/(?P<project>[^/]+)'
    r'/_build/latest\?definitionId=(?P<definition>\d+)',
)
BUILDS = 'https://dev.azure.com/{org}/{project}/_apis/build/builds?api-version=5.0&definitions={definition}&$top=5'  # noqa: E501
ARTIFACTS = 'https://dev.azure.com/{org}/{project}/_apis/build/builds/{build}/artifacts?api-version=5.0'  # noqa: E501


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('tag')
    parser.add_argument('--dest', default='dist')
    args = parser.parse_args()

    with open('README.rst') as f:
        match = DEFINITION_RE.search(f.read())
        assert match

    builds_resp = urllib.request.urlopen(BUILDS.format(**match.groupdict()))
    builds_json = json.load(builds_resp)

    build_id = next(
        iter([
            build['id'] for build in builds_json['value']
            if build['status'] == 'completed'
            if build['result'] == 'succeeded'
            if build['sourceBranch'] == f'refs/tags/{args.tag}'
        ]),
    )

    artifacts_url = ARTIFACTS.format(build=build_id, **match.groupdict())
    artifacts_resp = urllib.request.urlopen(artifacts_url)
    artifacts_json = json.load(artifacts_resp)

    os.makedirs(args.dest, exist_ok=True)
    for artifact in artifacts_json['value']:
        if artifact['name'].startswith('wheel_'):
            print(f'artifact: {artifact["name"]}')
            resp = urllib.request.urlopen(artifact['resource']['downloadUrl'])
            bio = io.BytesIO(resp.read())
            with zipfile.ZipFile(bio) as zipf:
                for info in zipf.infolist():
                    if info.filename.endswith('.whl'):
                        info.filename = os.path.basename(info.filename)
                        zipf.extract(info, path=args.dest)
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
