import datetime as dt
import json
import pathlib
import subprocess
import sys

report_path = pathlib.Path(sys.argv[1])
output_path = pathlib.Path(sys.argv[2])
report = json.loads(report_path.read_text())
attempt = next(r['attempts'][-1] for r in report['run']['results'] if r['attempts'])
video = next(a for a in attempt['artifacts'] if a['kind'] == 'video')
parse = lambda value: dt.datetime.fromisoformat(value.replace('Z', '+00:00'))
start = parse(video['startedAt'])
windows = []
for index, step in enumerate(attempt['steps']):
    if step['api'] != 'app.open' or '/pair' not in step.get('screen', {}).get('location', ''):
        continue
    following = next(s for s in attempt['steps'][index + 1:] if s['api'] == 'expect.not.toHaveURL')
    begin = max(0, (parse(step['startedAt']) - start).total_seconds() - 1)
    end = (parse(following['startedAt']) - start).total_seconds() + following['durationMs'] / 1000 + 1
    windows.append((begin, end))
if windows:
    windows[0] = (0, windows[0][1])
enable = '+'.join(f'between(t,{a:.3f},{b:.3f})' for a, b in windows) or '0'
filters = (
    "drawbox=x=0:y=0:w=iw:h=ih:color=0xf3f4f6:t=fill:enable='" + enable + "',"
    "drawtext=text='Pairing screen hidden':fontcolor=0x374151:fontsize=24:"
    "x=(w-tw)/2:y=(h-th)/2:enable='" + enable + "'"
)
source = report_path.parent / 'results' / video['path']
subprocess.run(['ffmpeg', '-v', 'error', '-i', str(source), '-vf', filters, '-an',
                '-c:v', 'libx264', '-threads', '2', '-preset', 'veryfast', '-crf', '20',
                '-movflags', '+faststart', str(output_path)], check=True)
print(json.dumps({'pairingScreensRedacted': len(windows), 'windowsSeconds': windows}))
