import os,sys,time,json,socket,select,threading,socketserver,subprocess,pty,signal,pathlib
out=pathlib.Path(sys.argv[1]); out.mkdir(parents=True,exist_ok=True)
root=pathlib.Path(sys.argv[2]); started=time.monotonic(); events=[]; hits=[]; lock=threading.Lock()
def log(s):
 t=time.monotonic()-started
 print(f'{t:6.1f}s {s}',flush=True);events.append([t,s])
class Proxy(socketserver.StreamRequestHandler):
 def handle(self):
  line=self.rfile.readline().decode().strip()
  while self.rfile.readline() not in (b'\r\n',b'\n',b''):pass
  if not line.startswith('CONNECT '):return
  hostport=line.split()[1]; host,port=hostport.rsplit(':',1)
  with lock:hits.append(hostport)
  log('HTTPS CONNECT '+hostport)
  try:
   remote=socket.create_connection((host,int(port)),timeout=10)
   self.wfile.write(b'HTTP/1.1 200 Connection established\r\n\r\n');self.wfile.flush()
   with remote:
    while True:
     readable,_,_=select.select([self.connection,remote],[],[],2)
     for src in readable:
      data=src.recv(65536)
      if not data:return
      (remote if src is self.connection else self.connection).sendall(data)
  except Exception as e:log('Proxy connection ended: '+type(e).__name__)
server=socketserver.ThreadingTCPServer(('127.0.0.1',0),Proxy);server.daemon_threads=True
threading.Thread(target=server.serve_forever,daemon=True).start()
envs={}
for side in ['base','head']:
 target=str(root/(side+'-state'))
 for p in pathlib.Path('/proc').iterdir():
  if not p.name.isdigit():continue
  try:
   cmd=(p/'cmdline').read_bytes().split(b'\0'); raw=(p/'environ').read_bytes()
   if len(cmd)>1 and cmd[1]==b'acp' and target.encode() in raw and b'/agy' in cmd[0]:
    env=dict(x.decode().split('=',1) for x in raw.split(b'\0') if b'=' in x);envs[side]=env;break
  except (OSError,UnicodeError):pass
 if side not in envs:raise RuntimeError('No live T3-spawned agy acp for '+side)
 log(side.upper()+' live T3-spawned agy acp: AGY_CLI_DISABLE_AUTO_UPDATE='+envs[side]['AGY_CLI_DISABLE_AUTO_UPDATE'])
log('Linux x64 / agy '+subprocess.check_output(['agy','--version'],text=True).strip())
log('Each interactive run: inherited ACP environment, fresh HOME, HTTPS logging proxy, 12 seconds in PTY.')
results=[]
for trial in range(1,4):
 for side in ['base','head']:
  run=out/f'{side}-{trial}';run.mkdir();home=run/'home';home.mkdir()
  env=envs[side].copy();env['HOME']=str(home);env['HTTPS_PROXY']=f'http://127.0.0.1:{server.server_address[1]}'
  env['TERM']='xterm-256color'
  log(f'BEGIN {side.upper()} trial {trial}; opt-out={env["AGY_CLI_DISABLE_AUTO_UPDATE"]}; fresh HOME')
  first=len(hits);master,slave=pty.openpty()
  proc=subprocess.Popen(['agy'],env=env,stdin=slave,stdout=slave,stderr=slave,start_new_session=True);os.close(slave)
  data=b'';deadline=time.monotonic()+12
  while time.monotonic()<deadline:
   ready,_,_=select.select([master],[],[],min(.2,max(0,deadline-time.monotonic())))
   if ready:
    try:data+=os.read(master,65536)
    except OSError:break
  os.killpg(proc.pid,signal.SIGTERM);proc.wait(timeout=10);os.close(master)
  (run/'terminal.raw').write_bytes(data)
  contacts=hits[first:];updater=[x for x in contacts if 'antigravity-cli-auto-updater' in x]
  statuses=[]
  for f in home.rglob('update_status.json'):
   statuses.append(json.loads(f.read_text()))
  log(f'END {side.upper()} trial {trial}: updater connections={len(updater)}; update_status='+json.dumps(statuses))
  results.append(dict(side=side,trial=trial,optOut=env['AGY_CLI_DISABLE_AUTO_UPDATE'],contacts=contacts,statuses=statuses))
log('OBSERVED: base updater runs='+str(sum(bool([h for h in r['contacts'] if 'auto-updater' in h]) for r in results if r['side']=='base'))+'/3; head updater runs='+str(sum(bool([h for h in r['contacts'] if 'auto-updater' in h]) for r in results if r['side']=='head'))+'/3')
(out/'observations.json').write_text(json.dumps(results,indent=2));(out/'events.json').write_text(json.dumps(events,indent=2));server.shutdown()
