import argparse
import datetime
import json
import pathlib
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('report')
parser.add_argument('output')
args = parser.parse_args()
report = pathlib.Path(args.report)
attempt = next(result for result in json.loads(report.read_text())['run']['results'] if result['attempts'])['attempts'][0]
video = next(artifact for artifact in attempt['artifacts'] if artifact['kind'] == 'video')
source = report.parent / 'results' / video['path']
def stamp(value):
    return datetime.datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
origin = stamp(video['startedAt'])
def seconds(step):
    return stamp(step['startedAt']) - origin
filters = []
for step in attempt['steps']:
    if step['api'] == 'locator.fill' and step.get('label') == 'getByRole("combobox")':
        start = max(0, seconds(step) - 0.5)
        end = seconds(step) + step['durationMs'] / 1000 + 0.8
        filters.append(f"drawbox=x=388:y=82:w=445:h=45:color=0x333333:t=fill:enable='between(t,{start},{end})'")
    if step['api'] == 'locator.fill' and 'PAIRCODE' in step.get('label', ''):
        start = max(0, seconds(step) - 0.5)
        end = seconds(step) + step['durationMs'] / 1000 + 1.0
        filters.append(f"drawbox=x=836:y=447:w=165:h=38:color=0x333333:t=fill:enable='between(t,{start},{end})'")
first = next(step for step in attempt['steps'] if step['api'] == 'locator.tap' and 'New thread in settings-source' in step.get('label', ''))
last = next(step for step in attempt['steps'] if step['api'] == 'app.screenshot' and step.get('label') == '12-environment-retarget-default')
start = max(0, seconds(first) + first["durationMs"] / 1000 - 1.2)
end = seconds(last) + last['durationMs'] / 1000 + 0.1
filters.extend([f'trim=start={start}:end={end}', 'setpts=PTS-STARTPTS'])
subprocess.run(['ffmpeg', '-y', '-v', 'error', '-i', str(source), '-vf', ','.join(filters), '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', args.output], check=True)
print(json.dumps({'start': start, 'end': end, 'output': pathlib.Path(args.output).name}))
