import argparse,json,os,pathlib,re,signal,sqlite3,subprocess
p=argparse.ArgumentParser()
p.add_argument('action',choices=['inspect','terminate','status'])
p.add_argument('--checkout',required=True)
p.add_argument('--port',required=True,type=int)
p.add_argument('--thread',required=True)
a=p.parse_args()
root=pathlib.Path(a.checkout).resolve()
conn=sqlite3.connect(f'file:{root}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
conn.row_factory=sqlite3.Row
rows=conn.execute('select * from orchestration_v2_projection_provider_sessions where thread_id=?',(a.thread,)).fetchall()
for r in rows:
 d=dict(r)
 payload=json.loads(d['payload_json'])
 print(json.dumps({'status':d['status'],'lastError':payload.get('lastError'),'activeTurnId':payload.get('activeTurnId')}))
 if a.action=='terminate': assert d['status']=='ready', 'Pi must be idle and ready before termination'
if a.action=='status': raise SystemExit(0)
ss=subprocess.check_output(['ss','-H','-ltnp',f'sport = :{a.port}'],text=True)
server=int(re.search(r'pid=(\d+)',ss).group(1))
assert pathlib.Path(f'/proc/{server}/cwd').resolve()==root/'apps/server'
def descendants(pid):
 children=pathlib.Path(f'/proc/{pid}/task/{pid}/children').read_text().split()
 for c in children:
  yield int(c)
  yield from descendants(int(c))
found=[]
for pid in descendants(server):
 try: argv=pathlib.Path(f'/proc/{pid}/cmdline').read_bytes().decode().split('\0')
 except FileNotFoundError: continue
 if argv[0].strip()=='pi': found.append(pid)
assert len(found)==1, f'Expected exactly one Pi child, got {len(found)}'
print('Verified one Pi RPC descendant of this checkout server.')
if a.action=='terminate':
 os.kill(found[0],signal.SIGTERM)
 print('Sent SIGTERM to idle Pi RPC process.')
