"""video.py — prepara um VÍDEO MOSTRADO para a comp-a: quadros (img/filmes/<nome>/0001.jpg…) + som (audio/videos/<nome>.wav)
+ ficha (info.json) + índice para o HTML (img/filmes/_indice.js → window.FILMES_INFO).

  python comp-a/video.py <fonte.mp4> --nome glass-hub --de 12.4 --dur 3.2 --w 960
  python comp-a/video.py <fonte.mp4> --nome ai-opener-vertical --de 4 --dur 4 --crop 608:1080:656:0 --w 440 --sem-som
  python comp-a/video.py --indice            # só refaz o _indice.js

No HTML: janela('glass-hub', {som: true}) toca os quadros e registra o trecho de som; o audio_p1.py/audio_p2.py lê o
__events().videos e põe audio/videos/<nome>.wav no tempo certo (trilha para ou segue, conforme a janela).
"""
import argparse, json, subprocess, sys
from pathlib import Path

AQUI = Path(__file__).resolve().parent
FIL, SOM = AQUI / "img" / "filmes", AQUI / "audio" / "videos"
sys.stdout.reconfigure(encoding="utf-8")


def indice():
    info = {}
    for d in sorted(FIL.iterdir()):
        f = d / "info.json"
        if d.is_dir() and f.exists():
            info[d.name] = json.load(open(f, encoding="utf-8"))
    (FIL / "_indice.js").write_text("window.FILMES_INFO = " + json.dumps(info, ensure_ascii=False, indent=0) + ";\n", encoding="utf-8")
    print(len(info), "filmes no índice")


def tem_audio(fonte):
    r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", str(fonte)], capture_output=True, text=True)
    return bool(r.stdout.strip())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("fonte", nargs="?"); ap.add_argument("--nome"); ap.add_argument("--de", type=float, default=0.0)
    ap.add_argument("--dur", type=float, default=4.0); ap.add_argument("--w", type=int, default=960); ap.add_argument("--crop")
    ap.add_argument("--fps", type=int, default=30); ap.add_argument("--q", type=int, default=3)
    ap.add_argument("--sem-som", action="store_true"); ap.add_argument("--indice", action="store_true")
    a = ap.parse_args()
    if a.indice:
        return indice()
    fonte = Path(a.fonte).resolve(); out = FIL / a.nome
    out.mkdir(parents=True, exist_ok=True)
    for f in out.glob("*.jpg"):
        f.unlink()
    vf = (f"crop={a.crop}," if a.crop else "") + f"fps={a.fps},scale={a.w}:-2"
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", str(a.de), "-t", str(a.dur), "-i", str(fonte), "-vf", vf, "-q:v", str(a.q), str(out / "%04d.jpg")], check=True)
    n = len(list(out.glob("*.jpg")))
    som = None
    if not a.sem_som and tem_audio(fonte):
        SOM.mkdir(parents=True, exist_ok=True); som = SOM / f"{a.nome}.wav"
        subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", str(a.de), "-t", str(a.dur), "-i", str(fonte), "-vn", "-ac", "2", "-ar", "48000", str(som)], check=True)
    from PIL import Image
    w, h = Image.open(out / "0001.jpg").size
    ficha = {"n": n, "fps": a.fps, "w": w, "h": h, "dur": round(n / a.fps, 3), "som": bool(som), "fonte": str(fonte), "de": a.de}
    json.dump(ficha, open(out / "info.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(a.nome, ficha); indice()


if __name__ == "__main__":
    main()
