"""Allowlist extraction; never publish raw provider logs or arbitrary message text."""
import json
from pathlib import Path

ROOT = Path('/home/ubuntu/wt/issue-24460')
OUT = Path('/tmp/issue-24460/evidence')
CASES = [
 ('before', '8176b58931', 'events.thread-project-76373805-4b82-4e2f-81d6-493afacddee5-b52b97ec-c54f-4a0f-9bb4-a842.log', '01a16f90-798c-7a43-b5d9-36278ca5448a'),
 ('after', '325c7af9f4470e224124fa703507ec6471c11473', 'events.fdddf73c-5ac8-4bc3-ac96-4a1e7711c411.log', '01a16f96-fd88-70c2-bd6b-56a3a398c05d'),
]
for label, sha, filename, fork_id in CASES:
 rows = []
 for line in (ROOT / '.t3/userdata/logs/provider' / filename).read_text().splitlines():
  if ' NTIVE: ' not in line: continue
  obj = json.loads(line.split(' NTIVE: ', 1)[1])
  event = obj.get('event', {})
  if event.get('stage') != 'decoded': continue
  rows.append((line[1:25], event.get('direction'), event.get('payload', {})))
 result = [{'case':label, 'codeSha':sha, 'environment':'Linux x86_64; real dev web app; Chromium; Codex CLI 0.163.0', 'protocol':'codex.app-server'}]
 seen = set()
 for timestamp, direction, p in rows:
  clean = None
  if direction == 'outgoing' and p.get('method') == 'thread/fork' and p.get('id') == 4:
   params = p['params']
   clean = {'id':4, 'method':'thread/fork', 'params':{k:params[k] for k in ('excludeTurns','lastTurnId','model','threadId') if k in params}}
  elif direction == 'incoming' and p.get('id') == 4 and p.get('result',{}).get('thread',{}).get('id') == fork_id:
   thread = p['result']['thread']
   turns = thread.get('turns', [])
   clean = {'id':4, 'result':{'thread':{'id':fork_id, 'turnCount':len(turns), 'turns':[{'id':t['id'], 'status':t.get('status'), 'markerPresent':any(i.get('text') == 'FORK-CONTEXT-24460' for i in t.get('items',[]))} for t in turns]}}}
  elif p.get('method') == 'turn/completed' and p.get('params',{}).get('threadId') == fork_id:
   turn = p['params']['turn']
   markers = [i['text'] for i in turn.get('items',[]) if i.get('type') == 'agentMessage' and i.get('text') == 'FORK-CONTEXT-24460']
   if markers: clean = {'method':'turn/completed','params':{'threadId':fork_id,'turn':{'id':turn['id'],'status':turn['status'],'marker':markers[0]}}}
  if clean is not None:
   key = json.dumps(clean, sort_keys=True)
   if key not in seen:
    seen.add(key)
    result.append({'timestamp':timestamp,'direction':direction,'payload':clean})
 assert len(result) == 4, (label, len(result))
 request, response, completed = [r['payload'] for r in result[1:]]
 assert request['id'] == response['id'] == 4
 assert response['result']['thread']['id'] == completed['params']['threadId'] == fork_id
 assert completed['params']['turn']['status'] == 'completed'
 if label == 'after':
  assert request['params']['excludeTurns'] is True
  assert response['result']['thread']['turns'] == []
 else:
  assert 'excludeTurns' not in request['params']
  assert response['result']['thread']['turnCount'] == 1
 (OUT / f'{label}-runtime.ndjson').write_text(''.join(json.dumps(r,sort_keys=True)+'\n' for r in result))
 print(f'{label}: verified fork request id 4, correlated response and completed continuation; {len(result)-1} deduplicated frames')
