#!/usr/bin/env python3
"""Adapta o placements do-zero (weddings/<x>/placements.json, naming camN_slug_FOOTAGE) pro formato
que o MOTOR DE CORTE (unified.py) espera: name=`camN_FOOTAGE.wav`, cam=`camN`. As caches de percepção
(shake/face/zoom) são keyed pelo FOOTAGE (mesma filmagem) → reconectam de graça. Só troca o naming +
o campo cam; posições (startFrame/dur) vêm do do-zero. Backup do placements.json anterior.
Uso: dozero_to_engine.py weddings/<x>/placements.json  [-> escreve placements.json]"""
import json, re, os, sys, shutil

src = sys.argv[1] if len(sys.argv) > 1 else "weddings/paula/placements.json"
dz = json.load(open(src))
out = []
for c in dz["clips"]:
    name = c["name"]
    m = re.match(r'^cam(\d+)_', name)
    if not m:
        print(f"  ! sem camN em {name}, pulando"); continue
    num = m.group(1)
    footage = re.sub(r'^cam\d+_[a-z0-9]+_', '', name)  # tira camN_slug_ -> PRE_0172cerimonia
    out.append({
        "name": f"cam{num}_{footage}",  # stem puro; v0.4 footage_key não precisa de .wav dummy
        "cam": f"cam{num}",
        "startFrame": c["startFrame"], "durationFrames": c["durationFrames"],
        "confidence": c.get("confidence", 0.9), "orange": c.get("orange", False),
    })

if os.path.exists("placements.json"):
    shutil.copy("placements.json", "placements_prev.json")
    print("backup: placements.json -> placements_prev.json")
json.dump({"clips": out, "masterStartFrame": dz.get("masterStartFrame", 0)},
          open("placements.json", "w"), indent=0)
from collections import Counter
print(f"placements.json (motor): {len(out)} clips {dict(Counter(c['cam'] for c in out))}")
# valida que as caches conectam
import os as _os
try:
    import vlib as _V
    def _fk(n, cam=None):
        return _V.footage_key(n, cam=cam)
except Exception:
    def _fk(n, cam=None):
        if cam and n.startswith(cam + "_"):
            return n[len(cam) + 1 :]
        return n
miss = [c["name"] for c in out
        if not _os.path.exists("shakecache/" + _fk(c["name"], c.get("cam")) + ".json")]
print(f"caches shake: {len(out)-len(miss)}/{len(out)} conectam" + (f" | FALTAM: {miss[:5]}" if miss else " ✅"))
