"""Add an environment label and timestamped input captions to an unedited capture."""
import json
import pathlib
import subprocess
import sys

root = pathlib.Path(sys.argv[1])
data = json.loads((root / 'observations.json').read_text())
duration = float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',str(root/'interaction.mp4')]))
def timestamp(seconds):
    n = round(seconds * 100)
    return f'{n//360000}:{n//6000%60:02}:{n//100%60:02}.{n%100:02}'
header = '''[Script Info]
ScriptType: v4.00+
PlayResX: 1440
PlayResY: 1020
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Header,DejaVu Sans,22,&H00FFFFFF,&H00FFFFFF,&H00181818,&H00181818,0,0,0,0,100,100,0,0,1,0,0,8,16,16,12,1
Style: Action,DejaVu Sans,22,&H00FFFFFF,&H00FFFFFF,&H00181818,&H00181818,0,0,0,0,100,100,0,0,1,0,0,2,16,16,14,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
'''
lines = [header]
label = f'{data["side"].upper()} | {data["sha"][:10]} | Linux desktop / Electron 44 | 1440 x 900 | Light theme'
lines.append(f'Dialogue: 0,0:00:00.00,{timestamp(duration)},Header,,0,0,0,,{label}\n')
for i, step in enumerate(data['steps']):
    end = data['steps'][i+1]['seconds'] if i+1 < len(data['steps']) else duration
    text = step['name'].replace('markdown','Markdown').replace('html','HTML').replace('-', ' ')
    lines.append(f'Dialogue: 0,{timestamp(step["seconds"])},{timestamp(end)},Action,,0,0,0,,{text}\n')
(root/'captions.ass').write_text(''.join(lines))
subprocess.run(['ffmpeg','-y','-i',str(root/'interaction.mp4'),'-vf',f'pad=1440:1020:0:60:color=0x181818,ass={root / "captions.ass"}', '-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(root/(data['side']+'-desktop-search.mp4'))],check=True)
