"""Record real T3 server migration and maintenance, without test mocks or DB writes.
Usage: python3 live-proof.py STOPPED_V1_SQLITE BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_ROOT
Requires node, Xvfb, wish, ffmpeg, sqlite3 and ImageMagick. Each run gets a new directory.
The V1 input must have two completed turns created in t3@0.0.45 and be fully stopped.
"""
import sys,pathlib,subprocess,os,time,sqlite3,shutil,hashlib,json,datetime
source,base,head,out=map(pathlib.Path,sys.argv[1:])
run=out/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');run.mkdir(parents=True)
seed_hash=hashlib.sha256(source.read_bytes()).hexdigest()
viewer=run/'viewer.tcl';view=run/'live.txt';view.write_text('Starting real T3 servers...')
viewer.write_text('''wm title . "T3 SQLite migration proof - live read-only command output"
wm geometry . 1280x800+0+0
wm overrideredirect . 1
text .t -bg "#111827" -fg "#e5e7eb" -font {{DejaVu Sans Mono} 11} -padx 24 -pady 18 -wrap none -borderwidth 0 -highlightthickness 0
pack .t -fill both -expand 1
proc refresh {} {
 set f [open [lindex $::argv 0] r]; set data [read $f]; close $f
 .t delete 1.0 end; .t insert end $data
 after 250 refresh
}
refresh
''')
processes=[];logs={};history={'base':[],'head':[]};latest={};start=time.monotonic()
try:
 xvfb=subprocess.Popen(['Xvfb','-displayfd','1','-screen','0','1280x800x24','-nolisten','tcp'],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True);processes.append(xvfb)
 display=':'+xvfb.stdout.readline().strip();env={**os.environ,'DISPLAY':display}
 ui=subprocess.Popen(['wish',str(viewer),str(view)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);processes.append(ui)
 time.sleep(1)
 if ui.poll() is not None: raise RuntimeError('Console viewer failed to start')
 rec=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1280x800','-framerate','2','-i',display,'-c:v','libx264','-preset','ultrafast','-crf','22','-pix_fmt','yuv420p',str(run/'live-maintenance.mp4')],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=open(run/'ffmpeg.log','w'))
 for side,checkout,port in [('base',base,18371),('head',head,18372)]:
  home=run/side;data=home/'userdata';data.mkdir(parents=True);shutil.copy2(source,data/'state.sqlite')
  raw=run/(side+'-private.log');logs[side]=raw
  child=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--host','127.0.0.1','--port',str(port)],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD':'0'},stdout=open(raw,'w'),stderr=subprocess.STDOUT);processes.append(child)
 print('Recording started',flush=True)
 with open(run/'samples.jsonl','w') as samples:
  for tick in range(43):
   elapsed=round(time.monotonic()-start,1)
   for side in ['base','head']:
    p=run/side/'userdata/statev2.sqlite'
    if not p.exists():continue
    try:
     with sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True) as c:
      row={'side':side,'elapsedSeconds':elapsed,**{k:c.execute('pragma '+k).fetchone()[0] for k in ['auto_vacuum','page_count','freelist_count','page_size']}}
      row['allocatedBytes']=row['page_count']*row['page_size'];row['reclaimableBytes']=row['freelist_count']*row['page_size']
      row['messages']=c.execute('select count(*) from orchestration_v2_projection_messages').fetchone()[0]
      row['v1Unchanged']=hashlib.sha256((run/side/'userdata/state.sqlite').read_bytes()).hexdigest()==seed_hash
      latest[side]=row;history[side].append(row);samples.write(json.dumps(row)+'\n');samples.flush()
    except sqlite3.Error: pass
   lines=['T3 SQLITE MIGRATION - REAL SERVER / LIVE READ-ONLY OBSERVATION',
    'Linux x64 | Node 26.13.1 | identical stopped t3@0.0.45 V1 input',
    'No manual VACUUM, SQL mutation, test clock, or maintenance trigger.',
    '',f'Elapsed: {elapsed:6.1f}s     Sampling: 5s     Page size: 4096 bytes',
    'BEFORE: ed101ef641                  AFTER: 8b1156cd1a','']
   for key,label in [('auto_vacuum','auto_vacuum'),('page_count','page_count'),('freelist_count','freelist_count'),('allocatedBytes','allocated bytes'),('reclaimableBytes','free bytes'),('messages','migrated messages'),('v1Unchanged','V1 hash unchanged')]:
    lines.append(f'{label:20s} {str(latest.get("base",{}).get(key,"starting")):>12s}    |    {str(latest.get("head",{}).get(key,"starting")):>12s}')
   lines+=['','CAPTURED SERVER LOG EVENTS (paths and pairing credentials omitted)']
   for side in ['base','head']:
    ls=logs[side].read_text().splitlines()
    for i,l in enumerate(ls):
     if any(t in l for t in ['Imported legacy v1 thread shells','Hydrated legacy v1 thread transcripts','Compacted orchestration history']):
      lines.append(side.upper()+': '+l[l.find('INFO'):])
      for detail in ls[i+1:i+7]:
       if any(t in detail for t in ['importedThreadCount','deletedEventCount','deletedReceiptCount','reclaimableBytes']):lines.append('  '+detail.strip())
   lines+=['','SAMPLE HISTORY: elapsed / base pages,free / head pages,free']
   for b,h in list(zip(history['base'],history['head']))[-5:]:lines.append(f'{b["elapsedSeconds"]:6.1f}s    {b["page_count"]:4d}, {b["freelist_count"]:2d}              {h["page_count"]:4d}, {h["freelist_count"]:2d}')
   view.write_text('\n'.join(lines));print(json.dumps({'elapsedSeconds':elapsed,'base':latest.get('base'),'head':latest.get('head')}),flush=True)
   time.sleep(5)
 # Two stable stills, 500ms apart.
 subprocess.run(['import','-display',display,'-window','root',str(run/'metrics-a.png')],check=True);time.sleep(.5)
 subprocess.run(['import','-display',display,'-window','root',str(run/'metrics-b.png')],check=True)
 rec.communicate(input=b'q',timeout=15)
 for side in ['base','head']:
  lines=logs[side].read_text().splitlines();safe=[]
  for i,l in enumerate(lines):
   if any(t in l for t in ['Imported legacy v1 thread shells','Hydrated legacy v1 thread transcripts','Compacted orchestration history']):
    safe.append(l)
    for detail in lines[i+1:i+7]:
     if any(t in detail for t in ['importedThreadCount','deletedEventCount','deletedReceiptCount','reclaimableBytes']):safe.append(detail)
  (run/(side+'-events.txt')).write_text('\n'.join(safe)+'\n')
 print('Finished recording',flush=True)
finally:
 if 'rec' in locals() and rec.poll() is None:rec.communicate(input=b'q',timeout=15)
 for p in reversed(processes):
  if p.poll() is None:
   p.terminate()
   try:p.wait(timeout=15)
   except subprocess.TimeoutExpired:p.kill();p.wait()
print(run,flush=True)
