#!/usr/bin/env python3
"""Run: EVIDENCE_ROOT=... BASE_CHECKOUT=... HEAD_CHECKOUT=... PROBE_MODEL=... python3 prove.py
Requires vp i in both checkouts, real grok on PATH, and grok-probe beside this script.
All model identifiers, server logs, full CLI responses and paths remain private.
Only the allowlisted transcript, cast, summary and source scripts are publishable.
"""
import os,sys,json,time,pathlib,subprocess,datetime,socket,signal,shutil
root=pathlib.Path(os.environ['EVIDENCE_ROOT'])
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
project=root/'synthetic-project'
for side,var,port in [('before','BASE_CHECKOUT',15411),('after','HEAD_CHECKOUT',15412)]:
 checkout=pathlib.Path(os.environ[var]);run=root/(side+'-final-'+stamp);run.mkdir()
 home=checkout/'.t3'/('proof-'+stamp);userdata=home/'userdata';userdata.mkdir(parents=True)
 (userdata/'settings.json').write_text(json.dumps({'providerInstances':{'grok':{'driver':'grok','enabled':True,'config':{'binaryPath':str(root/'grok-probe')}}}}))
 probe=run/'launches.jsonl.threads'
 env=dict(os.environ,T3CODE_DEV_SEED='0',PROBE_OUTPUT=str(run/'launches.jsonl'),REAL_GROK=shutil.which('grok'))
 env.pop('T3CODE_THREAD_ID',None)
 server=subprocess.Popen(['vp','run','dev','--home-dir',str(home),'--port',str(port)],cwd=checkout,env=env,stdout=open(run/'server.private.log','w'),stderr=subprocess.STDOUT,start_new_session=True)
 (run/'server.pid').write_text(str(server.pid))
 start=time.monotonic();events=[];lines=[]
 def emit(s):
  print(s,flush=True);lines.append(s);events.append([round(time.monotonic()-start,3),'o',s.replace('\n','\r\n')+'\r\n'])
 def cli(args,wait=False):
  p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=90)
  (run/('cli-'+str(time.time_ns())+'.private.log')).write_text(p.stdout+'\n'+p.stderr)
  if p.returncode and not wait: raise RuntimeError('CLI failed; inspect private log')
  return p.stdout.strip()
 try:
  emit('Grok ACP process environment | '+side.upper())
  emit('Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip())
  emit('Linux x86_64 | real vp run dev server + source CLI | fresh database')
  emit('T3CODE_DEV_SEED=0 | inherited T3CODE_THREAD_ID unset')
  emit('No browser or device; terminal capture: 1280 x 900, dark theme')
  emit('$ T3CODE_DEV_SEED=0 env -u T3CODE_THREAD_ID vp run dev')
  deadline=time.monotonic()+120
  while True:
   try:
    with socket.create_connection(('127.0.0.1',port),timeout=.5):
     if not (userdata/'server-runtime.json').exists():raise OSError('runtime not ready')
     if 'Listening on' not in (run/'server.private.log').read_text():raise OSError('startup not ready')
     break
   except OSError:
    if time.monotonic()>deadline:raise RuntimeError('Server startup timed out')
    time.sleep(.5)
  emit('Real server listening; fresh database initialized by this commit.')
  emit('$ t3 project add --title "Environment probe" <synthetic-project>')
  cli(['project','add','--title','Environment probe',str(project)])
  emit('Synthetic git project registered; Grok wrapper configured.')
  ids=[];counts=[]
  for i in range(1,3):
   prior=len(probe.read_text().splitlines()) if probe.exists() else 0
   emit('$ t3 thread start --provider grok --model "$PROBE_MODEL" --wait --json')
   emit('  <project> \'echo "TID=[$T3CODE_THREAD_ID]"\'')
   raw=cli(['thread','start','--provider','grok','--model',os.environ['PROBE_MODEL'],'--title','Environment probe '+str(i),'--wait','--json',str(project),'echo "TID=[$T3CODE_THREAD_ID]"'],wait=True)
   data=json.loads(raw);thread=data['threadId'];ids.append(thread)
   emit('Thread '+str(i)+': '+thread)
   records=[json.loads(l) for l in probe.read_text().splitlines()][prior:]
   if not records:raise RuntimeError('No thread ACP process captured')
   counts.append(len(records));emit('Observed '+str(len(records))+' real Grok ACP process launch(es) for this request:')
   tids=sorted(set(str(r['T3CODE_THREAD_ID'] or '<ABSENT>') for r in records))
   emit('  T3CODE_THREAD_ID: '+', '.join(tids))
   emit('  Every launch matches its thread: '+str(all(r['T3CODE_THREAD_ID']==thread for r in records)))
   emit('  GROK_OAUTH2_REFERRER: '+', '.join(sorted(set(r['GROK_OAUTH2_REFERRER'] for r in records))))
   names=sorted(set(k for r in records for k in r['T3_ACP_names']))
   emit('  T3_ACP_* variable names:')
   if names:
    for name in names:emit('    '+name)
   else:emit('    <NONE>')
   emit('  Turn status: '+data['status']+' (ACP authentication-method mismatch)')
  emit('Scope: actual spawn environments proven; completed Grok turn not proven.')
  (run/'transcript.txt').write_text('\n'.join(lines)+'\n')
  with (run/'session.cast').open('w') as f:
   f.write(json.dumps({'version':2,'width':128,'height':50,'timestamp':int(time.time()),'title':'Grok ACP launch evidence '+side})+'\n')
   for e in events:f.write(json.dumps(e)+'\n')
  (run/'summary.json').write_text(json.dumps({'threadIds':ids,'launchCounts':counts,'launches':[json.loads(l) for l in probe.read_text().splitlines()]},indent=2))
  (root/(side+'-final-path')).write_text(str(run))
 finally:
  os.killpg(server.pid,signal.SIGTERM)
  try:server.wait(timeout=20)
  except subprocess.TimeoutExpired:os.killpg(server.pid,signal.SIGKILL);server.wait()
