#!/usr/bin/env python3
"""Run quality_scan over camera source files, cache one JSON per FOOTAGE (qcache/<footage>.json).
Sem args: TODOS os footages de media_paths.json. Com `--only <placements.json>`: SÓ os footages
que aquele cut usa (auto_switch/unified só precisam desses ~15, não dos ~317 do casamento todo —
evita decodificar 4K HEVC à toa). Uso: batch_scan.py [--only weddings/<x>/placements.json]"""
import json, os, sys
_only = None
if "--only" in sys.argv:
    _i = sys.argv.index("--only")
    _only = sys.argv[_i + 1]
    del sys.argv[_i:_i + 2]
sys.argv = [sys.argv[0]]            # keep quality_scan import clean
import quality_scan as q

import glob, re as _re
paths = json.load(open("media_paths.json"))
os.makedirs("qcache", exist_ok=True)
SAMPLE_FPS, W = 1.0, 240            # faster than the 2fps/320 default; fine for cut decisions


def decode_src(orig):
    """Pro qcache (análise de qualidade/movimento) usa o SUB proxy 1080p da câmera se existir —
    mesmo conteúdo, decode ~8x mais rápido que o 4K HEVC (medido). qcache continua nomeado pelo
    FOOTAGE original; só o DECODE muda. (Sony/Canon: CLIP/Cxxxx.MP4 <-> SUB/CxxxxS0N.MP4.)"""
    d = os.path.dirname(orig)
    if os.path.basename(d).lower() != "clip":
        return orig
    subdir = os.path.join(os.path.dirname(d), "SUB")
    if not os.path.isdir(subdir):
        # tenta case-insensitive
        cand = [x for x in glob.glob(os.path.join(os.path.dirname(d), "*")) if os.path.basename(x).lower() == "sub"]
        if not cand:
            return orig
        subdir = cand[0]
    stem = os.path.splitext(os.path.basename(orig))[0]
    for f in os.listdir(subdir):
        s = os.path.splitext(f)[0]
        if s == stem or _re.fullmatch(_re.escape(stem) + r"S\d{1,2}", s):
            return os.path.join(subdir, f)
    return orig

if _only and os.path.exists(_only):
    # footages que o placements do cut referencia (v0.4: footage_key estável, não [:-4] cego)
    import vlib as _V
    _pl = json.load(open(_only)).get("clips", [])
    _wanted = set()
    for c in _pl:
        n = c.get("name") or ""
        cam = c.get("cam")
        fk = _V.footage_key(n, cam=cam)
        if fk:
            _wanted.add(fk)
        # aliases que wedding_paths / resolve_media_path também aceitam
        if cam and n.startswith(cam + "_"):
            _wanted.add(n[len(cam) + 1 :])
        import re as _re
        m = _re.search(r"C\d+\w*", n, _re.I)
        if m:
            _wanted.add(m.group(0))
            _wanted.add(m.group(0).upper())
    names = sorted(n for n in paths if n in _wanted)
    print(f"batch_scan: {len(names)} footages do cut (de {len(paths)} no media_paths)")
else:
    names = sorted(paths)
    print(f"batch_scan: {len(names)} footages (media_paths inteiro)")
for i, name in enumerate(names, 1):
    out = f"qcache/{name}.json"
    if os.path.exists(out):
        print(f"[{i}/{len(names)}] skip {name}"); continue
    p = paths[name]
    if not os.path.exists(p):
        print(f"[{i}/{len(names)}] MISSING {p}"); continue
    r = q.scan(decode_src(p), sample_fps=SAMPLE_FPS, w=W)
    json.dump(r, open(out, "w"))
    print(f"[{i}/{len(names)}] {name}  n={r['n']} foc_med={r['focus_med']} mot_med={r['motion_med']} bad={len(r['bad'])}", flush=True)
print("DONE batch")
