"""Synthetic native reproduction. Use an isolated checkout/home and a leased iPhone.
Start: python native-clock-driver.py CHECKOUT HOST PORT METRO LIBFAKETIME start
Pair: same arguments, then pair SESSION (from the session's working directory).
Turn: same arguments, then turn. Capture with agent-device record start/stop.
The companion clock-proof-start-app.ts and clock-proof-shell.ts belong in scripts/.
"""
import json, os, subprocess, sys, urllib.parse
from pathlib import Path
checkout, host, port, metro, faketime, action, *rest = sys.argv[1:]
root = Path(checkout).resolve()
home = root / '.t3/manual'
workspace = home / 'workspaces/clock-demo'
env = dict(os.environ, T3CODE_DEV_SEED='0', T3CODE_PORT=port)
clock_env = dict(env, LD_PRELOAD=faketime, FAKETIME='+1h', FAKETIME_DONT_FAKE_MONOTONIC='1')
def cli(*args, skew=False):
    return subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=root,env=clock_env if skew else env,capture_output=True,text=True,check=True)
if action == 'start':
    def update(value, ms=250):
        return dict(type='emit_inbound',afterMs=ms,frame=dict(kind='notification',method='session/update',params=dict(sessionId='demo',update=value)))
    frames=[dict(type='expect_outbound',frame=dict(kind='request',method='session/prompt',params='<any>')),update(dict(sessionUpdate='tool_call',toolCallId='clock',kind='execute',title='Measure elapsed work',status='in_progress',rawInput=dict(command='measure elapsed work')))]
    frames += [update(dict(sessionUpdate='tool_call_update',toolCallId='clock',status='in_progress'),2000) for _ in range(60)]
    frames += [update(dict(sessionUpdate='tool_call_update',toolCallId='clock',status='completed')),update(dict(sessionUpdate='agent_message_chunk',content=dict(type='text',text='Elapsed work measured. Ready for the next task.'))),dict(type='emit_inbound',frame=dict(kind='response',method='session/prompt',result=dict(stopReason='end_turn')))]
    (root/'apps/server/scripts/dev-replay/showcase_transcript.ndjson').write_text('\n'.join(map(json.dumps,frames)))
    subprocess.run(['node','scripts/clock-proof-start-app.ts','mobile',str(home),port,metro,host],cwd=root,env=clock_env,check=True)
elif action == 'seed':
    workspace.mkdir(parents=True,exist_ok=True)
    (workspace/'README.md').write_text('Clock measurement workspace.\n')
    for args in [['git','init','-q',str(workspace)],['git','-C',str(workspace),'add','README.md'],['git','-C',str(workspace),'-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-qm','Initialize clock demo']]: subprocess.run(args,check=True)
    cli('project','add',str(workspace),'--title','Clock demo')
elif action == 'pair':
    result=cli('auth','pairing','create','--base-url',f'http://{host}:{port}','--ttl','15m','--label','scenario',skew=True)
    url=next(line[len('Pair URL: '):] for line in (result.stdout+result.stderr).splitlines() if line.startswith('Pair URL: '))
    link='t3code-dev://connections/new?'+urllib.parse.urlencode(dict(pairingUrl=url,autoConnect='1'))
    subprocess.run(['agent-device','open','com.t3tools.t3code.dev',link,'--session',rest[0]],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
elif action == 'turn':
    print(cli('thread','start',str(workspace),'Measure elapsed work','--title','Clock measurement','--provider','devReplay','--model','showcase','--json').stdout)
