#!/usr/bin/env python3
"""
Reusable declarative post-to-video renderer.
Renders 16:9 (1920x1080) and native vertical 9:16 (1080x1920) videos from JSON specs.
Supports typed visual panels: bar_compare, timeline_rows, loop_diagram, coda_card.
"""

from __future__ import annotations

import argparse
import json
import math
import subprocess
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont

from audio_synth import FPS, synthesize_spec_audio

BG = "#0b0c10"
PANEL = "#12141a"
GRID = "#262932"
BONE = "#e6e3dc"
MUTED = "#a9a8a2"
ASH = "#85868b"
AMBER = "#e2b45c"
CYAN = "#5ae6f0"
CLAY = "#ba6348"
SAGE = "#6ea388"


def load_font(size: int, kind: str = "serif") -> ImageFont.FreeTypeFont:
    candidates = {
        "serif": [
            "/System/Library/Fonts/Supplemental/Georgia Bold.ttf",
            "/System/Library/Fonts/Supplemental/Times New Roman.ttf",
        ],
        "serif_reg": [
            "/System/Library/Fonts/Supplemental/Georgia.ttf",
            "/System/Library/Fonts/Supplemental/Times New Roman.ttf",
        ],
        "mono": [
            "/System/Library/Fonts/Menlo.ttc",
            "/System/Library/Fonts/Courier.ttc",
        ],
    }[kind]
    for p in candidates:
        if Path(p).exists():
            try:
                return ImageFont.truetype(p, size)
            except Exception:
                continue
    return ImageFont.load_default()


FONTS = {
    (sz, k): load_font(sz, k)
    for sz in (16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64)
    for k in ("serif", "serif_reg", "mono")
}


def ease_out(u: float) -> float:
    u = max(0.0, min(1.0, u))
    return 1.0 - (1.0 - u) ** 3


def active_pulse(t: float, events: list[dict]) -> tuple[float, dict | None]:
    last = None
    for ev in events:
        if ev["t_s"] <= t + 1e-6:
            last = ev
    if last is None:
        return 0.0, None
    dt = t - last["t_s"]
    return math.exp(-dt / 0.40) if dt >= 0 else 0.0, last


def find_act(t: float, acts: list[dict]) -> tuple[dict, float]:
    for a in acts:
        if a["t0"] <= t < a["t1"]:
            prog = (t - a["t0"]) / max(1e-6, a["t1"] - a["t0"])
            return a, prog
    return acts[-1], 1.0


def draw_bar_compare(draw: ImageDraw.ImageDraw, x0: int, y0: int, w: int, h: int, act: dict, prog: float, is_vert: bool) -> None:
    draw.rectangle([x0, y0, x0 + w, y0 + h], fill=PANEL, outline=GRID, width=2)
    draw.text((x0 + 24, y0 + 22), act.get("panel_title", "Comparison"), fill=BONE, font=FONTS[(28 if not is_vert else 24, "serif")])
    items = act["bars"]
    grow = ease_out(min(1.0, prog / 0.42))
    mn = act.get("min_val", 0.0)
    mx = act.get("max_val", 1.0)
    row_h = max(62, (h - 90) // max(1, len(items)))
    for i, item in enumerate(items):
        ry = y0 + 76 + i * row_h
        val = item["value"] * grow + mn * (1.0 - grow)
        frac = max(0.02, min(1.0, (val - mn) / max(1e-6, mx - mn)))
        col = {"amber": AMBER, "cyan": CYAN, "clay": CLAY, "sage": SAGE}.get(item.get("color", "clay"), CLAY)
        draw.text((x0 + 24, ry), item["label"], fill=BONE, font=FONTS[(22 if not is_vert else 20, "mono")])
        draw.text((x0 + w - 24, ry), item["display"], fill=col, font=FONTS[(22 if not is_vert else 20, "mono")], anchor="ra")
        draw.rectangle([x0 + 24, ry + 32, x0 + w - 24, ry + 54], fill=GRID)
        draw.rectangle([x0 + 24, ry + 32, int(x0 + 24 + (w - 48) * frac), ry + 54], fill=col)


def draw_timeline_rows(draw: ImageDraw.ImageDraw, x0: int, y0: int, w: int, h: int, act: dict, prog: float, is_vert: bool) -> None:
    draw.rectangle([x0, y0, x0 + w, y0 + h], fill=PANEL, outline=GRID, width=2)
    rows = act["rows"]
    step_y = max(66, (h - 32) // max(1, len(rows)))
    reveal_n = int(prog * (len(rows) + 1.4))
    for i, r in enumerate(rows):
        ry = y0 + 24 + i * step_y
        on = i <= reveal_n
        col = {"amber": AMBER, "cyan": CYAN, "clay": CLAY, "sage": SAGE}.get(r.get("color", "amber"), AMBER)
        draw.line([x0 + 24, ry + step_y - 12, x0 + w - 24, ry + step_y - 12], fill=GRID, width=1)
        draw.text((x0 + 26, ry + 4), r["title"], fill=col if on else ASH, font=FONTS[(28 if not is_vert else 22, "serif")])
        draw.text((x0 + 26, ry + 40), r["detail"], fill=BONE if on else ASH, font=FONTS[(20 if not is_vert else 16, "mono")])


def draw_loop_diagram(draw: ImageDraw.ImageDraw, x0: int, y0: int, w: int, h: int, act: dict, prog: float, is_vert: bool) -> None:
    draw.rectangle([x0, y0, x0 + w, y0 + h], fill=PANEL, outline=GRID, width=2)
    cx, cy = x0 + w // 2, y0 + h // 2 + 10
    nodes = act["nodes"]  # 3 or 4 nodes arranged clockwise
    rx = int(w * (0.30 if not is_vert else 0.31))
    ry = int(h * (0.28 if not is_vert else 0.29))
    draw.ellipse([cx - rx, cy - ry, cx + rx, cy + ry], outline=GRID, width=3)
    arc_deg = int(ease_out(min(1.0, prog / 0.75)) * 360)
    draw.arc([cx - rx, cy - ry, cx + rx, cy + ry], start=-90, end=-90 + arc_deg, fill=CYAN, width=4)
    active_idx = int((prog * len(nodes)) % len(nodes))
    for i, nd in enumerate(nodes):
        ang = -math.pi / 2 + (2 * math.pi * i) / len(nodes)
        nx, ny = int(cx + rx * math.cos(ang)), int(cy + ry * math.sin(ang))
        bw, bh = (280 if not is_vert else 250), 82
        on = (i <= active_idx)
        draw.rounded_rectangle([nx - bw // 2, ny - bh // 2, nx + bw // 2, ny + bh // 2],
                               radius=8, fill=BG, outline=AMBER if on else GRID, width=3 if on else 2)
        draw.text((nx, ny - 14), nd["title"], fill=AMBER if on else MUTED, font=FONTS[(22 if not is_vert else 20, "serif")], anchor="mm")
        draw.text((nx, ny + 16), nd["sub"], fill=BONE if on else ASH, font=FONTS[(18 if not is_vert else 16, "mono")], anchor="mm")


def render_frame(t: float, spec: dict, events: list[dict], aspect: str) -> Image.Image:
    is_vert = (aspect == "9x16")
    W, H = (1080, 1920) if is_vert else (1920, 1080)
    img = Image.new("RGB", (W, H), BG)
    draw = ImageDraw.Draw(img)

    act, prog = find_act(t, spec["acts"])
    pulse, ev = active_pulse(t, events)
    pad_x = 72 if is_vert else 96
    top_y = 140 if is_vert else 68
    bot_y = H - (150 if is_vert else 64)

    draw.line([pad_x, top_y - 24, W - pad_x, top_y - 24], fill=GRID, width=4)
    u_tot = max(0.0, min(1.0, t / float(spec["duration_s"])))
    draw.line([pad_x, top_y - 24, int(pad_x + (W - 2 * pad_x) * u_tot), top_y - 24], fill=AMBER, width=4)

    draw.text((pad_x, top_y), act["kicker"], fill=AMBER, font=FONTS[(22 if not is_vert else 24, "mono")])
    hl = act["headline_vert"] if is_vert and "headline_vert" in act else act["headline"]
    draw.multiline_text((pad_x, top_y + 38), hl, fill=BONE, font=FONTS[(52 if not is_vert else 48, "serif")], spacing=10)

    hx, hy = W - pad_x - 32, top_y + 28
    if pulse > 0.05:
        rr = int(10 + (1.0 - pulse) * 30)
        draw.ellipse([hx - rr, hy - rr, hx + rr, hy + rr], outline=CLAY, width=3)
    draw.ellipse([hx - 9, hy - 9, hx + 9, hy + 9], fill=CLAY if pulse > 0.25 else GRID)

    stage_y = top_y + (212 if is_vert else 190)
    stage_h = bot_y - stage_y - 52
    stage_w = W - 2 * pad_x

    kind = act["kind"]
    if kind == "bar_compare":
        draw_bar_compare(draw, pad_x, stage_y, stage_w, stage_h, act, prog, is_vert)
    elif kind == "timeline_rows":
        draw_timeline_rows(draw, pad_x, stage_y, stage_w, stage_h, act, prog, is_vert)
    elif kind == "loop_diagram":
        draw_loop_diagram(draw, pad_x, stage_y, stage_w, stage_h, act, prog, is_vert)
    else:
        draw.rectangle([pad_x, stage_y, pad_x + stage_w, stage_y + stage_h], fill=PANEL, outline=AMBER, width=2)
        cx, cy = W // 2, stage_y + stage_h // 2
        draw.text((cx, cy - 72), act.get("coda_top", "Open data, code, and independent checks:"), fill=MUTED, font=FONTS[(28 if not is_vert else 22, "serif_reg")], anchor="mm")
        draw.text((cx, cy - 6), spec["url"], fill=CYAN, font=FONTS[(32 if not is_vert else 24, "mono")], anchor="mm")
        draw.text((cx, cy + 66), spec.get("byline", "Ziding Zhang"), fill=AMBER, font=FONTS[(22 if not is_vert else 20, "mono")], anchor="mm")

    sub = ev["label"] if ev else spec.get("default_caption", "")
    draw.text((pad_x, bot_y - 24), sub, fill=MUTED, font=FONTS[(20 if not is_vert else 18, "mono")])
    draw.text((W - pad_x, bot_y - 24), f"{t:05.2f}s", fill=ASH, font=FONTS[(20, "mono")], anchor="ra")
    return img


def encode_aspect(spec: dict, events: list[dict], wav_path: Path, aspect: str, out_dir: Path) -> None:
    w, h = (1080, 1920) if aspect == "9x16" else (1920, 1080)
    slug = spec["slug"]
    out_mp4 = out_dir / f"{slug}-{aspect}.mp4"
    out_poster = out_dir / f"{slug}-{aspect}-poster.webp"
    total_frames = int(round(float(spec["duration_s"]) * FPS))
    cmd = [
        "ffmpeg", "-y", "-f", "rawvideo", "-vcodec", "rawvideo", "-pix_fmt", "rgb24",
        "-s", f"{w}x{h}", "-r", str(FPS), "-i", "-", "-i", str(wav_path),
        "-c:v", "libx264", "-crf", "22", "-preset", "medium", "-pix_fmt", "yuv420p",
        "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-shortest", str(out_mp4),
    ]
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    assert proc.stdin is not None
    poster_t = float(spec.get("poster_t", 7.2))
    saved = False
    for f_idx in range(total_frames):
        t = f_idx / FPS
        im = render_frame(t, spec, events, aspect)
        proc.stdin.write(im.tobytes())
        if not saved and t >= poster_t:
            im.save(out_poster, format="WEBP", quality=88)
            saved = True
    proc.stdin.close()
    err = proc.stderr.read() if proc.stderr else b""
    proc.wait()
    if proc.returncode != 0:
        raise RuntimeError(f"ffmpeg failed ({aspect}): {err.decode('utf-8', 'ignore')[-600:]}")
    print(f"Encoded {out_mp4} ({out_mp4.stat().st_size / 1048576:.2f} MB)")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", type=Path, required=True)
    ap.add_argument("--out-dir", type=Path, required=True)
    args = ap.parse_args()

    spec = json.loads(args.spec.read_text())
    args.out_dir.mkdir(parents=True, exist_ok=True)
    build_dir = args.spec.resolve().parent / "_build"
    build_dir.mkdir(parents=True, exist_ok=True)
    wav_path = build_dir / f"{spec['slug']}.wav"
    events = synthesize_spec_audio(spec, wav_path)
    (build_dir / f"{spec['slug']}_events.json").write_text(json.dumps(events, indent=2) + "\n")
    for aspect in ("16x9", "9x16"):
        encode_aspect(spec, events, wav_path, aspect, args.out_dir)


if __name__ == "__main__":
    main()
