#!/usr/bin/env python3
"""Real-app proof driver. FORGEJO_PROOF_DIR is scratch; T3_PROOF_CHECKOUT is the commit's checkout.
prepare <base|head>; start that checkout's scripts/scenarios/start-app.ts using the printed home;
seed; signin; after 65 seconds: list; number; unlink; url; fresh; missing.
The active agent is T3's existing recorded Replay question, never a substitute forge or CLI.
"""
import os,sys,json,pathlib,subprocess,urllib.request,uuid,time,datetime
p=pathlib.Path(os.environ['FORGEJO_PROOF_DIR']);checkout=pathlib.Path(os.environ['T3_PROOF_CHECKOUT'])
action=sys.argv[1]
def sh(args,**kw):
 r=subprocess.run(args,cwd=checkout,env=os.environ,capture_output=True,text=True,**kw)
 if r.returncode not in (0,2):raise RuntimeError(r.stderr or r.stdout)
 return r.stdout.strip()
def save(path,data):path.write_text(json.dumps(data,indent=2)+'\n')
if action=='prepare':
 side=sys.argv[2];run=p/f'manual-{side}-{int(time.time())}';run.mkdir();(p/'manual-current').write_text(str(run))
 for name,path in [('gt',p/'auth/gt'),('fj',p/'auth/fj/forgejo-cli')]:
  if path.exists():path.rename(run/f'{name}-previous')
  path.mkdir(parents=True)
 sha=sh(['git','rev-parse','HEAD']);save(p/'proof-current.json',{'sha':sha})
 sh(['git','clone','--quiet','ssh://git@localhost:12285/acme/project.git',str(run/'project')])
 save(run/'state.json',{'side':side,'sha':sha,'home':str(run/'home'),'checkout':str(checkout)})
 print(run/'home');sys.exit(0)
run=pathlib.Path((p/'manual-current').read_text());state=json.loads((run/'state.json').read_text());home=pathlib.Path(state['home'])
def cli(*args):return sh(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)])
def origin():return json.loads((home/'userdata/server-runtime.json').read_text())['origin']
def api(path,data=None):
 headers={'authorization':'Bearer '+(run/'api-auth').read_text(),'content-type':'application/json'}
 req=urllib.request.Request(origin()+path,data=json.dumps(data).encode() if data is not None else None,headers=headers)
 return json.load(urllib.request.urlopen(req))
def record(kind,value):
 with (run/'transcript.jsonl').open('a') as f:f.write(json.dumps({'time':datetime.datetime.now(datetime.timezone.utc).isoformat(),'action':kind,'value':value})+'\n')
def mcp(name,args):
 auth=(run/'mcp-auth').read_text();sid=None
 def send(method,params,id):
  nonlocal sid
  headers={'Authorization':auth,'Content-Type':'application/json','Accept':'application/json, text/event-stream','MCP-Protocol-Version':'2025-06-18'}
  if sid:headers['Mcp-Session-Id']=sid
  r=urllib.request.urlopen(urllib.request.Request(origin()+'/mcp',data=json.dumps({'jsonrpc':'2.0','id':id,'method':method,'params':params}).encode(),headers=headers))
  sid=r.headers.get('Mcp-Session-Id') or sid;data=r.read().decode()
  if data.startswith('event:') or data.startswith('data:'):
   values=[json.loads(line[5:].strip()) for line in data.splitlines() if line.startswith('data:')]
   return next(v for v in values if v.get('id')==id)
  return json.loads(data)
 send('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'forgejo-proof','version':'1'}},1)
 full={'projectId':state['projectId'],**args}
 if name not in ('list_issues',):full['threadId']=state['threadId']
 result=send('tools/call',{'name':name,'arguments':full},2)
 record(name,{'arguments':args,'response':result});print(json.dumps(result,indent=2));return result
if action=='seed':
 (run/'api-auth').write_text(cli('auth','session','issue','--token-only'))
 existing=next((v for v in api('/api/projects')['projects'] if v['workspaceRoot']==str(run/'project')),None)
 projectId=existing['id'] if existing else str(uuid.uuid4())
 if existing is None:api('/api/projects/mutate',{'type':'project.create','commandId':str(uuid.uuid4()),'projectId':projectId,'title':'project','workspaceRoot':str(run/'project')})
 # The app's provider catalog has finished its startup scan by the time the paired browser opens.
 launched=json.loads(cli('thread','start',str(run/'project'),'Check the existing Forgejo issue.','--title','Attach existing Forgejo issue','--provider','devReplay','--model','question','--wait','--json'))
 state.update(projectId=projectId,threadId=launched['threadId'])
 for proc in pathlib.Path('/proc').iterdir():
  if not proc.name.isdigit():continue
  try:
   cmd=(proc/'cmdline').read_bytes().decode()
   if str(checkout/'apps/server/scripts/dev-replay-agent.ts') not in cmd:continue
   env=dict(v.split('=',1) for v in (proc/'environ').read_bytes().decode().split('\0') if '=' in v)
   if env.get('T3CODE_THREAD_ID')==state['threadId']:(run/'mcp-auth').write_text(env['T3_ACP_MCP_AUTHORIZATION'])
  except (FileNotFoundError,PermissionError,ProcessLookupError):continue
 if not (run/'mcp-auth').exists():raise RuntimeError('Real Replay process credential not found')
 save(run/'state.json',state);record('seed',{'sha':state['sha'],'projectId':projectId,'threadId':state['threadId'],'agent':'Replay question remains active','gitRemote':sh(['git','-C',str(run/'project'),'remote','get-url','origin'])})
 print(json.dumps({'projectId':projectId,'threadId':state['threadId']}))
elif action=='resume':
 launched=json.loads(cli('thread','send',state['threadId'],'Check the existing Forgejo issue.','--wait','--json'))
 for proc in pathlib.Path('/proc').iterdir():
  if not proc.name.isdigit():continue
  try:
   cmd=(proc/'cmdline').read_bytes().decode()
   if str(checkout/'apps/server/scripts/dev-replay-agent.ts') not in cmd:continue
   env=dict(v.split('=',1) for v in (proc/'environ').read_bytes().decode().split('\0') if '=' in v)
   if env.get('T3CODE_THREAD_ID')==state['threadId']:(run/'mcp-auth').write_text(env['T3_ACP_MCP_AUTHORIZATION'])
  except (FileNotFoundError,PermissionError,ProcessLookupError):continue
 record('resume',{'agent':'Replay question remains active after server restart'})
 print('Resumed the recorded Replay question.')
elif action=='signin':
 token=(p/'token').read_text().strip();web='http://localhost:13885'
 sh(['gt','auth','login','--host',web,'--with-token','--credential-store','file','--yes'],input=token)
 sh(['gt','config','set','ssh_host','localhost','--host',web]);sh(['fj','-H',web,'auth','add-token'],input=token)
 record('account',{'gt':json.loads(sh(['gt','auth','status','--json','host,user,active'])),'fjWhoami':sh(['fj','--host',web,'whoami'])})
 state['signedInAt']=time.time();save(run/'state.json',state);print('Signed in; allow the negative identity cache 65 seconds.')
elif action=='list':mcp('list_issues',{})
elif action=='number':mcp('link_issue',{'key':'1'})
elif action=='unlink':mcp('unlink_issue',{'key':'1'})
elif action=='url':mcp('link_issue',{'url':'http://localhost:13885/acme/project/issues/1'})
elif action=='fresh':
 sh(['git','clone','--quiet','ssh://git@localhost:12285/acme/project.git',str(run/'fresh')]);freshId=str(uuid.uuid4());api('/api/projects/mutate',{'type':'project.create','commandId':str(uuid.uuid4()),'projectId':freshId,'title':'fresh SSH discovery','workspaceRoot':str(run/'fresh')});record('fresh',{'projectId':freshId});print('Fresh SSH project added.')
elif action=='missing':
 for name,path in [('gt',p/'auth/gt'),('fj',p/'auth/fj/forgejo-cli')]:path.rename(run/f'{name}-signed-in');path.mkdir(parents=True)
 mcp('link_issue',{'key':'1'})
elif action=='state':print(json.dumps(state))
else:raise ValueError(action)
