#!/usr/bin/env python3
import sys,os,json,time,sqlite3,subprocess,urllib.parse,urllib.request,signal,re
from pathlib import Path
ROOT=Path(__file__).parent
SIDE=sys.argv[2]
WT=Path(os.environ['PROOF_BASE_DIR' if SIDE=='base' else 'PROOF_HEAD_DIR'])
DB=WT/'.t3/userdata/statev2.sqlite'
PORT=6815 if SIDE=='base' else 8023
SERVER=json.loads((WT/'.t3/userdata/server-runtime.json').read_text())['origin']
ENV=json.load(urllib.request.urlopen(SERVER+'/.well-known/t3/environment'))['environmentId']
WEB=os.environ.get('PROOF_BASE_WEB_URL' if SIDE=='base' else 'PROOF_HEAD_WEB_URL',f'http://localhost:{PORT}')
def rows(table,where='',args=()):
 with sqlite3.connect(f'file:{DB}?mode=ro',uri=True) as db:
  return [json.loads(r[0]) for r in db.execute('select payload_json from '+table+(' where '+where if where else ''),args)]
def cli(args,prompt=None):
 r=subprocess.run(['node','apps/server/src/bin.ts','thread',*args,'--base-dir','.t3','--json'],cwd=WT,input=prompt,text=True,capture_output=True)
 if r.returncode: raise RuntimeError(r.stderr+r.stdout)
 return json.loads(r.stdout)
def save(d):
 archive=ROOT/'runs'/str(d.get('startedAt',time.time()));archive.mkdir(parents=True,exist_ok=True)
 (archive/'index.json').write_text(json.dumps(d,indent=2))
 (ROOT/(SIDE+'-'+d['case']+'-index.json')).write_text(json.dumps(d,indent=2))
def load(case):return json.loads((ROOT/(SIDE+'-'+case+'-index.json')).read_text())
def wait(fn,seconds=180):
 end=time.time()+seconds
 while time.time()<end:
  v=fn()
  if v:return v
  time.sleep(.1)
 raise RuntimeError('milestone timeout')
def children(parent):return rows('orchestration_v2_projection_subagents','thread_id=?',(parent,))
def items(child):return rows('orchestration_v2_projection_turn_items','thread_id=?',(child,))
def runs(child):return rows('orchestration_v2_projection_runs','thread_id=?',(child,))
def url(t):return f'{WEB}/{ENV}/{urllib.parse.quote(t,safe="")}'
cmd=sys.argv[1];case=sys.argv[3]
if cmd=='start':
 prompt=(ROOT/('parent-final.txt' if case=='A' else 'parent-'+case+'.txt')).read_text()
 d=cli(['start',str(ROOT/'workspace'),'-','--provider','claudeAgent','--model','claude-haiku-5-5','--title',case+': '+{'A':'normal completion','B':'provider failure','C':'cancel Monitor turn'}[case]],prompt)
 d.update(case=case,side=SIDE,startedAt=time.time());save(d)
 c=wait(lambda:next((x for x in children(d['threadId']) if x['origin']=='app_owned'),None))
 d.update(childThreadId=c['childThreadId'],taskId=c['id']);save(d)
 print(json.dumps({'parent':url(d['threadId']),'child':url(d['childThreadId'])}),flush=True)
elif cmd=='state':
 d=load(case);cs=children(d['threadId']); rs=runs(d['childThreadId']);it=items(d['childThreadId'])
 print(json.dumps({'tasks':[{k:c.get(k) for k in ['status','result','cancelledRunId','completionDelivery']} for c in cs if c['origin']=='app_owned'],'runs':[{k:r.get(k) for k in ['ordinal','status','requestedAt','startedAt','completedAt']} for r in rs],'items':[{k:i.get(k) for k in ['type','toolName','command','text','status','input','failure']} for i in it if i['type'] not in ['reasoning','checkpoint','user_message']],'parentMessages':[m['text'] for m in rows('orchestration_v2_projection_messages','thread_id=?',(d['threadId'],)) if m['role']=='assistant']},indent=2))
elif cmd=='kill':
 d=load(case)
 def stopped():
  rr=runs(d['childThreadId']); second=next((r for r in rr if r['ordinal']==2),None)
  if not second:return None
  ss=[i for i in items(d['childThreadId']) if i['runId']==second['id'] and i.get('toolName')=='TaskStop' and i['status']=='completed']
  return ss if len(ss)==2 else None
 ss=wait(stopped);time.sleep(8)
 spawn=next(x for x in reversed([json.loads(l) for l in (ROOT/'spawns.jsonl').read_text().splitlines()]) if x.get('threadId')==d['childThreadId'])
 pid=spawn['pid'];outcome='already exited'
 try:
  os.kill(pid,0);os.kill(pid,signal.SIGKILL);outcome='SIGKILL sent'
 except ProcessLookupError:pass
 d['intervention']={'type':'SIGKILL','pid':pid,'at':time.time(),'outcome':outcome};save(d);print(outcome,flush=True)
elif cmd=='cancel':
 d=load(case)
 def foreground():
  return next((i for i in items(d['childThreadId']) if i['type']=='command_execution' and i['status']=='running' and 'python3' in str(i)),None)
 wait(foreground)
 reply=cli(['send',d['threadId'],'Cancel the delegated task now with task_cancel using taskId '+d['taskId']+'. This cancellation is authorized. Do not ask questions. Once task_cancel returns, reply exactly PARENT CANCELLED and end this turn. If any later delegated completion notification arrives, report PARENT GOT with its status and reply.'])
 d['intervention']={'type':'task_cancel','at':time.time(),'request':reply};save(d);print('Cancellation requested',flush=True)

elif cmd=='wait-finish':
 d=load(case)
 wait(lambda: all(r['status'] not in ['running','queued','starting','preparing','waiting'] for r in runs(d['childThreadId'])) and all(c['status'] not in ['running','queued','starting','preparing','waiting'] for c in children(d['threadId']) if c['origin']=='app_owned'))
 wait(lambda: len(runs(d['threadId']))>=2 and all(r['status'] not in ['running','queued','starting','preparing','waiting'] for r in runs(d['threadId'])))
 print('Child and parent have finished',flush=True)
elif cmd=='export':
 d=load(case)
 export={'capturedAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'side':SIDE,'case':case,'intervention':{k:v for k,v in d.get('intervention',{}).items() if k!='pid'},'task':children(d['threadId']),'childRuns':runs(d['childThreadId']),'childItems':[i for i in items(d['childThreadId']) if i['type']!='reasoning'],'parentRuns':runs(d['threadId']),'parentTools':[i for i in items(d['threadId']) if i['type']=='dynamic_tool' and i.get('toolName','').endswith(('task_cancel','task_status'))],'parentMessages':rows('orchestration_v2_projection_messages','thread_id=?',(d['threadId'],))}
 raw=json.dumps(export,indent=2)
 for value,replacement in [(str(ROOT),'<proof>'),(str(WT),'<checkout>'),(str(Path.home()),'<home>')]:raw=raw.replace(value,replacement)
 raw=re.sub(r'/tmp/[^\s\"\\]+','<temporary-output>',raw)
 (ROOT/(SIDE+'-'+case+'-runtime.json')).write_text(raw)
 archive=ROOT/'runs'/str(d['startedAt']);archive.mkdir(parents=True,exist_ok=True);(archive/'runtime.json').write_text(raw)
 print('Exported synthetic runtime',flush=True)

elif cmd=='status':
 d=load(case)
 reply=cli(['send',d['threadId'],'Read the cancelled task once with task_status using taskId '+d['taskId']+'. This is an explicit read request, not a completion notification. Reply exactly STATUS: <status> | <reply or result text returned by task_status>. Do not call any other tool except ToolSearch to load task_status.'])
 d['statusRead']={'at':time.time(),'request':reply};save(d);print('Status read requested',flush=True)
