"""Real Android capture driver. Start on Chats (automatic) or Limits (manual),
with a paired, connected T3 server whose persisted ID is lab,west.
The PID must belong to that isolated server. No responses are substituted:
pausing then terminating it causes a genuine in-flight connection failure.
"""
import argparse, subprocess, os, signal, time, pathlib, datetime
p=argparse.ArgumentParser()
p.add_argument('--pid',type=int,required=True)
p.add_argument('--session',required=True)
p.add_argument('--out',required=True)
p.add_argument('--mode',choices=['automatic','manual'],required=True)
a=p.parse_args()
out=pathlib.Path(a.out);out.mkdir(parents=True,exist_ok=True)
log=[]
def device(*args):
    result=subprocess.run(['agent-device',*args,'--session',a.session],text=True,capture_output=True)
    log.append({'time':datetime.datetime.now(datetime.timezone.utc).isoformat(),'command':['agent-device',*args], 'output':result.stdout,'error':result.stderr,'code':result.returncode})
    if result.returncode: raise RuntimeError(result.stderr)
    return result.stdout
try:
    device('record','start',str(out/'flow.mp4'),'--hide-touches')
    os.kill(a.pid,signal.SIGSTOP)
    if a.mode=='automatic': device('press','text=Usage','--settle')
    else: device('swipe','540','720','540','1660')
    time.sleep(1)
    os.kill(a.pid,signal.SIGKILL)
    time.sleep(4)
    device('snapshot','-i')
    device('screenshot',str(out/'settled-a.png'))
    time.sleep(.5)
    device('screenshot',str(out/'settled-b.png'))
finally:
    device('record','stop')
    # Public transcript omits local artifact paths and session identifiers.
    import json
    public=[]
    for entry in log:
        entry['command']=[s.replace(str(out),'<capture>') for s in entry['command']]
        entry['output']='\n'.join(s for s in entry['output'].splitlines() if not ('Session state:' in s or str(out) in s))
        public.append(entry)
    (out/'interaction.json').write_text(json.dumps(public,indent=2))
