#!/usr/bin/env python3
"""hf_export.py — the film's cut, as a HyperFrames project the operator can EDIT in Studio.

    hf_export.py --project <dir> --style <sid> --mv-config build/mv-<sid>.json \
                 --selection build/selection-<sid>.json [--vclaw dist/cli/vclaw.js | --plan <dry-run.json>] \
                 [--out build/hyperframes/<sid>] [--cards build/bookends/cards.json]

HyperFrames (heygen-com/hyperframes) composes EXISTING media on an HTML timeline and its Studio
(`hyperframes preview`) is a real editor: scrub, razor, move and trim clips, hear the mix, write the
edit back to the HTML. It generates no picture and measures no sync, so it is the lane's EDITING
surface, never its cutter: the cut list here is the assembler's own dry-run plan (the same
`vclaw video music-video --config` call `select_cut.py --verify-plan` makes), one `<video>` per cut,
so what Studio shows is exactly what the frame-exact cutter will build. `hf_import.py` reads the
edit back into `selection-<sid>.json`, and the normal cut → sync-gate → deliver runs on it.

Every clip carries `data-hf-window` (the selection's performerClip id) and `data-hf-role`; the
importer maps by those, never by position. Assets are symlinks into the stage dirs — no copies.
"""
from __future__ import annotations

import argparse
import html
import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from select_cut import LABEL_RE  # noqa: E402  the one regex for the assembler's cut labels

GSAP = "https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"


def dry_run_plan(vclaw: str, config: str) -> dict:
    r = subprocess.run(["node", vclaw, "video", "music-video", "--config", config],
                       capture_output=True, text=True)
    try:
        plan = json.loads(r.stdout or "{}")
    except json.JSONDecodeError:
        plan = {}
    if not plan.get("steps"):
        raise SystemExit(f"hf_export: the assembler's dry run gave no plan (is {vclaw} built?)\n{r.stderr[-600:]}")
    return plan


def cuts_from_plan(plan: dict) -> list[dict]:
    """[{i, role, clip, inSec, seconds}] in film order, from the plan's cut labels."""
    out = []
    for s in plan.get("steps", []):
        m = LABEL_RE.match(s.get("label", ""))
        if m:
            out.append({"i": int(m[1]), "role": m[2], "clip": m[3], "inSec": float(m[4]), "seconds": float(m[5])})
    return out


def link(src: str, assets: str, name: str) -> str:
    dst = os.path.join(assets, name)
    if os.path.islink(dst) or os.path.exists(dst):
        os.remove(dst)
    os.symlink(os.path.realpath(src), dst)
    return "assets/" + name


def build_html(title: str, w: int, h: int, fps: int, song_end: float, videos: list[str],
               song_src: str, cards: list[str]) -> str:
    body = "\n".join(videos + cards)
    return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width={w}, height={h}"/>
<title>{html.escape(title)}</title>
<script src="{GSAP}"></script>
<style>
body{{margin:0;background:#000}}
#root{{position:relative;width:{w}px;height:{h}px;overflow:hidden;background:#000}}
.clip{{position:absolute;inset:0;width:{w}px;height:{h}px;object-fit:cover}}
</style>
</head>
<body>
<div id="root" data-composition-id="main" data-start="0" data-width="{w}" data-height="{h}" data-duration="{song_end:.3f}" data-fps="{fps}">
{body}
<audio id="song" src="{song_src}" data-timeline-role="music" data-start="0" data-media-start="0" data-duration="{song_end:.3f}" data-track-index="10" data-volume="1"></audio>
</div>
<script>
// Media-only composition: the framework owns playback; the timeline just spans the song.
window.__timelines = window.__timelines || {{}};
const tl = gsap.timeline({{ paused: true }});
tl.to("#root", {{ duration: {song_end:.3f} }}, 0);
window.__timelines["main"] = tl;
</script>
</body>
</html>
"""


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--style", required=True)
    ap.add_argument("--mv-config", required=True, help="build/mv-<sid>.json (build_mv_config.py)")
    ap.add_argument("--selection", required=True, help="build/selection-<sid>.json")
    ap.add_argument("--vclaw", default="", help="dist/cli/vclaw.js — runs the assembler's dry run for the cut list")
    ap.add_argument("--plan", default="", help="an already-captured dry-run plan JSON (tests)")
    ap.add_argument("--out", default="")
    ap.add_argument("--cards", default="", help="build/bookends/cards.json — title/outro cards as clips (preview only)")
    ap.add_argument("--title", default="")
    ap.add_argument("--alternates", default="", help="JSON [{id, path, start, mediaStart, seconds, note}] — takes offered HIDDEN "
                    "on their own track (Studio's eye icon shows one; hf_import takes it into the cut)")
    a = ap.parse_args()

    cfg = json.load(open(a.mv_config, encoding="utf-8"))
    sel = json.load(open(a.selection, encoding="utf-8"))
    plan = json.load(open(a.plan, encoding="utf-8")) if a.plan else dry_run_plan(
        a.vclaw or os.path.join(os.environ.get("MAIN", os.path.expanduser("~/Documents/GitHub/videoclaw-v3")), "dist/cli/vclaw.js"),
        a.mv_config)
    cuts = cuts_from_plan(plan)
    if not cuts:
        raise SystemExit("hf_export: the plan has no cut steps")
    fps = int(cfg.get("fps") or sel.get("fps") or 24)
    w, h = int(cfg["width"]), int(cfg["height"])
    song_end = float(cfg.get("songEnd") or sel.get("songEnd"))
    clips = {c["id"]: c for c in cfg["clips"]}
    exempt = set(cfg.get("lipSyncExempt") or [])
    by_window = {s.get("performerClip"): s for s in sel.get("vocalMap", []) if s.get("performerClip")}

    out = a.out or os.path.join(a.project, "build", "hyperframes", a.style)
    assets = os.path.join(out, "assets")
    os.makedirs(assets, exist_ok=True)

    videos, rows, t_frames = [], [], 0
    for c in cuts:
        clip = clips.get(c["clip"])
        if not clip:
            raise SystemExit(f"hf_export: cut {c['i']} names clip '{c['clip']}' which the config does not carry")
        src = link(clip["path"], assets, f"{c['clip']}.mp4")
        dur_f = round(c["seconds"] * fps)
        start, dur = t_frames / fps, dur_f / fps
        sec = by_window.get(c["clip"], {})
        role = "performer" if (c["role"] == "performer" and not sec.get("lipSyncExempt") and c["clip"] not in exempt) else "pool"
        track = 0 if role == "performer" else 1
        videos.append(
            f'<video id="v-{c["clip"]}" class="clip" src="{src}" data-start="{start:.6f}" data-media-start="{c["inSec"]:.4f}" '
            f'data-duration="{dur:.6f}" data-track-index="{track}" data-hf-window="{c["clip"]}" data-hf-role="{role}" '
            f'data-hf-cut="{c["i"]}" muted playsinline></video>')
        rows.append({"cut": c["i"], "window": c["clip"], "role": role, "start": round(start, 6),
                     "seconds": round(dur, 6), "inSec": c["inSec"], "src": clip["path"]})
        t_frames += dur_f
    if abs(t_frames / fps - song_end) > 1.5 / fps:
        print(f"hf_export: WARNING the cuts end at {t_frames / fps:.3f}s but the song ends at {song_end:.3f}s", file=sys.stderr)

    cards = []
    if a.cards and os.path.isfile(a.cards):
        # preview-only: the FILM's title/outro cards around the body, so Studio shows the whole film length
        try:
            cj = json.load(open(a.cards, encoding="utf-8"))
            for i, card in enumerate(cj.get("cards", []) if isinstance(cj, dict) else cj):
                p = card.get("path") or card.get("file")
                if p and os.path.isfile(p):
                    cards.append(f'<img id="card-{i}" class="clip" src="{link(p, assets, os.path.basename(p))}" '
                                 f'data-start="{song_end + i * 5:.3f}" data-duration="5" data-track-index="2" data-hf-role="card">')
        except (OSError, ValueError):
            pass
    if a.alternates and os.path.isfile(a.alternates):
        # EVERY singing take the operator owns, where it fits best, hidden: he un-hides one in
        # Studio and the next --from cut takes it (hf_import reads data-hidden as "dropped").
        for alt in json.load(open(a.alternates, encoding="utf-8")):
            if not os.path.isfile(alt["path"]):
                continue
            src = link(alt["path"], assets, f"{alt['id']}.mp4")
            cards.append(f'<video id="alt-{alt["id"]}" class="clip" src="{src}" data-start="{float(alt["start"]):.6f}" '
                         f'data-media-start="{float(alt.get("mediaStart", 0)):.4f}" data-duration="{float(alt["seconds"]):.6f}" '
                         f'data-track-index="3" data-hf-window="{alt["id"]}" data-hf-role="performer" data-hidden '
                         f'data-hf-note="{html.escape(str(alt.get("note", "")))}" muted playsinline></video>')
    song_src = link(cfg["song"], assets, "song" + os.path.splitext(cfg["song"])[1])
    title = a.title or f"{os.path.basename(os.path.abspath(a.project))} — {a.style}"
    open(os.path.join(out, "index.html"), "w", encoding="utf-8").write(
        build_html(title, w, h, fps, song_end, videos, song_src, cards))
    json.dump({"schemaVersion": 1, "style": a.style, "selection": os.path.abspath(a.selection),
               "mvConfig": os.path.abspath(a.mv_config), "fps": fps, "songEnd": song_end,
               "width": w, "height": h, "cuts": rows},
              open(os.path.join(out, "export-map.json"), "w", encoding="utf-8"), indent=1)
    print(f"hf_export: {len(rows)} cut(s) -> {out}/index.html", file=sys.stderr)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
