from pathlib import Path
import subprocess, time

p = Path(__file__).parent
deadline = time.monotonic() + 900

def upload(names):
    while time.monotonic() < deadline:
        try:
            result = subprocess.run(['ghdrop', 'upload', '-m', *(str(p / name) for name in names)], capture_output=True, text=True, timeout=40)
            if result.returncode == 0:
                print(result.stdout, end='', flush=True)
                return result.stdout
            print(result.stderr.strip(), flush=True)
        except subprocess.TimeoutExpired:
            print('ghdrop upload timed out; originals retained locally.', flush=True)
        time.sleep(30)
    raise SystemExit('Upload deadline reached; files remain available locally.')

scripts = upload(['build-evidence.py', 'reproduce.md', 'upload-final.py'])
with (p / 'uploads-all.md').open('a') as f:
    f.write('\n' + scripts)
subprocess.run(['python3', str(p / 'build-evidence.py')], check=True)
final = upload(['evidence.md', 'index.html', 'uploads-all.md', 'artifact-urls.json'])
(p / 'uploads-final.md').write_text(final)
