#!/usr/bin/env python3
"""run.py: pad 4 CC0 photos onto 4 canvases with pad-photo.sh, measure the result by pixel scan,
and compare with the Koldflux letterbox calculator (tool-output.txt) and with its published formula.
Usage: run.py <indir> <outdir> <tool-output.txt> <scriptdir>"""
import subprocess, sys, re, os, math
indir, outdir, toolfile, sdir = sys.argv[1:5]
sys.path.insert(0, sdir)
from scan import scan
os.makedirs(outdir, exist_ok=True)
jsround = lambda x: math.floor(x + 0.5)           # JavaScript Math.round
def probe(p):
    o = subprocess.run(["ffprobe","-v","error","-show_entries","stream=width,height","-of","csv=p=0",p],capture_output=True,text=True,check=True).stdout
    return tuple(map(int,o.strip().split(",")))
def formula(w,h,cw,ch):
    s = min(cw/w, ch/h); dw, dh = w*s, h*s
    return dw, dh, (cw-dw)/2, (ch-dh)/2, dw*dh/(cw*ch)*100
tool = {}
for line in open(toolfile):
    m = re.match(r"(\d+x\d+:\d+x\d+) => bar=(.*?) \| scaled=(\d+) × (\d+) \| thickness=(\S+)( px.*?)? \| fills=([\d.]+)%", line)
    if m: tool[m.group(1)] = dict(sw=int(m.group(3)), sh=int(m.group(4)), th=m.group(5), kind=m.group(2), fills=float(m.group(7)))
def ssim(a, b):
    r = subprocess.run(["ffmpeg","-nostdin","-v","info","-i",a,"-i",b,"-lavfi","[0:v][1:v]ssim","-f","null","-"],capture_output=True,text=True)
    m = re.search(r"All:([\d.]+)", r.stderr); return float(m.group(1)) if m else float("nan")
def pad(src, dst, cw, ch):
    subprocess.run([sdir+"/pad-photo.sh", src, dst, str(cw), str(ch)], check=True, capture_output=True)
print("photo | canvas | tool says (scaled, bar px, fills) | ffmpeg measured (content, top/bottom, left/right, fills) | match | ssim whole-photo | ssim 10%-cropped control")
mism = 0; n = 0
photos = sorted(f for f in os.listdir(indir) if f.endswith(".jpg"))
canvases = [(1080,1080),(1080,1350),(1080,1920),(1080,566),(1080,1440)]
for f in photos:
    src = os.path.join(indir,f); w,h = probe(src)
    for cw,ch in canvases:
        key = f"{w}x{h}:{cw}x{ch}"; out = os.path.join(outdir, f"{f[:-4]}-{cw}x{ch}.png")
        pad(src,out,cw,ch)
        ow,oh,t,b,l,r = scan(out)
        assert (ow,oh) == (cw,ch), "output is not the canvas size"
        mw, mh = ow-l-r, oh-t-b
        fills = mw*mh/(cw*ch)*100
        tl = tool[key]
        bar_tool = int(tl["th"])
        bar_meas = t if t else l          # top/bottom or left/right: the thick side
        bar_other = b if t else r
        ok_size = (tl["sw"], tl["sh"]) == (mw, mh)
        ok_bar = bar_tool in (t,b) if t else bar_tool in (l,r) if l else tl["th"] == "none"
        ok_fill = abs(tl["fills"]-fills) < 0.15
        ok = ok_size and ok_bar and ok_fill; n += 1; mism += (not ok)
        # not cropped: the content region equals the whole photo scaled (SSIM), control: 10% of each edge cut off
        crop = out[:-4] + "-content.png"; ref = out[:-4] + "-ref.png"; ctl = out[:-4] + "-ctl.png"
        subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-i",out,"-vf",f"crop={mw}:{mh}:{l}:{t}",crop],check=True)
        subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-i",src,"-vf",f"scale={mw}:{mh}",ref],check=True)
        subprocess.run(["ffmpeg","-nostdin","-v","error","-y","-i",src,"-vf",f"crop=iw*0.8:ih*0.8,scale={mw}:{mh}",ctl],check=True)
        s1, s2 = ssim(crop,ref), ssim(crop,ctl)
        for x in (crop,ref,ctl): os.remove(x)
        print(f"{f[:-4]} {w}x{h} | {cw}x{ch} | {tl['sw']}x{tl['sh']}, {tl['th']}, {tl['fills']}% | {mw}x{mh}, {t}/{b}, {l}/{r}, {fills:.1f}% | {'MATCH' if ok else 'DIFF'}{'' if ok_size else ' size'}{'' if ok_bar else ' bar'}{'' if ok_fill else ' fill'} | {s1:.4f} | {s2:.4f}")
print(f"summary: {n-mism} of {n} photo/canvas pairs match the calculator (scaled size, one bar side, fill within 0.15 points); {mism} differ")
