#!/usr/bin/env python3
"""Replay from explicit authorized worktree. Restores every modified tracked file in finally.
Usage: python3 /tmp/pr24406-evidence/replay.py
Requires the requested candidate HEAD, installed vp dependencies, and adjacent fixtures/driver.
"""
import subprocess,pathlib,os,json,shutil,platform,datetime
root=pathlib.Path('/home/ubuntu/wt/pr-24406');os.chdir(root)
out=pathlib.Path(__file__).resolve().parent
base='6e792117436662208bf2b6eb71ee8d0d88817e43';candidate='f78d4efb83406ee495171e1252d176384a5aa582'
head=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip()
assert head==candidate,(head,candidate)
files=['packages/source-control-gitcafe/src/server/'+f for f in ['GitCafePullRequestProvider.ts','gitCafePullRequestJson.ts']]
saved={f:(root/f).read_bytes() for f in files}
test='packages/source-control-gitcafe/src/server/pr24406-proof.test.ts'
assert not (root/test).exists() or (root/test).read_bytes()==(out/'proof-driver.test.ts').read_bytes()
shutil.copyfile(out/'proof-driver.test.ts',root/test)
tests=['packages/source-control-gitcafe/src/server/gitCafePullRequestJson.test.ts','packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts']
commands=[]
def run(label,args,env=None):
 e=os.environ.copy();e.update(env or {});e['PROOF_DIR']=str(out)
 p=subprocess.run(args,env=e,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 (out/(label+'.log')).write_text('$ cd '+str(root)+'\n$ '+' '.join(f'{k}={v}' for k,v in (env or {}).items())+' '+' '.join(args)+'\n'+p.stdout+f'\nEXIT_CODE={p.returncode}\n')
 commands.append({'label':label,'command':args,'env':env,'exit':p.returncode})
 print(label,'exit',p.returncode,flush=True)
 return p.returncode
try:
 for f in files:(root/f).write_bytes(subprocess.check_output(['git','show',f'{base}:{f}']))
 assert run('base-regressions',['vp','test','run',*tests,'-t','keeps only the newest run of a re-run check|reads the checks state from each check\'s newest run'])!=0
 assert run('base-runtime',['vp','test','run',test],{'PROOF_VERSION':'base','PROOF_ASSERT':'0'})==0
finally:
 for f,data in saved.items():(root/f).write_bytes(data)
try:
 assert run('candidate-tests',['vp','test','run',*tests])==0
 assert run('candidate-runtime',['vp','test','run',test],{'PROOF_VERSION':'candidate','PROOF_ASSERT':'1'})==0
finally:
 (root/test).unlink(missing_ok=True)
 (out/'commands.json').write_text(json.dumps(commands,indent=2)+'\n')
print(subprocess.check_output(['git','status','--short'],text=True))
