#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""qc_h3.py — H3 片段质量抽检：每镜取 2 帧（35% / 85% 处）拼成带标签的联系表，便于一眼过检。

用法: python3 qc_h3.py [--shots S01,S02] [--out 05-分镜脚本/质检-H3片段.jpg]
"""
import argparse, json, os, subprocess, tempfile
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
os.chdir(ROOT)
FONT = "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"
CELL_W, CELL_H, BAR = 470, 268, 30


def dur(p):
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                        "-of", "default=nw=1:nk=1", str(p)], capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except Exception:
        return 0.0


def grab(video, t, out):
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{t:.2f}", "-i", str(video),
                    "-frames:v", "1", "-vf", f"scale={CELL_W-10}:-2", str(out)], capture_output=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--shots", default=None)
    ap.add_argument("--out", default="05-分镜脚本/质检-H3片段.jpg")
    a = ap.parse_args()

    shots = json.load(open("05-分镜脚本/shots.json", encoding="utf-8"))["shots"]
    want = {x.strip() for x in a.shots.split(",")} if a.shots else None
    rows = []
    for s in shots:
        sid = s["id"]
        if want and sid not in want:
            continue
        v = ROOT / "06-H3片段" / sid / f"{sid}.mp4"
        if not v.exists():
            continue
        rows.append((sid, s.get("lyric") or s["picture"][:18], v))
    if not rows:
        print("没有可抽检的 H3 片段"); return

    font = ImageFont.truetype(FONT, 19)
    sheet = Image.new("RGB", (2 * CELL_W, len(rows) * (CELL_H + BAR)), (245, 243, 236))
    d = ImageDraw.Draw(sheet)
    tmp = Path(tempfile.mkdtemp())
    for i, (sid, label, v) in enumerate(rows):
        y = i * (CELL_H + BAR)
        d.text((6, y + 5), f"{sid}　{label}"[:60], fill=(20, 20, 20), font=font)
        T = dur(v)
        for j, frac in enumerate((0.35, 0.85)):
            f = tmp / f"{sid}_{j}.jpg"
            grab(v, max(0.2, T * frac), f)
            if f.exists():
                im = Image.open(f).convert("RGB")
                im.thumbnail((CELL_W - 8, CELL_H - 8))
                sheet.paste(im, (j * CELL_W + (CELL_W - im.width) // 2, y + BAR + (CELL_H - im.height) // 2))
    sheet.save(a.out, quality=86)
    print(f"质检表已写 {a.out}（{len(rows)} 镜 / {sheet.size}）")


if __name__ == "__main__":
    main()
