#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学线 05/06/07 成片渲染（通用版，参数化自 chili04_render_review.py）

用法: python sci_render.py 05             -> 全量渲染
      python sci_render.py 05 --preview   -> 关键帧预览
规格（锁死）：
  1080x1920 / 30fps / H.264 / AAC 48k 单声道 / 60-90 秒
  底图满幅铺满、字幕条中心锁死 SUB_CY=1600、底部 12%(y>1690) 是视频号 UI 遮挡区不进内容
  每图 0.32s 淡入；AI 标识仅开头 3 秒；AIGC 元数据
  片尾「关注栖迟 / 科学 · NN ｜ 标题」；**禁 YouTube 口径**
"""
import json
import os
import subprocess
import sys
import time
import glob

from PIL import Image, ImageDraw, ImageFont

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sci_cfg import ep_paths, EPS

EP = sys.argv[1]
P = ep_paths(EP)
CFG = EPS[EP]

FPS, W, H = 30, 1080, 1920
GAIN_DB = float(os.environ.get("SCI_GAIN_DB", "0"))
PAPER = (250, 246, 236)
INK = (44, 48, 54)
FADE = 0.32
RED_LINE = int(H * 0.88)      # 1690
SUB_CY = 1600
FONT_B = "C:/Windows/Fonts/Noto Sans SC Bold (TrueType).otf"
FONT_R = "C:/Windows/Fonts/Noto Sans SC (TrueType).otf"
_fonts = {}

# ===== 动效 clip 支持（可选）=====
# 用法: python sci_render.py 05 --motion <clip.mp4> --motion-window 24.28,42.88 [--motion-nosub]
#   clip 无字幕  -> 加 --motion-nosub 表示窗口内**仍叠加**成片字幕
#   clip 有字幕  -> 不加 --motion-nosub，窗口内不叠加成片字幕（用 clip 自带字幕）
#   窗口末尾多出的段间停顿 -> 冻结 clip 末帧
# ⚠ ffmpeg %06d 默认从 1 开始编号，取帧必须 j+1
MOTION_CLIP = None
MOTION_WIN = None
MOTION_NOSUB = False
MOTION_STRIP = None      # (y0, y1) 顶部标题栏区域，整段替换为纸色（成片满幅无标题栏）
_motion = {}
for _a in sys.argv[1:]:
    if _a == "--motion" and sys.argv.index(_a) + 1 < len(sys.argv):
        MOTION_CLIP = sys.argv[sys.argv.index(_a) + 1]
    if _a == "--motion-window" and sys.argv.index(_a) + 1 < len(sys.argv):
        _w = sys.argv[sys.argv.index(_a) + 1].split(",")
        MOTION_WIN = (float(_w[0]), float(_w[1]))
    if _a == "--motion-nosub":
        MOTION_NOSUB = True
    if _a == "--motion-strip" and sys.argv.index(_a) + 1 < len(sys.argv):
        _s = sys.argv[sys.argv.index(_a) + 1].split(",")
        MOTION_STRIP = (int(_s[0]), int(_s[1]))
if MOTION_CLIP and not MOTION_WIN:
    raise SystemExit("给了 --motion 就必须给 --motion-window 起,止秒")


def F(sz, bold=True):
    k = (sz, bold)
    if k not in _fonts:
        _fonts[k] = ImageFont.truetype(FONT_B if bold else FONT_R, sz)
    return _fonts[k]


def build_base(name):
    path = os.path.join(P["assets"], name)
    if not os.path.splitext(path)[1]:
        path += ".png"
    src = Image.open(path).convert("RGB")
    assert src.size == (W, H), "%s size=%s" % (name, src.size)
    return src


def build_tail():
    im = Image.new("RGB", (W, H), PAPER)
    d = ImageDraw.Draw(im)
    d.line((340, 760, 740, 760), fill=(120, 110, 96), width=3)
    d.text((W // 2, 900), "关注栖迟", font=F(120), fill=INK, anchor="mm")
    d.text((W // 2, 1050), "科学 · %s   ｜   %s" % (EP, CFG["title"]),
           font=F(46, False), fill=(120, 110, 96), anchor="mm")
    d.line((340, 1160, 740, 1160), fill=(120, 110, 96), width=3)
    return im


def draw_subtitle(im, text):
    d = ImageDraw.Draw(im, "RGBA")
    sz = 56
    f = F(sz)
    maxw = W - 160
    while d.textlength(text, font=f) > maxw and sz > 34:
        sz -= 2
        f = F(sz)
    tw = d.textlength(text, font=f)
    cx, cy = W // 2, SUB_CY
    pw, ph = min(tw + 120, W - 40), sz + 56
    top, bot = cy - ph / 2, cy + ph / 2
    assert bot <= RED_LINE - 2, "字幕条越过红线: bot=%.0f" % bot
    d.rounded_rectangle((cx - pw / 2, top, cx + pw / 2, bot), radius=18,
                        fill=(255, 252, 244, 216), outline=(228, 220, 202, 255), width=2)
    d.text((cx, cy), text, font=f, fill=INK, anchor="mm")


def draw_ai(im):
    d = ImageDraw.Draw(im)
    s = "含 AI 生成内容"
    f = F(34)
    tw = d.textlength(s, font=f)
    d.rounded_rectangle((W - 60 - tw - 40, 110, W - 60, 110 + 62), 14, (44, 48, 54))
    d.text((W - 60 - tw / 2 - 20, 141), s, font=f, fill=(250, 246, 236), anchor="mm")
    d.rounded_rectangle((60, H - 190, 96, H - 154), 6, (44, 48, 54))
    d.text((72, H - 172), "AI", font=F(20), fill=(250, 246, 236), anchor="mm")


def render_frame(base_cache, img, t_rel, sub, ai_on):
    im = base_cache[img].copy()
    if t_rel < FADE:
        im = Image.blend(Image.new("RGB", im.size, PAPER), im, t_rel / FADE)
    if sub:
        draw_subtitle(im, sub)
    if ai_on:
        draw_ai(im)
    return im


def decode_motion(clip):
    """解码动效 clip 为帧序列（D 盘，幂等）。返回 (帧目录, 帧数)。
    目录名带 clip 文件名后缀，避免不同 clip 的帧混用（旧目录不删，改名归档）。"""
    tag = os.path.splitext(os.path.basename(clip))[0]
    d = os.path.join(P["prod"], "motion_frames_" + tag)
    os.makedirs(d, exist_ok=True)
    have = len(glob.glob(os.path.join(d, "m*.png")))
    if have < 2:
        subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-y", "-i", clip,
                        os.path.join(d, "m%06d.png")],
                       capture_output=True, text=True, encoding="utf-8", errors="replace")
        have = len(glob.glob(os.path.join(d, "m*.png")))
    return d, have


def motion_frame(d, nframes, t_rel, span):
    """按时间线性映射取 clip 帧（慢放/加速都支持）；超出末尾则冻结末帧。"""
    ratio = (t_rel / span) if span > 0 else 0.0
    idx = int(round(ratio * (nframes - 1)))
    idx = max(0, min(nframes - 1, idx))
    p = os.path.join(d, "m%06d.png" % (idx + 1))   # ffmpeg 从 1 编号
    if not os.path.exists(p):
        p = os.path.join(d, "m%06d.png" % nframes)
    im = Image.open(p).convert("RGB")
    if MOTION_STRIP:
        import numpy as _np
        y0, y1 = MOTION_STRIP
        a = _np.asarray(im, dtype=_np.float32)
        W = a.shape[1]
        for y in range(y0, min(y1, a.shape[0])):
            side = _np.concatenate([a[y, 0:12], a[y, W - 12:W]], axis=0)
            base = _np.median(side, axis=0)
            a[y] = base[None, :]
        im = Image.fromarray(_np.clip(a, 0, 255).astype(_np.uint8))
    return im


def main():
    preview = "--preview" in sys.argv
    tl = json.load(open(P["timeline"], encoding="utf-8"))
    segs = json.load(open(P["segments"], encoding="utf-8"))
    total = tl["total_s"]
    tail_start = total - tl["tail_s"]

    images, cur = [], None
    for s in tl["segments"]:
        if cur and cur["img"] == s["img"]:
            cur["end"] = s["end"] + s.get("pause_after", 0.2)
        else:
            cur = {"img": s["img"], "start": s["start"],
                   "end": s["end"] + s.get("pause_after", 0.2)}
            images.append(cur)
    images[-1]["end"] = tail_start
    names = sorted(set(x["img"] for x in images))
    bases = {n: build_base(n) for n in names}
    print("images=%d distinct=%d total=%.2fs tail@%.2fs" %
          (len(images), len(names), total, tail_start), flush=True)
    assert abs(tail_start - (segs[-1]["end"] + segs[-1]["pause_after"])) < 0.01

    tail_im = build_tail()

    # ===== 动效 clip 准备 =====
    if MOTION_CLIP:
        md, mn = decode_motion(MOTION_CLIP)
        _motion["dir"], _motion["n"] = md, mn
        assert mn >= 2, "clip 帧数不足: %d" % mn
        print("MOTION clip=%s frames=%d window=%.2f-%.2f nosub=%s" %
              (os.path.basename(MOTION_CLIP), mn, MOTION_WIN[0], MOTION_WIN[1], MOTION_NOSUB),
              flush=True)

    def frame_at(t, i=None):
        if i is None:
            i = int(round(t * FPS))
        if t >= tail_start:
            return tail_im.copy()
        # 动效窗口：clip 帧优先；字幕按 --motion-nosub 决定是否叠加
        if MOTION_CLIP and MOTION_WIN[0] <= t < MOTION_WIN[1]:
            im = motion_frame(_motion["dir"], _motion["n"], t - MOTION_WIN[0],
                              MOTION_WIN[1] - MOTION_WIN[0])
            sub = None
            if MOTION_NOSUB:
                for s in segs:
                    if s["start"] <= t < s["end"] + s["pause_after"]:
                        sub = s["sub"]
                        break
            if sub:
                draw_subtitle(im, sub)
            if t < 3.0:
                draw_ai(im)
            return im
        img = images[-1]
        for x in images:
            if x["start"] <= t < x["end"]:
                img = x
                break
        sub = None
        for s in segs:
            if s["start"] <= t < s["end"] + s["pause_after"]:
                sub = s["sub"]
                break
        return render_frame(bases, img["img"], t - img["start"], sub, t < 3.0)

    if preview:
        pdir = os.path.join(P["prod"], "preview")
        os.makedirs(pdir, exist_ok=True)
        marks = [0.2, 1.0, 3.5, 8.0, 15.0, 25.0, 40.0, 60.0, tail_start + 0.5, total - 0.3]
        for t in marks:
            frame_at(min(t, total - 0.1)).save(os.path.join(pdir, "f_%05.1f.png" % t))
        print("PREVIEW -> " + pdir, flush=True)
        return

    bases[CFG["imgs"][0]].save(P["cover"])
    print("COVER -> %s bytes=%d" % (P["cover"], os.path.getsize(P["cover"])), flush=True)

    tmpdir = os.path.join(P["prod"], "tmp_frames")
    os.makedirs(tmpdir, exist_ok=True)
    n = int(round(total * FPS))
    t0 = time.time()
    for i in range(n):
        t = i / FPS
        im = frame_at(t, i)
        im.save(os.path.join(tmpdir, "f%06d.png" % i), compress_level=1)
        if i % 300 == 0:
            print("frame %d/%d  %.1f%%  %.0fs" %
                  (i, n, 100.0 * i / n, time.time() - t0), flush=True)

    af = []
    if abs(GAIN_DB) > 1e-9:
        af = ["-af", "volume=%.2fdB" % GAIN_DB]   # 纯线性，非压缩/限幅
    # AAC 码率：192k 在瞬态段落（如硬句号停顿）重建过冲，真峰会从母带 −1.1 抬到 +1.7（超 ≤−1 规格）；
    # 实测 256k → 真峰 −1.1、320k → −1.0，故用 256k。可用 SCI_AAC_BR 覆盖。
    aac_br = os.environ.get("SCI_AAC_BR", "256k")
    ff = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-y",
                         "-framerate", str(FPS), "-i", os.path.join(tmpdir, "f%06d.png"),
                         "-i", P["master"]] + af +
                        ["-c:v", "libx264", "-preset", "medium", "-crf", "18",
                         "-pix_fmt", "yuv420p", "-r", str(FPS),
                         "-c:a", "aac", "-b:a", aac_br, "-ar", "48000", "-ac", "1",
                         "-shortest",
                         "-metadata", "comment=AIGC: AI-generated video (VoxCPM2 02 voice, whiteboard images); AI 标识仅开头3秒",
                         P["out"]], capture_output=True, text=True, encoding="utf-8",
                        errors="replace")
    assert ff.returncode == 0, ff.stderr[-1500:]
    print("OUT -> %s  bytes=%d  cost=%.1fmin" %
          (P["out"], os.path.getsize(P["out"]), (time.time() - t0) / 60), flush=True)


if __name__ == "__main__":
    main()
