"""Run with: python3 prove.py NODE_26_13_1 BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIRECTORY.
Requires vp i in each checkout. Uses only fresh synthetic data; runs no tests.
"""
import sys, pathlib, subprocess, os, time, datetime, re
node, base, head, output=sys.argv[1:]
root=pathlib.Path(output)/datetime.datetime.now(datetime.UTC).strftime('%Y%m%dT%H%M%SZ')
root.mkdir(parents=True)
scripts=pathlib.Path(__file__).parent
for side,checkout,port in [('base',base,14982),('head',head,14981)]:
    out=root/side
    out.mkdir()
    home=out/'home'
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    seed=subprocess.check_output([node,str(scripts/'seed.mjs'),checkout,str(home)],cwd=checkout,text=True,stderr=subprocess.STDOUT)
    (out/'seed.txt').write_text(seed)
    env={**os.environ,'T3CODE_DEV_SEED':'0'}
    log=out/'server-private.log'
    with log.open('w') as f:
        proc=subprocess.Popen([node,'apps/server/src/bin.ts','serve','--base-dir',str(home),'--host','127.0.0.1','--port',str(port)],cwd=checkout,env=env,stdout=f,stderr=subprocess.STDOUT)
    try:
        deadline=time.monotonic()+120
        while time.monotonic()<deadline:
            raw=log.read_text()
            if 'T3 Code server is ready.' in raw and 'Hydrated legacy v1 thread transcripts' in raw: break
            if proc.poll() is not None: raise RuntimeError('Server exited; inspect private log')
            time.sleep(.2)
        else: raise RuntimeError('Server readiness deadline exceeded')
        cli=subprocess.check_output([node,'apps/server/src/bin.ts','thread','show','thread-legacy','--base-dir',str(home)],cwd=checkout,env=env,text=True,stderr=subprocess.STDOUT)
        inspect=subprocess.check_output([node,str(scripts/'inspect.mjs'),str(home)],cwd=checkout,text=True,stderr=subprocess.STDOUT)
        raw=log.read_text()
        # Capture only the relevant server-emitted diagnostic lines; pairing credentials never enter evidence.
        diagnostics='\n'.join(line for line in raw.splitlines() if any(s in line for s in ['26_Canonicalize','Failed to sweep orphaned','Failed to load projects','failed to gather V2 startup counts','thread pull request refresh failed','automatic thread settlement sweep failed','SchemaError: Expected','at [0]["defaultModelSelection"]','T3 Code server is ready.','Hydrated legacy v1 thread transcripts']))
        transcript=f'{side.upper()} | commit {sha}\nLinux x64 | real t3 serve + t3 thread show | Node 26.13.1\nFresh synthetic V1 state.sqlite, migration 25; same seed on both sides.\n\n$ t3 serve (startup diagnostic excerpts)\n{diagnostics}\n\n$ inspect migrated database (read-only)\n{inspect}\n$ t3 thread show thread-legacy\n{cli}'
        (out/'transcript.txt').write_text(transcript)
        print(transcript,flush=True)
    finally:
        proc.terminate()
        try: proc.wait(timeout=15)
        except subprocess.TimeoutExpired:
            proc.kill(); proc.wait()
print('Evidence directory:',root)
