#!/usr/bin/env python3
"""Package the complete capture; label final stills by their actual export time.
Usage: python3 finalize.py DRIVER RUN_DIRECTORY ARTIFACT_DIRECTORY
"""
import ast, pathlib,sys,json,collections,time,shutil,math
from PIL import Image,ImageDraw,ImageFont
source=pathlib.Path(sys.argv[1]); root=pathlib.Path(sys.argv[2]); out=pathlib.Path(sys.argv[3]); out.mkdir(exist_ok=True)
nodes=[]
for node in ast.parse(source.read_text()).body:
 if isinstance(node,ast.FunctionDef) and node.name in ['f','stats','render']: nodes.append(node)
 if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id in ['TARGETS','font','mono'] for t in node.targets): nodes.append(node)
exec(compile(ast.Module(body=nodes,type_ignores=[]),'<renderer>','exec'))
metadata={}
for side,sha in [('before','b4d93997eb707075b105ae35280bfc5f71e53224'),('after','737f8d290853ca26efa28a7df2d69e80e7a07e92')]:
 d=root/side
 rows=[json.loads(l) for l in (d/'trace-structure.ndjson').read_text().splitlines()]
 elapsed=math.ceil((d/'trace-structure.ndjson').stat().st_mtime-(d/'frames/0000.png').stat().st_mtime)
 render({'side':side,'sha':sha},elapsed,rows,out/f'{side}-debug.png')
 time.sleep(.5)
 render({'side':side,'sha':sha},elapsed,rows,out/f'{side}-debug-stability.png')
 assert (out/f'{side}-debug.png').read_bytes()==(out/f'{side}-debug-stability.png').read_bytes()
 for src,dst in [('trace-growth.mp4',f'{side}-debug.mp4'),('trace-structure.ndjson',f'{side}-trace-structure.ndjson'),('requests.json',f'{side}-requests.json')]: shutil.copyfile(d/src,out/dst)
 state=json.loads((d/'claude-outcome.json').read_text())
 state['messages']=[{k:v for k,v in m.items() if k in ['role','text']} for m in state['messages']]
 (out/f'{side}-claude-outcome.json').write_text(json.dumps(state,indent=2))
 metadata[side]={'recordedSeconds':195,'playbackSpeed':10,'finalStillSecondsAfterMonitorStart':elapsed,'viewport':'1920x1080','traceMinLevel':'Debug','freshDatabase':True,'XDG_RUNTIME_DIR':'unset','claudeModel':'claude-haiku-5-5'}
 target_rows=[r for r in rows if r['name'] in TARGETS]
 metadata[side]['allTargetSpans']={'spans':len(target_rows),'traces':len({r['traceId'] for r in target_rows}),'roots':sum(not r.get('parentSpanId') for r in target_rows)}
 (out/f'{side}-summary.json').write_text(json.dumps(stats(rows),indent=2))
(out/'capture-timing.json').write_text(json.dumps(metadata,indent=2))
for name in ['analysis.json']: shutil.copyfile(root/name,out/name)
print(json.dumps(metadata,indent=2))
