import json,os,pathlib,signal,subprocess,sys,time
checkout=pathlib.Path(sys.argv[1]).resolve(); session=sys.argv[2]; output=pathlib.Path(sys.argv[3]); port=sys.argv[4]
output.mkdir(parents=True,exist_ok=True)
started=time.monotonic(); transcript=[]
def device(*args,check=True):
    result=subprocess.run(['agent-device',*args,'--session',session],cwd=checkout,text=True,capture_output=True)
    transcript.append({'seconds':round(time.monotonic()-started,2),'action':' '.join(args[:2]),'exitCode':result.returncode})
    if check and result.returncode:raise RuntimeError(result.stdout+result.stderr)
    return result.stdout+result.stderr

def capture(label):
    subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('stable_capture.py')),str(output/(label+'.png')),session],cwd=checkout,check=True)

runtime=json.loads((checkout/'.t3/manual/userdata/server-runtime.json').read_text())
pid=runtime['pid']
if not pathlib.Path(os.readlink(f'/proc/{pid}/cwd')).is_relative_to(checkout):raise RuntimeError('Wrong server checkout')
device('wait','label="Fork from this response"','60000')
device('record','start',str(output/'fork-failure.mp4'))
try:
    device('snapshot','-i')
    os.kill(pid,signal.SIGSTOP)
    subprocess.run(['sudo','-n','iptables','-I','INPUT','-p','tcp','--dport',port,'-j','REJECT','--reject-with','tcp-reset'],check=True)
    subprocess.run(['sudo','-n','ss','-K','sport','=',':'+port],check=True,capture_output=True)
    device('wait','stable','500','10000')
    device('snapshot','-i')
    for number in [1,2]:
        device('click','label="Fork from this response"','--settle')
        device('wait','stable','500','10000')
        snapshot=device('snapshot')
        (output/f'failed-fork-{number}.txt').write_text(snapshot)
        if number==1 and 'Could not confirm fork' in snapshot:
            device('click','text="OK"','--settle')
    device('wait','stable','500','10000')
finally:
    (output/'record-result.txt').write_text(device('record','stop',check=False))
    subprocess.run(['sudo','-n','iptables','-D','INPUT','-p','tcp','--dport',port,'-j','REJECT','--reject-with','tcp-reset'],check=False)
    os.kill(pid,signal.SIGCONT)
    (output/'actions.json').write_text(json.dumps(transcript,indent=2))
print('Recorded disconnected fork attempts; backend resumed.')
