#!/usr/bin/env python3
"""Run an unmodified T3 server against a synthetic SIGTERM-resistant connector.
Usage: python3 prove.py CHECKOUT OUTPUT_ROOT LABEL
Requires Node, openssl, ffmpeg and Pillow. No test runner or mocked spawner.
"""
import os,sys,json,time,ssl,threading,subprocess,socket,signal,textwrap
from pathlib import Path
from http.server import ThreadingHTTPServer,BaseHTTPRequestHandler
from PIL import Image,ImageDraw,ImageFont
checkout=Path(sys.argv[1]).resolve(); root=Path(sys.argv[2]).resolve(); label=sys.argv[3]
r=root/(label+'-'+str(int(time.time())));r.mkdir(parents=True)
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
def port():
 with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1]
serverport=port()
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(r/'key.pem'),'-out',str(r/'cert.pem'),'-days','1','-subj','/CN=proof.local','-addext','subjectAltName=IP:127.0.0.1'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
start=time.time();events=[];lock=threading.Lock()
def log(msg):
 with lock:
  line=f'{time.time()-start:6.1f}s  {msg}';events.append(line)
  print(line,flush=True)
  with (r/'observations.txt').open('a') as f:f.write(line+'\n')
class Edge(BaseHTTPRequestHandler):
 def log_message(self,*_):pass
 def do_GET(self):
  p=json.loads((r/'spawns.json').read_text()) if (r/'spawns.json').exists() else []
  status=530 if len(p)<2 else 200
  log('Synthetic HTTPS edge: HTTP '+str(status)+(' / error 1033' if status==530 else ' / replacement registered'))
  self.send_response(status);self.end_headers();self.wfile.write(b'{"error_code":1033}' if status==530 else b'{}')
edge=ThreadingHTTPServer(('127.0.0.1',0),Edge);ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.load_cert_chain(r/'cert.pem',r/'key.pem');edge.socket=ctx.wrap_socket(edge.socket,server_side=True)
threading.Thread(target=edge.serve_forever,daemon=True).start()
state=r/'home'/'userdata';secrets=state/'secrets';secrets.mkdir(parents=True)
config={'providerKind':'cloudflare_tunnel','connectorToken':'synthetic-token','tunnelId':'proof-tunnel','tunnelName':'proof-tunnel'}
(secrets/'cloud-endpoint-runtime-config.bin').write_text(json.dumps(config))
(secrets/'cloud-endpoint-confirmed-origin.bin').write_text(json.dumps({'config':config,'origin':{'localHttpHost':'127.0.0.1','localHttpPort':serverport}}))
env=os.environ.copy();env.update(T3CODE_DEV_SEED='0',T3CODE_CLOUDFLARED_PATH=str(Path(__file__).with_name('connector.py')),PROOF_RUN=str(r),PROOF_TLS_PORT=str(edge.server_port),PROOF_SERVER_PORT=str(serverport),NODE_EXTRA_CA_CERTS=str(r/'cert.pem'),TUNNEL_TRANSPORT_PROTOCOL='http2',NO_COLOR='1')
# Avoid inheriting credentials or production relay settings.
for key in list(env):
 if key.startswith(('T3CODE_RELAY','OTEL_','VITE_')):env.pop(key,None)
raw=(r/'server-private.log').open('w')
p=subprocess.Popen(['node','src/bin.ts','serve','--base-dir',str(r/'home'),'--port',str(serverport),'--host','127.0.0.1'],cwd=checkout/'apps/server',env=env,stdout=raw,stderr=subprocess.STDOUT)
log('Linux / Node '+subprocess.check_output(['node','--version'],text=True).strip()+' / real T3 server CLI')
log(label+' commit '+sha[:10]);log('Fresh isolated state; synthetic connector and HTTPS edge; real OS child spawner')
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19);title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',27)
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1280x900','-r','2','-i','-','-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(r/'recording.mp4')],stdin=subprocess.PIPE)
seen=set();raw_seen=set();fixture_seen=0;restart=None;outcome='';lastimg=None
try:
 while time.time()-start<230:
  elapsed=time.time()-start
  logfile=state/'logs'/'relay-client.ndjson'
  if logfile.exists():
   for line in logfile.read_text().splitlines():
    if line in seen:continue
    seen.add(line)
    try:
     entry=json.loads(line);message=entry['message'];message=message[0] if isinstance(message,list) else message
    except Exception:continue
    if any(t in message for t in ['process started','no live connection','exited; restarting','tunnel connection registered','Relay client stopped']):
     log('T3: '+message)
     if 'no live connection' in message and restart is None:restart=time.time()
  for line in (r/'server-private.log').read_text().splitlines():
   if line in raw_seen:continue
   raw_seen.add(line)
   if any(t in line for t in ['Cloudflare has no live connection from the relay client; restarting it','T3 Connect is reachable from other devices.']):
    clean=line.split('): ',1)[-1];log('T3 stdout: '+clean)
    if 'no live connection' in clean and restart is None:restart=time.time()
  fixture=r/'fixture-events.log'
  if fixture.exists():
   lines=fixture.read_text().splitlines()
   for line in lines[fixture_seen:]:log('OS fixture: '+json.loads(line)['message'])
   fixture_seen=len(lines)
  pids=json.loads((r/'spawns.json').read_text()) if (r/'spawns.json').exists() else []
  alive=False
  if pids:
   try:os.kill(pids[0],0);alive=True
   except ProcessLookupError:pass
  if restart and time.time()-restart>=25 and not outcome:
   outcome=('RECOVERED: old PID exited; replacement spawned' if len(pids)>=2 and not alive else 'STUCK: old PID alive; no replacement spawned')
   log(outcome);log('Observation window: 25 seconds after restart request')
  img=Image.new('RGB',(1280,900),'#0c1423');d=ImageDraw.Draw(img)
  d.text((32,22),'T3 Connect | connector restart evidence',font=title,fill='#eaf1ff')
  d.text((32,68),f'{label.upper()}  {sha[:10]}  |  elapsed {elapsed:05.1f}s',font=font,fill='#79c8ff')
  d.text((32,103),'Real server CLI + OS processes; synthetic cloudflared / edge',font=font,fill='#b5c2d8')
  d.text((32,140),f'Spawns: {len(pids)}  |  original process alive: {alive}',font=font,fill='#f6d279')
  if restart:d.text((32,175),f'Since T3 restart request: {time.time()-restart:.1f}s',font=font,fill='#f6d279')
  with lock: displayed=events[-20:]
  y=225
  for line in displayed:
   for wrapped in textwrap.wrap(line,100):d.text((32,y),wrapped,font=font,fill='#d8e2f4');y+=26
  if outcome:d.rectangle((20,821,1260,885),fill='#153b2c' if len(pids)>1 else '#55242c');d.text((32,840),outcome,font=font,fill='white')
  video.stdin.write(img.tobytes());lastimg=img
  if outcome:
   img.save(r/'result.png')
   for _ in range(6):video.stdin.write(img.tobytes())
   break
  if p.poll() is not None:log('Server exited before observation; inspect private startup log');break
  time.sleep(.5)
 if not outcome:log('No complete restart observation within 230 seconds')
 (r/'result.json').write_text(json.dumps({'sha':sha,'outcome':outcome,'spawns':len(pids),'oldAlive':alive,'restartObserved':restart is not None,'elapsed':time.time()-start},indent=2))
finally:
 # Only kill PIDs captured from our spawned connector, then our own server.
 if (r/'spawns.json').exists():
  for pid in json.loads((r/'spawns.json').read_text()):
   try:os.kill(pid,signal.SIGKILL)
   except ProcessLookupError:pass
 p.terminate()
 try:p.wait(timeout=12)
 except subprocess.TimeoutExpired:p.kill();p.wait()
 edge.shutdown();video.stdin.close();video.wait();raw.close()
print('OUTPUT',r,flush=True)
