import subprocess as s, os, time, json, re, signal, pathlib, threading, urllib.request
import argparse
a=argparse.ArgumentParser()
a.add_argument('--base-worktree',required=True)
a.add_argument('--head-worktree',required=True)
a.add_argument('--output',required=True)
args=a.parse_args()
ROOT=pathlib.Path(args.output)
run=ROOT/time.strftime('%Y%m%d-%H%M%S'); run.mkdir()
host=json.loads(s.check_output(['tailscale','status','--json']))['Self']['DNSName'].rstrip('.')
events=[]; start=time.monotonic()
def clean(x):
 x=re.sub(r'\x1b\[[0-9;]*[a-zA-Z]','',x).replace(host,'tailnet-host')
 for worktree in (args.base_worktree,args.head_worktree): x=x.replace(worktree,'<worktree>')
 x=re.sub(r'https?://\S*(?:pair|token)\S*','[private pairing URL omitted]',x)
 return x.replace(str(run), '[isolated-run]')

def emit(x):
 x=clean(x); events.append([round(time.monotonic()-start,2),x]); print(x,flush=True)
def cmd(args):
 p=s.run(args,capture_output=True,text=True); return p.stdout+p.stderr
class Handler(__import__('http.server',fromlist=['BaseHTTPRequestHandler']).BaseHTTPRequestHandler):
 def do_GET(self):
  self.send_response(200); self.end_headers(); self.wfile.write(b'<h1>OTHER-APP-ON-9555</h1>')
 def log_message(self,*a): pass
s.run(['sudo','tailscale','set','--operator='+__import__('getpass').getuser()],check=True)
server=__import__('http.server',fromlist=['HTTPServer']).HTTPServer(('127.0.0.1',9555),Handler)
threading.Thread(target=server.serve_forever,daemon=True).start()
def probe(url):
 p=s.run(['curl','--noproxy','*','-ksS','--max-time','8',url],capture_output=True,text=True)
 if p.returncode: return 'Connection failed (curl exit '+str(p.returncode)+')'
 if 'OTHER-APP-ON-9555' in p.stdout:return 'OTHER-APP-ON-9555'
 title=re.search(r'<title>(.*?)</title>',p.stdout)
 return title.group(0) if title else p.stdout[:200]
try:
 for side,sha,path in [('before','9d28fc921be19a7314376f6438242dcb838eb221',args.base_worktree),('after','8753835917bd5d537e3cae9c2cacfff126d3e576',args.head_worktree)]:
  events=[]; start=time.monotonic(); emit(side.upper()+' | commit '+sha[:10]+' | Linux CLI | fresh dev data')
  emit('$ python3 HTTP server on 127.0.0.1:9555\n$ tailscale serve --bg --https=7733 http://127.0.0.1:9555')
  cmd(['tailscale','serve','--bg','--https=7733','http://127.0.0.1:9555'])
  emit('INITIAL ROUTE\n'+cmd(['tailscale','serve','status'])+'HTTPS response: '+probe('https://'+host+':7733/'))
  emit('$ T3CODE_DEV_SEED=0 T3CODE_PORT_OFFSET=2000 vp run dev --share')
  log=open(run/(side+'-raw.log'),'w'); p=s.Popen(['vp','run','dev','--share','--home-dir',str(run/(side+'-data'))],cwd=path,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_PORT_OFFSET':'2000'},stdout=log,stderr=s.STDOUT,start_new_session=True)
  try:
   deadline=time.monotonic()+240
   while time.monotonic()<deadline:
    if p.poll() is not None: break
    if probe('http://localhost:7733/') == '<title>T3 Code (Dev)</title>' and 'Authentication required' in (run/(side+'-raw.log')).read_text():
     time.sleep(3)
     if probe('http://localhost:7733/') == '<title>T3 Code (Dev)</title>': break
    time.sleep(2)
   time.sleep(3)
   raw=(run/(side+'-raw.log')).read_text()
   selected=[x for x in raw.splitlines() if '[dev-runner]' in x and ('mode=' in x or 'share' in x or 'tailnet' in x or 'mapping' in x)]
   emit('DEV RUNNER OUTPUT\n'+'\n'.join(selected))
   emit('WHILE DEV RUNS\n'+cmd(['tailscale','serve','status'])+'HTTPS response: '+probe('https://'+host+':7733/')+'\nLocal dev: '+probe('http://localhost:7733/')+'\nOther app locally: '+probe('http://127.0.0.1:9555/'))
  finally:
   emit('$ SIGINT to captured dev process group')
   os.killpg(p.pid,signal.SIGINT)
   try:p.wait(timeout=30)
   except s.TimeoutExpired:os.killpg(p.pid,signal.SIGTERM);p.wait(timeout=15)
   log.close()
  time.sleep(2)
  emit('AFTER DEV STOPS\n'+cmd(['tailscale','serve','status'])+'HTTPS response: '+probe('https://'+host+':7733/')+'\nOther app locally: '+probe('http://127.0.0.1:9555/'))
  (run/(side+'.json')).write_text(json.dumps(events,indent=2)); (run/(side+'.txt')).write_text('\n\n'.join(e[1] for e in events))
  cmd(['tailscale','serve','--https=7733','--set-path=/','off'])
finally:
 server.shutdown()
 cmd(['tailscale','serve','--https=7733','--set-path=/','off'])
 s.run(['sudo','tailscale','set','--operator='],check=True)
print('ARTIFACT_DIR='+str(run))
