#!/usr/bin/env python3
"""render_board.py — ONE page that says what is done and what still needs doing.

    python3 skills/rap-avatar-mv/scripts/render_board.py --project <dir> [--out build/render-board.html]

Reads the plan (windows), the cutaway plan, the free-lane queue's live records, the
landed clips and the superseded draws, and writes a board: a summary strip (landed /
rendering / refused / rejected / pending, the pace and a finish estimate), then one card
per job in film order — a 1-fps filmstrip of the landed clip, or the keyframe the render
will open on, with its status, draw count and times. The page refreshes itself every two
minutes, so it can stay open while the lane runs (operator, 2026-09-06: "update html so I
can see what's done and needs doing"). Strips are cached next to the page and rebuilt only
when the clip changes.
"""
from __future__ import annotations

import argparse
import datetime as dt
import glob
import hashlib
import html
import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lane_page import page  # noqa: E402

CSS = """
.summary{display:flex;gap:14px;flex-wrap:wrap;margin:14px 0 22px}
.summary .box{background:var(--panel,#161a22);border:1px solid var(--line,#2a2f3a);border-radius:10px;padding:10px 16px;min-width:120px}
.summary .n{font-size:28px;font-weight:700;line-height:1}
.summary .l{opacity:.7;font-size:12px;margin-top:4px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(420px,1fr));gap:14px}
.card{background:var(--panel,#161a22);border:1px solid var(--line,#2a2f3a);border-radius:10px;overflow:hidden}
.card img{display:block;width:100%;height:auto;background:#000}
.card .meta{padding:8px 12px;font-size:13px}
.card .meta b{font-size:14px}
.st{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:700;margin-left:6px;vertical-align:middle}
.st-landed{background:#1f6b3a;color:#dff7e6}.st-rendering{background:#8a6d00;color:#fff5cc}
.st-refused{background:#7a1f1f;color:#ffd9d9}.st-rejected{background:#5a2d7a;color:#eedcff}
.st-pending{background:#333a47;color:#cfd6e4}.st-borderline{background:#6b4a1f;color:#ffe9c7}
.card.landed{border-color:#2d8a4e}.card.rendering{border-color:#c9a400}.card.refused,.card.rejected{border-color:#a33}
.small{opacity:.65;font-size:12px}
"""


def sha_file(p: str) -> str:
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()[:12]


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


def filmstrip(clip: str, out_jpg: str) -> str:
    """A 1-fps strip of the whole clip (one frame a second — the QC sampling rule),
    tiled 8 across. Cached by the clip's content."""
    tag = out_jpg + ".sha"
    sha = sha_file(clip)
    if os.path.isfile(out_jpg) and os.path.isfile(tag) and open(tag).read().strip() == sha:
        return out_jpg
    secs = max(1, int(round(probe_seconds(clip))))
    rows = max(1, (secs + 7) // 8)
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", clip,
                    "-vf", f"fps=1,scale=200:-1,tile=8x{rows}", "-frames:v", "1", out_jpg], check=False)
    if os.path.isfile(out_jpg):
        open(tag, "w").write(sha)
    return out_jpg if os.path.isfile(out_jpg) else ""


def thumb(src: str, out_jpg: str) -> str:
    if not src or not os.path.isfile(src):
        return ""
    if os.path.isfile(out_jpg) and os.path.getmtime(out_jpg) >= os.path.getmtime(src):
        return out_jpg
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", src, "-vf", "scale=640:-1", "-frames:v", "1", out_jpg], check=False)
    return out_jpg if os.path.isfile(out_jpg) else ""


def parse_ts(s: str | None) -> dt.datetime | None:
    if not s:
        return None
    for fmt in ("%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S"):
        try:
            return dt.datetime.strptime(s, fmt)
        except ValueError:
            continue
    return None


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--out", default="")
    ap.add_argument("--refresh", type=int, default=120, help="seconds between page reloads (0 = none)")
    a = ap.parse_args()
    P = os.path.abspath(a.project)
    build = os.path.join(P, "build")
    out = a.out or os.path.join(build, "render-board.html")
    board_dir = os.path.join(build, "board")
    os.makedirs(board_dir, exist_ok=True)
    qdir = os.path.join(build, "queue", "explore")
    clips_dir = os.path.join(qdir, "clips")
    sup_dir = os.path.join(qdir, "superseded")

    plan = json.load(open(os.path.join(build, "plan.json"), encoding="utf-8"))
    jobs = list(plan.get("jobs", []))
    bp = os.path.join(build, "broll-plan.json")
    if os.path.isfile(bp):
        jobs += json.load(open(bp, encoding="utf-8")).get("jobs", [])
    live = {}
    for f in glob.glob(os.path.join(qdir, "*-live-job.json")):
        try:
            r = json.load(open(f, encoding="utf-8"))
            live[r.get("window") or os.path.basename(f).split("-live-job")[0]] = r
        except (OSError, ValueError):
            continue
    superseded = {}
    for f in glob.glob(os.path.join(sup_dir, "*.mp4")):
        wid = os.path.basename(f).split("-")[0]
        superseded.setdefault(wid, []).append(os.path.basename(f))

    rows, counts = [], {"landed": 0, "rendering": 0, "refused": 0, "rejected": 0, "pending": 0}
    durations = []
    now = dt.datetime.now().astimezone()
    for j in sorted(jobs, key=lambda x: (0 if x["id"].startswith("w") else 1, float(x.get("startSec") or 0))):
        jid = j["id"]
        # cutaways land under build/broll/clips (the cover stage hardcodes it); windows under the queue
        clip = os.path.join(build, "broll", "clips", f"{jid}.mp4") if jid.startswith("b") else os.path.join(clips_dir, f"{jid}.mp4")
        rec = live.get(jid) or {}
        note = os.path.join(os.path.dirname(os.path.dirname(clip)), f"{jid}-reused.json")
        reused = ""
        if os.path.isfile(note):
            try:
                reused = os.path.basename(str(json.load(open(note, encoding="utf-8")).get("source") or json.load(open(note, encoding="utf-8")).get("from") or "")) or "library"
            except (OSError, ValueError):
                reused = "library"
        state = rec.get("state", "")
        if os.path.isfile(clip):
            status = "landed"
            sub = parse_ts(rec.get("submittedAt"))
            landed_at = dt.datetime.fromtimestamp(os.path.getmtime(clip)).astimezone()
            if sub:
                durations.append((landed_at - sub).total_seconds() / 60.0)
        elif str(rec.get("needs") or "").startswith("rerender"):
            status = "refused" if state == "refused" else "rejected"   # judged and parked; waits for a redraw
        elif state == "accepted-by-provider":
            status = "rendering"
        elif state == "refused":
            status = "refused"
        elif jid in superseded:
            status = "rejected"
        else:
            status = "pending"
        counts[status] += 1
        needs = str(rec.get("needs") or "")
        borderline = "borderline" in needs
        if status == "landed":
            img = filmstrip(clip, os.path.join(board_dir, f"{jid}-strip.jpg"))
            img_note = f"1 fps filmstrip · {probe_seconds(clip):.1f}s"
        else:
            img = thumb(j.get("identityRef") or "", os.path.join(board_dir, f"{jid}-key.jpg"))
            img_note = "opens on this keyframe"
        when = ""
        if status == "landed":
            when = f"landed {dt.datetime.fromtimestamp(os.path.getmtime(clip)).strftime('%H:%M')}"
        elif status == "rendering" and rec.get("submittedAt"):
            sub = parse_ts(rec["submittedAt"])
            when = f"submitted {sub.strftime('%H:%M')} ({int((now - sub).total_seconds() // 60)} min ago)" if sub else ""
        elif status in ("refused", "rejected"):
            when = f"needs: {needs or 'redraw'}"
        draws = rec.get("draw")
        extra = ""
        if jid in superseded:
            extra = f" · parked: {', '.join(superseded[jid])}"
        if reused:
            extra += f" · PLACED from {reused}"
        kind = "cutaway" if jid.startswith("b") else ("sung" if j.get("voiceRef") else "dance")
        voice_bits = f" · performer {j.get('performer')}" if j.get("performer") else ""
        rows.append(
            f'<div class="card {status}">'
            + (f'<img src="{html.escape(os.path.relpath(img, build))}" alt="{jid}">' if img else '<div class="meta small">no image</div>')
            + f'<div class="meta"><b>{jid}</b> <span class="st st-{status}">{status.upper()}</span>'
            + (f'<span class="st st-borderline">BORDERLINE</span>' if borderline else "")
            + f'<br><span class="small">{html.escape(j.get("styleId", ""))} · {kind} · {float(j.get("startSec") or 0):.1f}s + {float(j.get("seconds") or 0):g}s'
            + f'{voice_bits}{(" · draw " + str(draws)) if draws else ""}{html.escape(extra)}</span>'
            + f'<br><span class="small">{html.escape(when)} · {img_note}</span></div></div>'
        )

    total = sum(counts.values())
    pace = (sum(durations) / len(durations)) if durations else 0.0
    left = counts["rendering"] + counts["pending"] + counts["refused"] + counts["rejected"]
    eta = (now + dt.timedelta(minutes=pace * left)).strftime("%a %H:%M") if pace and left else "—"
    state_file = os.path.join(build, "rap-state")
    stages = open(state_file).read().split() if os.path.isfile(state_file) else []
    summary = (
        '<div class="summary">'
        + "".join(f'<div class="box"><div class="n">{counts[k]}</div><div class="l">{k}</div></div>'
                  for k in ("landed", "rendering", "refused", "rejected", "pending"))
        + f'<div class="box"><div class="n">{total}</div><div class="l">jobs in the contract</div></div>'
        + f'<div class="box"><div class="n">{pace:.0f} min</div><div class="l">per landing (avg)</div></div>'
        + f'<div class="box"><div class="n" style="font-size:18px">{eta}</div><div class="l">finish estimate</div></div>'
        + "</div>"
        + f'<p class="small">stages done: {" · ".join(stages) or "none"} · written {now.strftime("%H:%M:%S")}'
        + (f" · this page reloads every {a.refresh}s" if a.refresh else "") + "</p>"
    )
    body = summary + '<div class="grid">' + "".join(rows) + "</div>"
    doc = page("Render board", "What has landed, what is rendering, what still needs doing",
               body, slug=os.path.basename(P), extra_css=CSS)
    if a.refresh:
        doc = doc.replace("<head>", f'<head><meta http-equiv="refresh" content="{a.refresh}">', 1)
    open(out, "w", encoding="utf-8").write(doc)
    print(f"render_board: {out} — " + ", ".join(f"{k} {v}" for k, v in counts.items())
          + (f" · {pace:.0f} min/landing · finish ~{eta}" if pace else ""))


if __name__ == "__main__":
    main()
