"""Trim runner setup/fixture teardown and caption observed scenario milestones.
Usage: python render-recording.py REPORT RESULTS OUT PLATFORM [shortcuts]
No source frames are removed between the chosen first and last milestones.
"""
import json, sys, subprocess
from pathlib import Path
from datetime import datetime
report, results, out, platform, *options = sys.argv[1:]
x=json.load(open(report))
a=[r for r in x['run']['results'] if r['attempts']][0]['attempts'][0]
v=next(v for v in a['artifacts'] if v['kind']=='video')
time=lambda s: datetime.fromisoformat(s.replace('Z','+00:00')).timestamp()
origin=time(v['startedAt'])
shots=[s for s in a['steps'] if s['api']=='app.screenshot']
first=next(s for s in shots if s['label']=='composer-focused-before-find-shortcut')
last=next(s for s in shots if s['label']==('button-find-shortcut-result' if options else 'final-main-conversation-preserved'))
start=time(first['startedAt'])-origin-0.25
end=time(last['startedAt'])-origin+last['durationMs']/1000
key='Cmd+F' if platform.startswith('macOS') else 'Ctrl+F'
labels={
'composer-focused-before-find-shortcut':f'Composer focused; next: {key}',
'composer-find-shortcut-result':f'After {key} from the side-chat composer',
'conversation-focused-before-find-shortcut':f'Conversation focused; next: {key}',
'conversation-find-shortcut-result':f'After {key} from the side-chat conversation',
'button-focused-before-find-shortcut':f'Add to chat focused (blue outline); next: {key}',
'button-find-shortcut-result':f'After {key} from Add to chat',
'find-input-before-escape':'App find action establishes the same query on BOTH commits; next: Escape',
'escape-input-composer-focus':'After Escape in find input, type: Focus returned to composer',
'escape-conversation-composer-focus':'After Escape in conversation, type: Focus returned to composer',
'settings-with-find-suspended':'Visit Settings with a side-chat query',
'settings-return-retains-find':'Return from Settings: compare query retention',
'narrow-retains-find':'Re-establish query on BOTH commits, then resize to 900px',
'wide-retains-find':'Resize back to 1280px: compare query retention',
'side-chat-tab-closed':'Close the side-chat tab',
'reopened-pane-find-cleared':'Reopen the SAME saved side chat through the app action',
'narrow-before-escape':f'900px: reopen find; next: Escape, then Escape again',
'first-escape-closes-find':'After FIRST Escape at 900px',
'second-escape-closes-sheet':'After SECOND Escape at 900px',
'final-main-conversation-preserved':'Main conversation remains present before harness cleanup',
}
selected=[s for s in shots if time(first['startedAt'])<=time(s['startedAt'])<=time(last['startedAt'])]
def stamp(n):
 n=max(0,round(n*1000));return f'{n//3600000:02}:{n//60000%60:02}:{n//1000%60:02},{n%1000:03}'
subs=[]
for i,s in enumerate(selected):
 begin=max(0,time(s['startedAt'])-origin-start)
 finish=time(selected[i+1]['startedAt'])-origin-start if i+1<len(selected) else end-start+1
 if finish-begin<0.15:continue
 subs.append(f'{i+1}\n{stamp(begin)} --> {stamp(finish)}\n{platform}\n{labels.get(s["label"],s["label"])}\n')
p=Path(out);srt=p.with_suffix('.srt');srt.write_text('\n'.join(subs))
filters=f"trim=duration={end-start},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=1,pad=iw:ih+128:0:0:black,subtitles={srt}:force_style='FontName=DejaVu Sans,FontSize=8,PrimaryColour=&H00FFFFFF,Outline=0,Alignment=2,MarginV=6'"
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-ss',str(start),'-i',str(Path(results)/v['path']),'-t',str(end-start+1),'-vf',filters,'-an','-c:v','libx264','-preset','fast','-crf','18','-pix_fmt','yuv420p',out],check=True)
p.with_suffix('.timing.json').write_text(json.dumps({'start':start,'end':end,'sourceDurationMs':a['durationMs'],'milestones':[s['label'] for s in selected]},indent=2))
print(out)
