#!/usr/bin/env python3
"""Real-server proof, no unit tests. Usage: driver.py CHECKOUT before|after SCRATCH
Requires official git-lfs 3.4.1 extracted next to this script, vp i in CHECKOUT.
Uses only synthetic random data and fresh server state. Never reads installed T3 state.
"""
import os,sys,time,subprocess,json,threading,hashlib,signal,shutil,re,socket
from pathlib import Path
checkout=Path(sys.argv[1]).resolve(); side=sys.argv[2]; root=Path(sys.argv[3]).resolve()
run=root/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
base=run/'home'; repo=run/'timeout-repo'; good=run/'success-repo'
env=os.environ.copy(); env.update(T3CODE_DEV_SEED='0',GIT_CONFIG_GLOBAL=str(run/'gitconfig'),GIT_CONFIG_NOSYSTEM='1',PROOF_LFS_EVENTS=str(run/'lfs-processes.jsonl'),T3CODE_TELEMETRY_ENABLED='false')
for k in ['T3_SERVICE_LAUNCHER_CONTEXT','T3_BOOT_SERVICE_UNIT','T3CODE_HOME','VITE_HTTP_URL','VITE_WS_URL']: env.pop(k,None)
node=shutil.which('node'); cli=[node,str(checkout/'apps/server/src/bin.ts')]
events=[]; samples=[]; done=threading.Event(); started=time.monotonic(); lock=threading.Lock(); server=None

def clean(s):
 s=re.sub(r'\x1b\[[0-9;]*m','',s)
 for source,target in [(str(run),'$RUN'),(str(root),'$SCRATCH'),(str(checkout),'$CHECKOUT'),(str(Path.home()),'$HOME')]: s=s.replace(source,target)
 s=re.sub(r'(?:pairingUrl:|pairing URL).*','[pairing URL omitted]',s,flags=re.I)
 s=re.sub(r'http://[^\s]*?/pair[^\s]*','[pairing URL omitted]',s)
 return s

def event(text):
 with lock:
  item={'t':round(time.monotonic()-started,3),'message':clean(text)}; events.append(item)
  with open(run/'events.jsonl','a') as f: f.write(json.dumps(item)+'\n')
 print(f"{item['t']:7.2f}s {item['message']}",flush=True)

def cmd(args,cwd=None,secret=False):
 p=subprocess.run(args,cwd=cwd or checkout,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=180)
 if not secret: event('$ '+clean(' '.join(map(str,args)))+'\n'+p.stdout.strip())
 if p.returncode: raise RuntimeError(f'command failed: {p.returncode}: {clean(p.stdout)}')
 return p.stdout.strip()

def git(*args,cwd=repo): return cmd(['git',*args],cwd)
def t3(*args,secret=False): return cmd([*cli,*args,'--base-dir',str(base)],secret=secret)

def init(r):
 r.mkdir(); git('init','-q',cwd=r); git('config','core.hooksPath','/dev/null',cwd=r); git('config','user.name','LFS proof',cwd=r); git('config','user.email','proof@example.invalid',cwd=r)
 (r/'.gitattributes').write_text('*.npz filter=lfs diff=lfs merge=lfs -text\n')
 (r/'README.md').write_text('Synthetic checkpoint proof\n')
 git('add','.gitattributes','README.md',cwd=r); git('commit','-qm','synthetic initial commit',cwd=r)
 (r/'data').mkdir()

def files_at(p):
 result=[]
 if p.exists():
  for f in p.rglob('*'):
   try:
    if f.is_file(): result.append({'path':str(f.relative_to(p)),'bytes':f.stat().st_size})
   except FileNotFoundError: pass
 return result

def measure(r):
 gd=r/'.git'; dirs=list((gd/'objects').glob('tmp_objdir-t3-checkpoint-*'))
 return {'sharedTmp':files_at(gd/'lfs/tmp'),'sharedObjects':files_at(gd/'lfs/objects'),'private':[{ 'directory':d.name,'tmp':files_at(d/'lfs/tmp'),'objects':files_at(d/'lfs/objects')} for d in dirs]}

def monitor():
 while not done.is_set():
  sample={'t':round(time.monotonic()-started,3),'serverAlive':server.poll() is None,'timeout':measure(repo),'success':measure(good)}
  # Only inspect PIDs emitted by our own LFS launcher, never search or signal by name.
  try: procs=[json.loads(l) for l in (run/'lfs-processes.jsonl').read_text().splitlines()]
  except FileNotFoundError: procs=[]
  sample['liveLfsPids']=[]
  for p in procs:
   try:
    stat=Path(f"/proc/{p['pid']}/stat").read_text().split(') ')[1].split()[0]
    if stat!='Z': sample['liveLfsPids'].append(p['pid'])
   except FileNotFoundError: pass
  with lock: samples.append(sample)
  with open(run/'samples.jsonl','a') as f: f.write(json.dumps(sample)+'\n')
  done.wait(.1)

def wait_for(predicate,description,timeout=100):
 until=time.monotonic()+timeout
 while time.monotonic()<until:
  if predicate(): event(description); return
  if server.poll() is not None: raise RuntimeError('server exited')
  time.sleep(.1)
 raise RuntimeError('waiting for '+description)

def count(text):
 with lock: return sum(text in e['message'] for e in events if e['message'].startswith('SERVER:'))

try:
 # A scratch global config applies a genuine Git LFS filter; its launcher only limits CPU duty.
 lfs=root/'git-lfs-3.4.1/git-lfs'; wrapper=root/'lfs-duty.py'
 cmd([str(lfs),'install','--skip-repo'])
 cmd(['git','config','--global','filter.lfs.process',str(wrapper)+' filter-process'])
 cmd(['git','config','--global','filter.lfs.clean',str(wrapper)+' clean -- %f'])
 cmd(['git','config','--global','filter.lfs.smudge',str(wrapper)+' smudge -- %f'])
 init(repo); init(good); (repo/'.git/proof-slow-lfs').write_text('20ms run / 380ms stop\n')
 corpus=root/'corpus'; corpus.mkdir(exist_ok=True)
 for i in range(8):
  f=corpus/f'array-{i}.npz'
  if not f.exists():
   with f.open('wb') as out:
    for _ in range(128): out.write(os.urandom(8*1024*1024))
  if i<6: os.link(f,repo/'data'/f.name)
 small=corpus/'success-sample.npz'
 if not small.exists(): small.write_bytes(os.urandom(1024*1024))
 original=hashlib.sha256(small.read_bytes()).hexdigest()
 event(f'ENV Linux; {cmd(["git","--version"])}; {cmd([str(lfs),"version"])}; genuine LFS process at 5% wall-time duty in timeout repo only; same immutable corpus both sides')
 raw=open(run/'server-raw.log','w')
 sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=str(sock.getsockname()[1]); sock.close()
 server=subprocess.Popen([*cli,'serve','--port',port,'--base-dir',str(base),'--dev-url','http://127.0.0.1:5173'],cwd=checkout,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
 def logs():
  for line in server.stdout:
   raw.write(line); raw.flush()
   if any(t in line for t in ['checkpoint','Listening on','failed','Could not remove']): event('SERVER: '+line.strip())
 threading.Thread(target=logs,daemon=True).start()
 threading.Thread(target=monitor,daemon=True).start()
 state=base/'userdata/server-runtime.json'
 wait_for(state.exists,'fresh real server listening',60)
 t3('project','add',str(repo))
 event('TURN ONE: six untracked 1 GiB random LFS .npz files')
 first=json.loads(t3('thread','start','--provider','devReplay','--model','command-output','--wait','--json',str(repo),'turn one'))
 tid=first['threadId']
 wait_for(lambda:count('checkpoint baseline capture failed')>=1,'observed baseline timeout (5 s)')
 wait_for(lambda:count('orchestration V2 checkpoint capture failed')>=1,'observed turn-one checkpoint timeout (30 s)')
 time.sleep(2)
 event('AFTER FIRST TURN while server running: '+json.dumps(measure(repo)))
 for i in range(6,8): os.link(corpus/f'array-{i}.npz',repo/'data'/f'array-{i}.npz')
 event('TURN TWO: add two more untracked 1 GiB random LFS .npz files')
 t3('thread','send','--wait','--json',tid,'turn two')
 wait_for(lambda:count('orchestration V2 checkpoint capture failed')>=2,'observed turn-two checkpoint timeout (30 s)')
 time.sleep(2)
 event('AFTER SECOND TURN while server running: '+json.dumps(measure(repo)))
 # Successful capture: create a real app-managed isolated worktree, then add a unique payload.
 t3('project','add',str(good))
 event('SUCCESS PATH: isolated worktree, 1 MiB LFS payload; no LFS objects pre-populated')
 branch=git('symbolic-ref','--short','HEAD',cwd=good)
 success=json.loads(t3('thread','start','--provider','devReplay','--model','command-output','--worktree',branch,'--wait','--json',str(good),'setup isolated LFS capture'))
 context={'threadId':success['threadId'],'originalSha256':original,'repo':str(good),'baseDir':str(base),'origin':json.loads(state.read_text())['origin']}
 context_path=run/'success-context.json'; context_path.write_text(json.dumps(context))
 def inspect_success(): return json.loads(cmd([node,str(root/'restore.mjs'),str(checkout),str(context_path),'inspect']))
 info=inspect_success()
 until=time.monotonic()+30
 while not any(c['ordinalWithinScope']==1 and c['status']=='ready' for c in info['checkpoints']):
  if time.monotonic()>until: raise RuntimeError('empty setup checkpoint did not settle')
  time.sleep(.2); info=inspect_success()
 good_work=Path(info['worktreePath']); (good_work/'data').mkdir(exist_ok=True)
 (good_work/'data/sample.npz').write_bytes(small.read_bytes())
 context['repo']=str(good_work); context_path.write_text(json.dumps(context))
 event('SUCCESS PAYLOAD: wrote new 1 MiB LFS file inside the isolated worktree; SHA256 '+original)
 t3('thread','send','--wait','--json',success['threadId'],'capture unique LFS payload')
 wait_for(lambda:len(measure(good)['private'])==0 and len(measure(good)['sharedObjects'])>0,'successful capture published objects and removed private storage')
 info=inspect_success()
 until=time.monotonic()+30
 while not any(c['ordinalWithinScope']==2 and c['status']=='ready' for c in info['checkpoints']):
  if time.monotonic()>until: raise RuntimeError('LFS checkpoint did not settle')
  time.sleep(.2); info=inspect_success()
 refs=git('for-each-ref','--format=%(refname)','refs/t3',cwd=good).splitlines()
 event('SUCCESS checkpoint refs: '+json.dumps(refs))
 # Exercise the app's restore command while its server and filesystem monitor are running.
 git('config','lfs.url','http://127.0.0.1:1/no-network',cwd=good)
 app_restore=json.loads(cmd([node,str(root/'restore.mjs'),str(checkout),str(context_path)]))
 event('APP CHECKPOINT ROLLBACK: '+json.dumps(app_restore))
 (run/'app-restore.json').write_text(json.dumps(app_restore,indent=2))
 # Also restore a saved real-app checkpoint through Git's actual smudge filter, with networking disabled.
 restore_ref=app_restore['checkpointRef']
 pointer=git('show',restore_ref+':data/sample.npz',cwd=good_work)
 event('SAVED CHECKPOINT LFS POINTER: '+pointer)
 (good_work/'data/sample.npz').write_bytes(b'overwritten after capture\n')
 git('-c','lfs.url=http://127.0.0.1:1/no-network','checkout',restore_ref,'--','data/sample.npz',cwd=good_work)
 restored=hashlib.sha256((good_work/'data/sample.npz').read_bytes()).hexdigest()
 event(f'RESTORE via saved app checkpoint and real LFS smudge: expected SHA256 {original}; actual {restored}; match={original==restored}')
 if original!=restored: raise RuntimeError('LFS checkpoint restore bytes differ')
 time.sleep(3)
 summary={'side':side,'sha':cmd(['git','rev-parse','HEAD']),'baselineTimeouts':count('checkpoint baseline capture failed'),'checkpointTimeouts':count('orchestration V2 checkpoint capture failed'),'finalTimeoutRepo':measure(repo),'finalSuccessRepo':measure(good),'appRestore':app_restore,'restoredHashMatches':original==restored,'serverAliveAtFinalMeasurement':server.poll() is None}
 (run/'summary.json').write_text(json.dumps(summary,indent=2)); event('FINAL WHILE SERVER RUNNING: '+json.dumps(summary))
except Exception as e:
 event('ERROR: '+str(e)); raise
finally:
 done.set()
 if server is not None:
  server.terminate()
  try: server.wait(timeout=20)
  except subprocess.TimeoutExpired: server.kill(); server.wait()
 event('server stopped after all evidence measurements')
 (run/'events.json').write_text(json.dumps(events,indent=2)); (run/'samples.json').write_text(json.dumps(samples))
 print('RUN_DIRECTORY='+str(run),flush=True)
