#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 Short 1 成片质检：流参数/黑帧/削波/抽帧拼图/字幕逐句核对。"""
import json, os, re, subprocess
from PIL import Image, ImageDraw, ImageFont

BASE = r"D:/Download/muse_exchange"
OUT = os.path.join(BASE, "ep03_short1.mp4")
QADIR = os.path.join(BASE, "ep03_short1_final_qa")
os.makedirs(QADIR, exist_ok=True)


def run(a):
    r = subprocess.run(a, capture_output=True, text=True, encoding="utf-8", errors="replace")
    assert r.returncode == 0, (a[:4], (r.stderr or "")[-600:])
    return r.stdout


def probe():
    return json.loads(run(["ffprobe", "-v", "error", "-show_entries",
        "stream=index,codec_name,codec_type,width,height,pix_fmt,r_frame_rate,sample_rate,channels,duration,nb_frames,bit_rate",
        "-show_entries", "format=duration,size,format_name", "-of", "json", OUT]))


def loud():
    r = subprocess.run(["ffmpeg", "-v", "info", "-i", OUT,
        "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"],
        capture_output=True, text=True, encoding="utf-8", errors="replace")
    def g(k):
        m = re.search(r'"%s"\s*:\s*"([-\d.]+)"' % k, r.stderr)
        return float(m.group(1)) if m else None
    return {"lufs": g("input_i"), "tp": g("input_tp"), "lra": g("input_lra")}


def pcm_peak():
    r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", OUT, "-map", "0:a:0",
        "-af", "volumedetect", "-f", "null", "-"],
        capture_output=True, text=True, encoding="utf-8", errors="replace")
    m = re.search(r"max_volume:\s*([-\d.]+) dB", r.stderr)
    return float(m.group(1)) if m else None


def black_frames():
    r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", OUT,
        "-vf", "blackdetect=d=0.05:pix_th=0.10", "-an", "-f", "null", "-"],
        capture_output=True, text=True, encoding="utf-8", errors="replace")
    return re.findall(r"black_start:([-\d.]+).*?black_end:([-\d.]+)", r.stderr)


def frames():
    marks = [(1.0, "intro"), (6.0, "notbj"), (13.0, "remains"), (20.0, "burial"),
             (28.5, "fivechars"), (32.0, "taken"), (37.0, "noproof"), (40.0, "outro")]
    paths = []
    for t, name in marks:
        p = os.path.join(QADIR, "qa_%s_%04d.png" % (name, int(t * 100)))
        r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", "%.2f" % t, "-i", OUT,
                            "-frames:v", "1", p], capture_output=True)
        assert r.returncode == 0 and os.path.exists(p), (t, name)
        paths.append((t, name, p))
    # 2x4 拼图（每格 360x640）
    tw, th = 360, 640
    sheet = Image.new("RGB", (tw * 4, (th + 34) * 2), (235, 235, 235))
    d = ImageDraw.Draw(sheet)
    try:
        font = ImageFont.truetype(r"C:/Windows/Fonts/msyh.ttc", 22)
    except Exception:
        font = ImageFont.load_default()
    for i, (t, name, p) in enumerate(paths):
        im = Image.open(p).convert("RGB").resize((tw, th), Image.LANCZOS)
        x = (i % 4) * tw
        y = (i // 4) * (th + 34)
        sheet.paste(im, (x, y + 34))
        d.text((x + 8, y + 4), "%.1fs %s" % (t, name), font=font, fill=(20, 20, 20))
    sp = os.path.join(QADIR, "short1_qa_sheet.png")
    sheet.save(sp)
    return paths, sp


def subs_check():
    rep = json.load(open(os.path.join(BASE, "ep03_short1_frames_report.json"), encoding="utf-8"))
    txt = "".join(x["text"] for x in rep["subs"])
    required = ["公元1402年夏天", "南京宫城起火", "不是北京那座紫禁城", "从灰烬里扒出残骸",
                "这是皇帝", "这是皇后", "八天以后", "以天子之礼下葬", "只用了五个字",
                "帝不知所终", "胜利者派人", "没有旁证", "建文帝到底去哪儿了"]
    forbidden = ["四个字", "四字", "不知所踪", "北京那座紫禁城没"]
    return {"all": txt, "required_missing": [x for x in required if x not in txt],
            "forbidden_hit": [x for x in forbidden if x in txt],
            "count": len(rep["subs"])}


def main():
    pr = probe()
    v = [s for s in pr["streams"] if s["codec_type"] == "video"][0]
    a = [s for s in pr["streams"] if s["codec_type"] == "audio"][0]
    lm = loud()
    pk = pcm_peak()
    bk = black_frames()
    paths, sheet = frames()
    sc = subs_check()
    rep = {"probe": pr, "video": v, "audio": a, "loudness_aac": lm,
           "pcm_peak_dbfs": pk, "clipped_samples_est": "见 max_volume（<0dB 即无满刻度削波）",
           "black_segments": bk, "qa_frames": [{"t": t, "name": n, "path": p} for t, n, p in paths],
           "qa_sheet": sheet, "subs": sc,
           "checks": {
               "video_1080x1920": v["width"] == 1080 and v["height"] == 1920,
               "duration_40_8": abs(float(pr["format"]["duration"]) - 40.8) < 0.1,
               "tp_le_minus1": lm["tp"] is not None and lm["tp"] <= -1.0,
               "loudness_near_minus14": abs(lm["lufs"] + 14.0) < 0.6,
               "no_black": len(bk) == 0,
               "subs_ok": not sc["required_missing"] and not sc["forbidden_hit"],
           }}
    json.dump(rep, open(os.path.join(BASE, "ep03_short1_qa_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("PROBE", v["width"], v["height"], v["r_frame_rate"], v["nb_frames"],
          "|", a["codec_name"], a["sample_rate"], a["channels"], "|",
          pr["format"]["duration"], pr["format"]["size"], flush=True)
    print("LOUD", lm, "PCM_PEAK", pk, "BLACK", bk, flush=True)
    print("SUBS", sc, flush=True)
    print("CHECKS", rep["checks"], flush=True)
    print("SHEET", sheet, flush=True)

if __name__ == "__main__":
    main()
