#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 全渲后逐镜抽帧核验（tim 箱 id=166 自查项）。

- 14 镜各 ≥1 帧；S7-2 多抽几帧看面孔与年龄对照卡/「诡称」标签同步、不遮广西点；
- S7-3 铃铛 888.8s 附近抽帧；p100/p101「信」字字幕同步抽查；
- 输出 contact sheet + 报告 JSON（**画面结论仍需人眼/花酱复验，脚本只负责取帧**）。
"""
import json
import os
import subprocess
import sys

from PIL import Image, ImageDraw

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

HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(HERE, "ep03_package", "ep03_package")
MP4 = os.path.join(PKG, "ep03_final.mp4")
OUTDIR = os.path.join(HERE, "ep03_qa_frames")
os.makedirs(OUTDIR, exist_ok=True)

DUR = os.path.join(HERE, "ep3_build", "ep03_vox_full", "extracted", "docs",
                   "ep03_durations.json")
RES = os.path.join(HERE, "ep3_build", "ep03_vox_rerecord9", "docs",
                   "ep03_resynth_durations.json")

SHOT_ROWS = [
    ("s1_1", 1, 4), ("s1_2", 5, 8), ("s2_1", 9, 20),
    ("s3_1", 21, 32), ("s4_1", 33, 44), ("s5_1", 45, 54),
    ("s6_1", 55, 64), ("s7_1", 65, 66), ("s7_2", 67, 70),
    ("s7_3", 71, 78), ("s8_1", 79, 86), ("s8_2", 87, 90),
    ("s9_1", 91, 98), ("s10_1", 99, 109),
]


def seg_starts():
    D = json.load(open(DUR, encoding="utf-8"))
    R = json.load(open(RES, encoding="utf-8"))
    SD = [D["p%03d" % i]["duration_s"] for i in range(1, 110)]
    for v in R.values():
        if v.get("alt"):
            continue
        SD[int(v["id"][1:]) - 1] = v["duration_s"]
    starts, t = [], 0.0
    for x in SD:
        starts.append(round(t, 3))
        t += x
    return starts


def grab(t, name):
    out = os.path.join(OUTDIR, name)
    r = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin",
                        "-y", "-ss", "%.3f" % t, "-i", MP4, "-frames:v", "1",
                        out], capture_output=True, text=True, encoding="utf-8",
                       errors="replace")
    if r.returncode != 0 or not os.path.exists(out):
        print("GRAB_FAIL", name, r.stderr[-300:], flush=True)
        return None
    return out


def main():
    assert os.path.exists(MP4), "全渲成片还没出来：" + MP4
    S = seg_starts()
    marks = []
    # 14 镜各取一帧（镜中点）
    for i, (nm, a, b) in enumerate(SHOT_ROWS):
        t0 = S[a - 1]
        t1 = S[b] if b < 109 else 1520.32
        marks.append(("%.2f" % ((t0 + t1) / 2), "%02d_%s" % (i + 1, nm)))
    # 重点帧
    extra = [
        (S[66] + 1.0, "x01_s7_2_p67_start"),
        (S[69] + 1.0, "x02_s7_2_p70"),
        (888.8 + 1.0, "x03_s7_3_bell_888.8"),
        (888.8 + 3.0, "x04_s7_3_bell_end"),
        (S[99] + 1.0, "x05_p100_xin"),
        (S[100] + 1.0, "x06_p101_xin"),
        (1520.32 - 2.0, "x07_tail"),
    ]
    for t, n in extra:
        marks.append(("%.2f" % t, n))

    rows = []
    for t, name in marks:
        p = grab(float(t), name + ".png")
        if p:
            rows.append({"t": float(t), "name": name, "file": p})
            print("FRAME %s @%s" % (name, t), flush=True)

    # contact sheet
    tw, th = 320, 180
    cols = 4
    rn = (len(rows) + cols - 1) // cols
    sheet = Image.new("RGB", (tw * cols, (th + 24) * rn), (238, 235, 226))
    d = ImageDraw.Draw(sheet)
    for i, r in enumerate(rows):
        im = Image.open(r["file"]).convert("RGB").resize((tw, th), Image.LANCZOS)
        x, y = (i % cols) * tw, (i // cols) * (th + 24) + 24
        sheet.paste(im, (x, y))
        d.text((x + 5, y - 18), "%s  %s" % (r["name"], r["t"]), fill=(20, 20, 20))
    sheet.save(os.path.join(HERE, "ep03_qa_contact_sheet.png"))

    json.dump(rows, open(os.path.join(HERE, "ep03_qa_frames_report.json"), "w",
                         encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE frames=%d -> ep03_qa_contact_sheet.png" % len(rows), flush=True)


if __name__ == "__main__":
    main()
