import datetime
import json
from remote import ROOT

root=ROOT/'error-evidence/shared'
snap=json.loads((root/'snapshot.json').read_text())
windows=json.loads((root/'trace_windows.json').read_text())
kst=datetime.timezone(datetime.timedelta(hours=9))
def stamp(ms):return datetime.datetime.fromtimestamp(ms/1000,kst).isoformat(timespec='milliseconds')
rows=[]
for camera,data in sorted(snap['detail'].items(),key=lambda x:int(x[0])):
    diagnostic=data['last_cleanup']['diagnostic']
    events={event['name']:event['wall_ms'] for event in diagnostic['events']}
    trace=[x for w in windows if w['window']['camera']==camera for x in w['rows']]
    start=next(w for w in windows if w['window']['camera']==camera and w['window']['event']=='start_requested')
    http=[x for x in start['rows'] if x['doc']['phase']=='HTTP' and x['doc']['component']=='sidecar']
    item=dict(camera=camera,case_id='CTX-ERR-20261101-C'+camera,run_id=data['run_id'],generation=data['run_generation'],
        start_kst=stamp(events['start_requested']),error_kst=stamp(events['first_child_error']),
        elapsed_seconds=round((events['first_child_error']-events['start_requested'])/1000,3),
        first_error=diagnostic['first_error'],final_error=data['last_error'],
        decoded_observations=data['roles']['shared']['stage_counts']['decoded_frame_received'],
        child_reaped=data['last_cleanup']['child_reaped'],child_exit=diagnostic['exit_code'],
        forced=diagnostic['forced'],cleanup_pending=data['cleanup_pending'],child_exception=diagnostic['child_exception'],
        request_id=http[0]['doc']['requestId'] if http else None,
        initial_http=http[0]['doc']['httpStatus'] if http else None,
        initial_result=http[0]['doc']['responseBody'] if http else None,
        trace_sequences=sorted({x['seq'] for x in trace}),
        recorded_stop_requests=sum(x['doc'].get('action')=='stop' for x in trace))
    rows.append(item)
(root/'case_summary.json').write_text(json.dumps(rows,indent=2)+'\n')
print(json.dumps([dict(camera=x['camera'],generation=x['generation'],error=x['error_kst'],seconds=x['elapsed_seconds'],
    stage=x['first_error']['failure_stage'],received=x['decoded_observations'],http=x['initial_http'],stops=x['recorded_stop_requests']) for x in rows],indent=2))
