import subprocess, json, re, os
S="real/swan10.mp4"
def run(cmd):
    p=subprocess.run(cmd,shell=True,capture_output=True,text=True); return p.returncode,p.stdout+p.stderr
def psnr(a,b,filt=""):
    rc,o=run(f"ffmpeg -hide_banner -i {a} -i {b} -lavfi \"{filt}psnr\" -f null - 2>&1 | grep -o \"average:[a-z0-9.]*\" | tail -1")
    return o.strip() or "n/a"
runs={}
for l in open("work/tool-runs.jsonl"):
    if l.startswith("{"):
        try: d=json.loads(l.split("\n")[0]); runs[d["tag"]]=d
        except Exception: pass
# tool_odd line was cut in display only; reparse safely
print("tool runs parsed:",sorted(runs))
for tag,d in sorted(runs.items()):
    w,h,x,y=[int(v) for v in d["fields_xywh_order"]]
    m=re.search(r"OUTPUT SIZE (\d+) × (\d+)",d["readout"]); W,H=int(m[1]),int(m[2])
    ox=x//2*2; oy=y//2*2
    rc,_=run(f"ffmpeg -y -v error -i {S} -vf crop={W}:{H}:{ox}:{oy} -an -c:v libx264 -crf 0 -pix_fmt yuv420p work/ref_{tag}.mp4")
    exact=psnr("work/tool_%s.mp4"%tag,"work/ref_%s.mp4"%tag)
    rc,o=run(f"ffmpeg -y -v error -i {S} -vf crop={W}:{H}:{(ox+40) if ox+40+W<=1920 else max(0,ox-40)}:{oy} -an -c:v libx264 -crf 0 -pix_fmt yuv420p work/shift_{tag}.mp4")
    shifted=psnr("work/tool_%s.mp4"%tag,"work/shift_%s.mp4"%tag)
    print(f"{tag}: box requested {w}x{h}+{x}+{y} -> out {W}x{H} at {ox},{oy}; PSNR vs exact crop {exact}; PSNR vs 40px-shifted control {shifted}; bytes {d[chr(98)+chr(121)+chr(116)+chr(101)+chr(115)]}")
# self-compare control
print("control self-compare:",psnr("work/ref_mid.mp4","work/ref_mid.mp4"))
# source-vs-source-encoded baseline: how much loss does a plain re-encode (crf 23) of the same crop cost
run("ffmpeg -y -v error -i real/swan10.mp4 -vf crop=1280:720:320:180 -an -c:v libx264 -crf 23 -pix_fmt yuv420p work/cli_crf23.mp4")
print("ffmpeg CLI crf23 vs lossless crop:",psnr("work/cli_crf23.mp4","work/ref_mid.mp4"), "bytes",os.path.getsize("work/cli_crf23.mp4"))
# audio
for t in ["p916","mid"]:
    rc,o=run(f"ffprobe -v error -select_streams a -show_entries stream=codec_name,duration -of csv=p=0 work/tool_{t}.mp4"); print("audio",t,o.strip())
rc,o=run("ffprobe -v error -select_streams a -show_entries stream=codec_name,duration -of csv=p=0 real/swan10.mp4"); print("audio source",o.strip())
# ffmpeg failure cases
for name,vf in [("odd_dims_h264","crop=1001:555:101:51"),("out_of_range","crop=1920:1080:100:0"),("full_even_ok","crop=1000:554:100:50")]:
    rc,o=run(f"ffmpeg -y -hide_banner -v error -i {S} -t 1 -vf {vf} -c:v libx264 -pix_fmt yuv420p -an work/f_{name}.mp4 2>&1 | tail -2")
    print("ffmpeg",name,vf,"->",o.strip()[:200] or "ok")
rc,o=run("ffmpeg -version | head -1"); print(o.strip())
