"""Usage: python3 reproduce.py BASE_WORKTREE HEAD_WORKTREE OUTPUT_DIR
Run vp i in both checkouts first. Place fixture.ts and call-snapshot.py beside this file.
This adds temporary fixture hooks; the production save/formatting code is untouched.
"""
import datetime, os, pathlib, subprocess, sys, time
bundle = pathlib.Path(__file__).resolve().parent
out = pathlib.Path(sys.argv[3]).resolve() / datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
out.mkdir(parents=True)
for side, checkout, port in [('before', sys.argv[1], 14737), ('after', sys.argv[2], 14738)]:
    root = pathlib.Path(checkout).resolve()
    folder = root / 'apps/server/src/mcp'
    fixture = folder / 'evidenceFixture.ts'
    if fixture.exists(): raise RuntimeError('Fixture path already exists')
    originals = {}
    process = None
    try:
        fixture.write_text((bundle/'fixture.ts').read_text())
        for name, function in [('PreviewAutomationBroker','brokerFixture'), ('McpSessionRegistry','credentialFixture')]:
            path = folder / (name+'.ts')
            originals[path] = path.read_text()
            path.write_text('import { '+function+' } from "./evidenceFixture.ts";\n'+originals[path].replace(
                'Layer.effect('+name+', make)', 'Layer.effect('+name+', make.pipe(Effect.tap('+function+')))'))
        home = out / (side+'-home')
        with (out/(side+'-private-server.log')).open('w') as log:
            process = subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--port',str(port),'--host','127.0.0.1'],cwd=root,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=log,stderr=log)
            for _ in range(120):
                if process.poll() is not None: raise RuntimeError('Server stopped; inspect private log')
                if (home/'credential.json').exists():
                    try:
                        import urllib.request
                        urllib.request.urlopen('http://127.0.0.1:'+str(port), timeout=1)
                        break
                    except Exception as error:
                        if getattr(error,'code',None) is not None: break
                time.sleep(1)
            subprocess.run(['python3',str(bundle/'call-snapshot.py'),str(home),str(out/(side+'-response.json'))],check=True)
    finally:
        if process is not None:
            process.terminate()
            process.wait(timeout=30)
        for path, original in originals.items(): path.write_text(original)
        fixture.unlink()
print('Raw output (contains local paths; normalize T3 home before publishing):',out)
