#!/usr/bin/env python3
"""Run the real launcher build at both pins, unpack its tarball, and record provenance."""
import datetime, hashlib, json, os, pathlib, shlex, subprocess, tarfile

ROOT = pathlib.Path('/tmp/lead-32913-r2/evidence-capture-1')
PINS = {'before': 'fa2f4ff2a2bac5ac92e07749f6b83b0003d642a0', 'after': '1af59792b3ca105da634cdf90c392bae9ad1ff91'}
NODE = '/home/user/.local/share/vite-plus/bin/node'

def main():
    session = ROOT / ('build-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ'))
    session.mkdir()
    results = {}
    for side, sha in PINS.items():
        repo = pathlib.Path('/home/user/wt/pr-32913' + ('-before' if side == 'before' else ''))
        run = session / side
        (run / 'home').mkdir(parents=True)
        env = {'HOME': str(run / 'home'), 'T3CODE_HOME': str(run / 'home/t3'), 'PATH': '/usr/bin:/bin', 'NO_COLOR': '1'}
        check = subprocess.check_output(['/bin/sh', '-c', 'env | grep T3CODE; printf "HOME=%s\\n" "$HOME"'], env=env, text=True)
        assert '/home/user/.t3' not in check
        cmd = [NODE, str(repo / 'scripts/build-npm-launcher.ts'), '--version', '1.2.3', '--output-dir', str(run / 'out')]
        proc = subprocess.run(cmd, cwd=repo, env=env, capture_output=True, text=True)
        text = f'SHA={sha}\nUTC={datetime.datetime.now(datetime.timezone.utc).isoformat()}\n$ env | grep T3CODE\n{check}$ {shlex.join(cmd)}\n{proc.stdout}{proc.stderr}EXIT={proc.returncode}\n'
        (run / 'build-transcript.txt').write_text(text)
        assert proc.returncode == 0, text
        installed = run / 'unpacked'
        installed.mkdir()
        with tarfile.open(run / 'out/t3.tgz') as tf:
            tf.extractall(installed, filter='data')
        launcher = installed / 'package/bin/t3.mjs'
        original = subprocess.check_output(['git', '-C', str(repo), 'show', sha + ':scripts/npm-launcher/t3.mjs'])
        assert launcher.read_bytes() == original
        results[side] = {'sha': sha, 'launcher': str(launcher), 'sha256': hashlib.sha256(original).hexdigest(), 'build_command': cmd, 'package': json.loads((installed / 'package/package.json').read_text())}
        print(side, sha, launcher, flush=True)
    (session / 'provenance.json').write_text(json.dumps(results, indent=2))
    (ROOT / 'latest-build.txt').write_text(str(session))

if __name__ == '__main__': main()
