import subprocess, pathlib, json, time, os, signal, datetime
from recording import Recording
ROOT=pathlib.Path(__file__).resolve().parent
run=ROOT/datetime.datetime.now().strftime('run-%Y%m%d-%H%M%S'); run.mkdir()
registry=json.loads((ROOT/'registry-live.json').read_text())
agent=next(a for a in registry['agents'] if a['id']=='devin')
live=agent['version']; old='3000.12.57'
agent['version']=old
for target in agent['distribution']['binary'].values(): target['archive']=target['archive'].replace(live,old)
for side,checkout,port in [('before','factory-issue-40257-evidence-1-base',18357),('after','factory-issue-40257-evidence-1',18358)]:
    work=pathlib.Path.home()/'wt'/checkout
    home=run/side; (home/'caches/acp-registry').mkdir(parents=True); (home/'userdata').mkdir()
    cache=home/'caches/acp-registry/registry.json'; cache.write_text(json.dumps(registry)); os.utime(cache,(time.time()-5*86400,)*2)
    (home/'userdata/settings.json').write_text(json.dumps({'providerInstances':{'devin_acp':{'driver':'acpRegistry','enabled':True,'config':{'agentId':'devin'}}}}))
    project=home/'project'; project.mkdir(); subprocess.run(['git','init','-q',str(project)],check=True)
    log=open(home/'server.log','w')
    env={**os.environ,'T3CODE_DEV_SEED':'0'}
    server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--port',str(port),'--host','127.0.0.1'],cwd=work,env=env,stdout=log,stderr=log,start_new_session=True)
    transcript=[f'Surface: real T3 server + CLI; Linux x86_64; fresh isolated data',f'Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],cwd=work,text=True).strip(),f'Seed: live ACP Registry; Devin rewritten to {old}; cache mtime five days old.',f'Live registry version: {live}']
    recording=Recording(home/'terminal.mp4',side.upper()+' | ACP Registry stale-cache reproduction | real server + CLI',transcript)
    def cli(args,timeout=120):
        cmd=['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)]
        shown='t3 '+' '.join(args).replace(str(project),'<synthetic-project>')
        transcript.append('$ '+shown)
        try:
            p=subprocess.run(cmd,cwd=work,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout)
            transcript.append(p.stdout.replace(str(home),'<isolated-data>').replace(str(work),'<checkout>')); transcript.append('exit: '+str(p.returncode))
        except subprocess.TimeoutExpired as e: transcript.append('Timed out after '+str(timeout)+'s\n'+str(e.stdout))
    try:
        import urllib.request
        for i in range(120):
            try: urllib.request.urlopen(f'http://127.0.0.1:{port}/api/health',timeout=1); break
            except Exception:
                if 'T3 Code server is ready.' in (home/'server.log').read_text(): break
                if server.poll() is not None: raise RuntimeError('server exited')
                time.sleep(.5)
        cli(['project','add',str(project),'--title','ACP cache recovery'])
        cli(['thread','start',str(project),'Reply with OK','--provider','devin_acp','--model','default','--wait','--json'],180)
        transcript.append('Cached Devin version after thread start: '+next(a for a in json.loads(cache.read_text())['agents'] if a['id']=='devin')['version'])
        installs=list((home/'tools').rglob('bin/devin'))
        transcript.append('Devin install paths: '+str([str(p.relative_to(home)) for p in installs]))
        log.flush()
        import re
        causes=[]
        for line in (home/'server.log').read_text().splitlines():
            if '[cause]:' in line and any(t in line for t in ['AcpRegistryError:', 'HttpClientError:', 'authentication', 'Authentication', 'authenticate', 'ENOENT']):
                clean=line.split('[cause]:',1)[1].strip().removesuffix("\\n' +").strip()
                clean=re.sub(r'/home/[^ ]+', '<local-path>', clean)
                if clean not in causes: causes.append(clean)
        transcript.extend(['Server error causes (unique):',*causes])
        for binary in (home/'tools').rglob('bin/devin'):
            transcript.append('Installed binary size: '+str(binary.stat().st_size)+' bytes')
    finally:
        os.killpg(server.pid,signal.SIGTERM)
        try: server.wait(timeout=15)
        except subprocess.TimeoutExpired: os.killpg(server.pid,signal.SIGKILL); server.wait()
        log.close()
        (home/'transcript.txt').write_text('\n'.join(transcript))
        recording.close()
    print(side+'\n'+'\n'.join(transcript),flush=True)
print('OUTPUT '+str(run),flush=True)
