#!/usr/bin/env python3
"""Read-only inspection of real T3 projections; never inserts or changes state.
Usage: python3 inspect-searches.py SIDE [DATABASE]
Without DATABASE, reads the local .evidence-databases.json mapping.
"""
import json,sqlite3,sys,pathlib
side=sys.argv[1]
db=sys.argv[2] if len(sys.argv)>2 and sys.argv[2]!='--json' else json.loads(pathlib.Path('.evidence-databases.json').read_text())[side]
c=sqlite3.connect('file:'+str(pathlib.Path(db).resolve())+'?mode=ro',uri=True)
print('REAL SERVER PERSISTED SEARCHES | '+side.upper())
print('Read-only SQLite | real Codex adapter + deterministic stdio subprocess')
print('CASE         PARENT       SEARCH       ITEM         NODE         ITEM completedAt          NODE completedAt')
rows=c.execute('''select t.title,r.status,i.payload_json,n.payload_json
from orchestration_v2_projection_turn_items i
join orchestration_v2_projection_threads t using(thread_id)
join orchestration_v2_projection_runs r using(run_id)
join orchestration_v2_projection_nodes n on n.node_id=i.node_id
where i.type='web_search' and t.title like 'Evidence - %'
order by r.requested_at,i.ordinal''').fetchall()
results=[]
for title,run,payload,node in rows:
 i=json.loads(payload); n=json.loads(node)
 name='control' if 'completed control query' in i['patterns'] else 'unfinished'
 print('%-12s %-12s %-12s %-12s %-12s %-25s %s'%(title.removeprefix('Evidence - '),run,name,i['status'],n['status'],i['completedAt'] or 'NULL',n['completedAt'] or 'NULL'))
 results.append(dict(case=title.removeprefix('Evidence - '),runStatus=run,search=name,item=i,node=n))
if '--json' in sys.argv: print(json.dumps(results,indent=2))
