# -*- coding: utf-8 -*-
"""EP03 fix6 5镜验证帧：从重渲 shots 抽关键帧，拼 QA 图（交花酱验）。"""
import os, subprocess, json, sys
from PIL import Image, ImageDraw

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

BASE = r"D:/Download/muse_exchange/ep03_package/ep03_package"
SHOTS = os.path.join(BASE, "shots")
OUT = r"D:/Download/muse_exchange/ep03_fix6_qa"
os.makedirs(OUT, exist_ok=True)

d = json.load(open(r"D:/Download/muse_exchange/ep03_durations_v3.json", encoding="utf-8"))
st = {}; t = 0.0
for i in range(1, 110):
    st[i] = t; t += d["p%03d" % i]["duration_s"]

# (镜, 全局时间, 文件名, 说明)
POINTS = [
    ("s1_1", st[1] + 4,    "s1_1_p01_label_ON",  "S1-1 标签应在(p01 中)"),
    ("s1_1", st[3] + 2,    "s1_1_p03_label_OFF", "S1-1 标签应消失(p01 讲完)"),
    ("s1_2", st[5] + 2,    "s1_2_p05",           "S1-2 画面(p04 字幕属ASS,另验)"),
    ("s2_1", st[9] + 3,    "s2_1_legend",        "S2-1 图例补橙色分级"),
    ("s6_1", st[61] + 3,   "s6_1_p61_timeline",  "S6-1 时间轴卡新文案"),
    ("s10_1", st[107] + 2, "s10_1_p107_nobracket", "S10-1 p107 去括号"),
]
SHOT_START = {"s1_1": st[1], "s1_2": st[5], "s2_1": st[9],
              "s6_1": st[55], "s10_1": st[99]}

frames = []
for name, gt, fn, desc in POINTS:
    local = gt - SHOT_START[name]
    src = os.path.join(SHOTS, name + ".mp4")
    dst = os.path.join(OUT, fn + ".png")
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", "%.3f" % local,
                    "-i", src, "-frames:v", "1", dst], check=True)
    frames.append((fn, desc, dst))
    print(fn, "local %.2fs" % local, os.path.getsize(dst), flush=True)

# 拼 2 列 x 3 行 QA 图
TW, TH = 640, 360
sheet = Image.new("RGB", (TW * 2, (TH + 30) * 3), (245, 242, 236))
dr = ImageDraw.Draw(sheet)
for k, (fn, desc, dst) in enumerate(frames):
    im = Image.open(dst).convert("RGB").resize((TW, TH))
    x = (k % 2) * TW; y = (k // 2) * (TH + 30)
    sheet.paste(im, (x, y))
    dr.text((x + 8, y + TH + 6), "%s | %s" % (fn, desc), fill=(40, 40, 40))
qa = os.path.join(OUT, "ep03_fix6_5shots_qa_sheet.png")
sheet.save(qa)
print("QA sheet:", qa, os.path.getsize(qa), flush=True)
