#!/usr/bin/env python3
"""Select an unexpired private distribution artifact matching this checkout's source commit.
Uses read-only GitHub API calls through gh. Never changes a version or repository.
"""
import argparse
import json
import os
from pathlib import Path
import subprocess

p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--workflow', required=True)
p.add_argument('--platform', required=True)
p.add_argument('--run')
a = p.parse_args()
repo = os.environ.get('GITHUB_REPOSITORY', 'voyager-so/vork')
root = Path(__file__).resolve().parents[1]
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip()

def api(path):
    return json.loads(subprocess.check_output(['gh', 'api', f'repos/{repo}/{path}'], text=True))

runs = [api(f'actions/runs/{a.run}')] if a.run else api(f'actions/workflows/{a.workflow}/runs?status=success&per_page=100')['workflow_runs']
for run in runs:
    if run['conclusion'] != 'success' or Path(run['path']).name != a.workflow:
        continue
    if run['head_sha'] != commit:
        continue
    artifacts = api(f'actions/runs/{run["id"]}/artifacts?per_page=100')['artifacts']
    if any(item['name'] == a.platform and not item['expired'] for item in artifacts):
        print(run['id'])
        break
else:
    p.error(f'no successful {a.workflow} artifact for {a.platform} with source commit {commit}; build/sign matching artifacts or supply --run')
