#!/usr/bin/env python3
"""JUDGE de variety do-zero -> variety_inserts.json. Consome variety_candidates.json (localizador
nativo variety_cands.py, fora-clímax). Uso: variety_judge.py"""
import json, os
from vlm import ask_images, par_map
import judgelib as J
import cache_manifest as cm

OUT = "variety_inserts.json"
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

def main():
    # CACHE (backlog-30 grupo2): dezenas de calls. variety_candidates.json (localizador nativo,
    # sem estágio próprio cacheado) + UNI.json (pass0) são regenerados toda rodada -> content-
    # hash. Sem extra_deps: variety_cands.py não é estágio cacheado, o content-hash do
    # candidates.json já resolve sozinho (nota do backlog-30). vlib.py não entra: este script só
    # importa judgelib (J), não vlib.
    _sig = {"content": cm.content_signature(["variety_candidates.json", "versions/UNI.json"]),
            "mtime": cm.input_signature([os.path.join(_SCRIPT_DIR, "prompts", "variety_judge_v1.md"),
                                          os.path.join(_SCRIPT_DIR, "judgelib.py")])}
    if cm.is_fresh(".", "variety_judge", __file__, _sig) and os.path.exists(OUT):
        print(f"[cache] variety_judge: script+input inalterados, pulando VLM — reusando {OUT}")
        return
    cands = json.load(open("variety_candidates.json"))
    active = J.active_fn()
    prompt = J.prompt("variety_judge_v1.md")
    def work(ic):
        i, c = ic
        f0 = c.get("f0"); f1 = c.get("f1", (f0 or 0)+90)
        an = c.get("angle") or c.get("cam")
        if isinstance(an, str): an = int(an.replace("cam", ""))
        key = c.get("key") or c.get("type", "b-roll")
        mid = (f0+f1)//2
        a = J.frame_of(an, mid); b = J.frame_of(active(mid), mid)
        if not a or not b: return None
        txt, _ = ask_images([a, b], prompt.replace("{KEY}", str(key)))
        v = J.jparse(txt)
        st = "KEEP" if v.get("keep") else "drop"
        print(f"  [{i+1}/{len(cands)}] {J.tc(f0)} {key}@cam{an} -> {st} ({str(v.get('why',''))[:50]})")
        if not v.get("keep"): return None
        return {"f0": f0, "f1": f1, "angle": an, "key": key}
    out = [r for r in par_map(work, list(enumerate(cands))) if r]
    json.dump(out, open(OUT, "w"), indent=1)
    cm.mark_done(".", "variety_judge", __file__, _sig)
    print(f"variety_inserts.json: {len(out)}/{len(cands)} inserts")

if __name__ == "__main__":
    main()
