import sys, pathlib, subprocess, os, time, sqlite3, json, datetime, socket
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
run.mkdir()
for side, checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    data=run/side
    env=dict(os.environ,T3CODE_DEV_SEED='0')
    with socket.socket() as sock:
        sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]
    with (run/(side+'-startup.log')).open('w') as log:
        p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(data),'--host','127.0.0.1','--port',str(port)],cwd=checkout,env=env,stdout=log,stderr=log)
        try:
            for _ in range(120):
                db=data/'userdata/statev2.sqlite'
                if db.exists():
                    with sqlite3.connect(db) as c:
                        if c.execute("select count(*) from sqlite_master where name='agent_feedback'").fetchone()[0]:break
                if p.poll() is not None:raise RuntimeError('server exited; inspect startup log')
                time.sleep(.25)
            else:raise RuntimeError('migrations did not complete')
        finally:
            p.terminate();p.wait(timeout=30)
    (data/'userdata/settings.json').write_text('{"agentFeedback":{"mode":"auto"}}')
    with sqlite3.connect(db) as c:
        c.execute("insert into agent_feedback (id,created_at,kind,subject,expected,actual,workaround,user_requested,source,sent) values ('r1','2026-11-29T00:00:00.000Z','bug','t3_thread_read','a','b','',1,'cli',0)")
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    output=['T3 Code CLI | Linux | Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Commit: '+sha,'Fresh isolated database migrated by this commit’s real server.','']
    for turns,count in [(1,1),(0,0),(2,1),(1,2),(2,2)]:
        trace=dict(turns=turns,textTurns=0,truncated=False,entries=[dict(turn=1,type='user',text='synthetic')]*count)
        with sqlite3.connect(db) as c:c.execute('update agent_feedback set trace=? where id=?',(json.dumps(trace),'r1'))
        result=subprocess.run(['node','apps/server/src/bin.ts','feedback','list','--base-dir',str(data)],cwd=checkout,env=env,capture_output=True,text=True)
        output += [f'$ t3 feedback list --base-dir <isolated>  # turns={turns}, entries={count}',result.stdout.rstrip(),result.stderr.rstrip()]
        if result.returncode:raise RuntimeError(result.stderr)
    (root/(side+'.txt')).write_text('\n'.join(output))
print(run)
