#!/usr/bin/env python3
"""Commands used for both sides, packaged with portable paths.
Run prepare before starting a fresh worktree server; seed after it listens.
Use: python3 reproduce.py prepare|seed CHECKOUT SCRATCH
"""
import json, pathlib, shutil, subprocess, sys
mode,checkout,scratch=sys.argv[1:]
checkout=pathlib.Path(checkout).resolve(); scratch=pathlib.Path(scratch).resolve()
scratch.mkdir(parents=True,exist_ok=True)
home=checkout/'.t3'
project=scratch/'demo'
def run(args,cwd=checkout):
    subprocess.run(args,cwd=cwd,check=True)
if mode=='prepare':
    wrapper=scratch/'codex-final.cjs'
    real=shutil.which('codex')
    wrapper.write_text("""#!/usr/bin/env node
const {spawn}=require('node:child_process');
const readline=require('node:readline');
const child=spawn(REAL,process.argv.slice(2),{stdio:['pipe','pipe','inherit']});
process.stdin.pipe(child.stdin);
readline.createInterface({input:child.stdout}).on('line',line=>process.stdout.write(line.replaceAll('"phase":"commentary"','"phase":"final_answer"')+'\\n'));
child.on('exit',code=>process.exit(code??1));
process.on('SIGTERM',()=>child.kill('SIGTERM'));
""".replace('REAL',json.dumps(real)))
    wrapper.chmod(0o755)
    data=home/'userdata'; data.mkdir(parents=True,exist_ok=True)
    (data/'settings.json').write_text(json.dumps({'providerInstances':{'codex':{'driver':'codex','enabled':True,'config':{'binaryPath':str(wrapper)}}}}))
    if not project.exists():
        project.mkdir(); (project/'README.md').write_text('# Demo\n')
        for args in [['init','-q'],['add','.'],['-c','user.name=Demo','-c','user.email=demo@example.invalid','commit','-qm','Initial']]:
            run(['git',*args],project)
elif mode=='seed':
    cli=['node','apps/server/src/bin.ts']
    run([*cli,'project','add',str(project),'--title','Demo','--base-dir',str(home)])
    run([*cli,'thread','start',str(project),'Say exactly "Goal met. The README exists." before running any tools. Then run ls README.md. Then reply exactly "Verified: README.md is present."','--provider','codex','--model','gpt-6-luna','--title','README verification','--wait','--json','--base-dir',str(home)])
else:
    raise SystemExit('Use prepare or seed')
