#!/usr/bin/env python3
"""hf_import.py — read a Studio edit back into the selection the cutter builds from.

    hf_import.py --project <dir> --style <sid> --html build/hyperframes/<sid>/index.html \
                 --selection build/selection-<sid>.json [--cutaways build/cutaways-<sid>.json] [--dry-run]

The operator edits the HyperFrames project `hf_export.py` wrote (Studio's "Overwrite file with
Studio version"). This reads every `data-hf-window` clip's start / media-start / duration / src
and rewrites `vocalMap` (start, end, headSec, performerClip) and `clips[]` so the lane's own cutter,
sync gate and delivery run on the hand edit. It VALIDATES before touching anything:

  * the clips tile the song — no overlap, no hole (a hole is an empty screen, not a cutaway);
  * every clip file exists and has the frames its cut needs (the assembler's rule);
  * a SUNG window keeps its picture-to-song alignment: moving where a take's mouth sits relative
    to the record is `slide` / a re-render, not an edit — trimming its edges is fine;
  * a cutaway placed over a sung window's span is recorded in cutaways-<sid>.json as an operator
    cover (word_sync must not read that span as a missing word) and pins that span to the clip.

Refusals print the window and the numbers; nothing is written on a refusal.
"""
from __future__ import annotations

import argparse
import copy
import datetime as dt
import json
import os
import re
import subprocess
import sys

VIDEO_RE = re.compile(r"<video\b[^>]*>", re.I)
ATTR_RE = re.compile(r'([a-zA-Z0-9_:-]+)="([^"]*)"')
HOLE_MAX_FRAMES = 1          # tiling tolerance (frame snapping)


def probe_seconds(path: str) -> float:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def parse_clips(doc: str, base: str) -> list[dict]:
    out = []
    for m in VIDEO_RE.finditer(doc):
        attrs = dict(ATTR_RE.findall(m.group(0)))
        wid = attrs.get("data-hf-window")
        if not wid:
            continue
        if attrs.get("data-hidden") is not None:
            continue                                  # Studio's eye icon: dropped from the cut
        src = attrs.get("src", "")
        path = os.path.realpath(os.path.join(base, src)) if src and not src.startswith(("http:", "https:")) else src
        out.append({"window": wid, "role": attrs.get("data-hf-role", "pool"),
                    "start": float(attrs.get("data-start", 0)), "mediaStart": float(attrs.get("data-media-start", 0)),
                    "seconds": float(attrs.get("data-duration", 0)), "src": path, "srcName": os.path.basename(src)})
    return out


def import_edit(sel: dict, clips: list[dict], fps: int, cutaways: dict | None, probe=probe_seconds) -> tuple[dict, dict, list[str]]:
    """Returns (new selection, new cutaways record, notes) or raises ValueError with every refusal."""
    song_end = float(sel["songEnd"])
    problems, notes = [], []
    clips = sorted(clips, key=lambda c: c["start"])
    # 1. tiling
    t = 0.0
    for c in clips:
        if c["seconds"] <= 0:
            problems.append(f"{c['window']}: zero-length clip")
        gap_f = round((c["start"] - t) * fps)
        if gap_f > HOLE_MAX_FRAMES:
            problems.append(f"hole {t:.2f}-{c['start']:.2f}s before {c['window']}: nothing on screen — drop a cutaway there or close the gap")
        if gap_f < -HOLE_MAX_FRAMES:
            problems.append(f"{c['window']} at {c['start']:.2f}s overlaps the clip before it (ends {t:.2f}s) — only one clip per moment")
        t = c["start"] + c["seconds"]
    if clips and abs(round((t - song_end) * fps)) > HOLE_MAX_FRAMES:
        problems.append(f"the cut ends at {t:.2f}s but the song ends at {song_end:.2f}s")
    # 2. files + frames
    lengths = {}
    for c in clips:
        if not c["src"] or not os.path.isfile(c["src"]):
            problems.append(f"{c['window']}: clip file missing ({c['src'] or c['srcName']})")
            continue
        od = lengths.setdefault(c["src"], probe(c["src"]))
        need = round((c["mediaStart"] + c["seconds"]) * fps)
        if round(od * fps) < need:
            problems.append(f"{c['window']}: {c['srcName']} has {od:.2f}s but the cut needs {c['mediaStart'] + c['seconds']:.2f}s from its start")
    # 3. sung alignment
    old = {s.get("performerClip"): s for s in sel.get("vocalMap", []) if s.get("performerClip")}
    old_clip = {c["id"]: c for c in sel.get("clips", [])}
    for c in clips:
        s = old.get(c["window"])
        if not s or s.get("lipSyncExempt") or c["role"] != "performer":
            continue
        anchor_old = float(s["start"]) - float(s.get("headSec", 0.0))
        anchor_new = c["start"] - c["mediaStart"]
        d_ms = (anchor_new - anchor_old) * 1000
        if abs(d_ms) > 1000 / fps + 1e-6:
            problems.append(f"{c['window']}: a SUNG take moved {d_ms:+.0f} ms against the record — that changes where her mouth sits on the bar. "
                            f"Trim its edges here; to shift it use `--from slide` (sync_shift) or --replace {c['window']}")
        src_old = old_clip.get(c["window"], {}).get("path")
        if src_old and os.path.realpath(src_old) != c["src"]:
            problems.append(f"{c['window']}: a SUNG take's file changed ({os.path.basename(src_old)} -> {c['srcName']}) — swap takes with --replace / reuse_clips, not in Studio")
    if problems:
        raise ValueError("\n".join(problems))
    # 4. rebuild
    new = copy.deepcopy(sel)
    vm, clip_reg, cov = [], {c["id"]: dict(c) for c in sel.get("clips", [])}, []
    old_spans = [(float(s["start"]), float(s["end"]), s) for s in sel.get("vocalMap", []) if s.get("performerClip") and not s.get("lipSyncExempt")]
    for c in clips:
        s = old.get(c["window"])
        end = round(c["start"] + c["seconds"], 6)
        # start from the section the selection already carries (every key the later stages
        # read survives); only what Studio can change is rewritten, and only when it changed
        sec = dict(s) if s else {"type": "instrumental", "performerClip": c["window"], "lipSyncExempt": True}
        for key, val in (("start", round(c["start"], 6)), ("end", end), ("headSec", round(c["mediaStart"], 4))):
            if abs(float(sec.get(key, 0.0)) - val) > 0.5 / fps:
                sec[key] = val
        if not s or s.get("lipSyncExempt") or c["role"] != "performer":
            sec["lipSyncExempt"] = True
        vm.append(sec)
        reg = clip_reg.get(c["window"])
        if not reg or os.path.realpath(reg.get("path", "")) != c["src"]:
            clip_reg[c["window"]] = {"id": c["window"], "path": c["src"], "durationSec": round(lengths[c["src"]], 3)}
            notes.append(f"{c['window']}: clip -> {c['srcName']}")
        # a pool clip over what used to be sung = an operator cover
        if sec.get("lipSyncExempt"):
            for a0, a1, os_ in old_spans:
                lo, hi = max(a0, sec["start"]), min(a1, sec["end"])
                if hi - lo >= 0.25 and os_["performerClip"] != c["window"]:
                    cov.append({"clip": os_["performerClip"], "startSec": round(lo, 3), "endSec": round(hi, 3),
                                "broll": c["window"], "why": "operator: placed a cutaway in Studio"})
    new["vocalMap"] = vm
    order = [c["id"] for c in sel.get("clips", [])] + [k for k in clip_reg if k not in {c["id"] for c in sel.get("clips", [])}]
    new["clips"] = [clip_reg[k] for k in order]          # the selection's own order; new clips last
    new.setdefault("provenance", {})["_hfImport"] = {"at": dt.datetime.now().isoformat(timespec="seconds"), "windows": len(vm)}
    rec = copy.deepcopy(cutaways) if cutaways else {"_comment": "operator covers from Studio (hf_import.py)", "cutaways": []}
    rec.setdefault("cutaways", [])
    rec["cutaways"] = [x for x in rec["cutaways"] if x.get("why") != "operator: placed a cutaway in Studio"] + cov
    for x in cov:
        notes.append(f"{x['clip']}: cutaway {x['broll']} over {x['startSec']:.2f}-{x['endSec']:.2f}s recorded as an operator cover")
    return new, rec, notes


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--style", required=True)
    ap.add_argument("--html", required=True)
    ap.add_argument("--selection", required=True)
    ap.add_argument("--cutaways", default="")
    ap.add_argument("--fps", type=int, default=0)
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()
    sel = json.load(open(a.selection, encoding="utf-8"))
    fps = a.fps or int(sel.get("fps") or 24)
    clips = parse_clips(open(a.html, encoding="utf-8").read(), os.path.dirname(os.path.abspath(a.html)))
    if not clips:
        print("hf_import: the HTML carries no data-hf-window clips — nothing to import", file=sys.stderr)
        return 2
    cutaways = json.load(open(a.cutaways, encoding="utf-8")) if a.cutaways and os.path.isfile(a.cutaways) else None
    try:
        new, rec, notes = import_edit(sel, clips, fps, cutaways)
    except ValueError as e:
        print("hf_import: REFUSED — the Studio edit cannot be cut as it stands:\n  " + str(e).replace("\n", "\n  "), file=sys.stderr)
        return 5
    changed = json.dumps(new["vocalMap"], sort_keys=True) != json.dumps(sel.get("vocalMap"), sort_keys=True) \
        or json.dumps(new["clips"], sort_keys=True) != json.dumps(sel.get("clips"), sort_keys=True)
    for n in notes:
        print("  " + n, file=sys.stderr)
    if a.dry_run:
        print(f"hf_import: {len(new['vocalMap'])} window(s), {'changes' if changed else 'no change'} (dry run)", file=sys.stderr)
        return 0
    if not changed:
        print("hf_import: the Studio project matches the selection — nothing to write", file=sys.stderr)
        return 0
    stamp = dt.datetime.now().strftime("%m%d-%H%M")
    bak = a.selection.replace(".json", f".before-hf-{stamp}.json")
    os.replace(a.selection, bak)
    json.dump(new, open(a.selection, "w", encoding="utf-8"), indent=1)
    if a.cutaways:
        json.dump(rec, open(a.cutaways, "w", encoding="utf-8"), indent=1)
    print(f"hf_import: wrote {a.selection} ({len(new['vocalMap'])} windows; previous kept as {os.path.basename(bak)})", file=sys.stderr)
    return 0


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