import sys,json,subprocess
from pathlib import Path
from datetime import datetime
mode, source, destination, side, sha = sys.argv[1:]
if mode == "web":
 report=json.loads(Path(source).read_text())
 attempt=next(r for r in report["run"]["results"] if r["status"] in ["passed","failed"])["attempts"][0]
 video=next(a for a in attempt["artifacts"] if a["kind"]=="video")
 step=next(s for s in attempt["steps"] if s["api"]=="browser.keyboard.press" and s["label"]=="Control+d")
 dt=lambda s:datetime.fromisoformat(s.replace("Z","+00:00"))
 start=(dt(step["startedAt"])-dt(video["startedAt"])).total_seconds()+step["durationMs"]/1000
 original=Path(source).parent/"results"/video["path"]
 args=["-ss",str(start),"-i",str(original)]
 filters=f"crop=540:800:740:0,pad=540:840:0:40:color=white,drawtext=text='Web {side} {sha} - Diff panel':x=12:y=10:fontsize=18:fontcolor=black"
else:
 clips=[Path(source), *sorted(Path(source).parent.glob(Path(source).stem+".part-*.mp4"))]
 args=[part for clip in clips for part in ["-i",str(clip)]]
 filters=f"setpts=PTS/4,pad=1080:2488:0:64:color=white,drawtext=text='Android {side} {sha} - 4x playback':x=24:y=18:fontsize=30:fontcolor=black"
if mode != "web" and len(clips)>1:
 filters="".join(f"[{i}:v]" for i in range(len(clips)))+f"concat=n={len(clips)}:v=1:a=0,"+filters+"[v]"
 filtering=["-filter_complex",filters,"-map","[v]"]
else: filtering=["-vf",filters]
subprocess.run(["ffmpeg","-y",*args,*filtering,"-an","-c:v","libx264","-preset","fast","-crf","22",destination],check=True)
