# -*- coding: utf-8 -*-
"""EP03 fix10 成片 QA：三项实测 + PCM 峰/削波 + 黑帧扫描 + s7_2/铃铛验证帧。"""
import json, os, re, subprocess, sys, wave

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

BASE = r"D:/Download/muse_exchange"
VID = os.path.join(BASE, "ep03_final_fix10.mp4")
OUT = os.path.join(BASE, "ep03_fix10_final_qa")
WAV = os.path.join(BASE, "ep03_fix10_final_check.wav")
os.makedirs(OUT, exist_ok=True)

PICKS = [
    ("s6_1_p64", 748.0, "s6_1 复用 fix9（v5 时序）不动，p64 卡片与字幕对位"),
    ("s7_1", 780.0, "s7_1 复用镜紧邻 p67 新起点 786.24s"),
    ("s7_2_p67_age", 800.0, "p67 重渲：年龄对照卡，僧人脸不遮广西地图点"),
    ("s7_2_p68", 812.0, "p68 起 809.12s：诡称·按问·乃杨行祥卡"),
    ("s7_2_p70", 838.0, "p70 起约 832.00s：迎回西内养老 × 与提问卡"),
    ("bell_894", 894.0, "铃铛 p73 起点 892.96s，画面与母带音对齐"),
    ("tail", 1520.0, "尾帧评论区卡与收尾字幕"),
]


def run(args):
    return subprocess.run(args, capture_output=True, text=True,
                          encoding="utf-8", errors="replace")


def main():
    assert os.path.exists(VID)
    for tag, t, what in PICKS:
        p = os.path.join(OUT, "fix10_" + tag + ".png")
        subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-loglevel", "error", "-y",
                        "-ss", "%.2f" % t, "-i", VID, "-frames:v", "1", p], check=True)
        print("FRAME", tag, "t=%.2f" % t, os.path.getsize(p), "B |", what, flush=True)

    from PIL import Image, ImageDraw
    thumbs = []
    for tag, _, _ in PICKS:
        im = Image.open(os.path.join(OUT, "fix10_" + tag + ".png")).convert("RGB")
        thumbs.append((tag, im.resize((640, 360))))
    W, H = 1280, 390 * 4
    sheet = Image.new("RGB", (W, H), (245, 243, 238))
    dr = ImageDraw.Draw(sheet)
    for i, (tag, im) in enumerate(thumbs):
        x, y = (i % 2) * 640, (i // 2) * 390
        sheet.paste(im, (x, y + 24))
        dr.text((x + 6, y + 5), tag, fill=(30, 30, 30))
    sheet_p = os.path.join(OUT, "fix10_qa_sheet.png")
    sheet.save(sheet_p)
    print("SHEET", os.path.getsize(sheet_p), "B", flush=True)

    # 三项实测
    r = run(["ffmpeg", "-v", "info", "-i", VID,
             "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"])
    def g(k):
        m = re.search(r'"%s"\s*:\s*"([-\d.]+)"' % k, r.stderr)
        return float(m.group(1)) if m else None
    meas = {"lufs": g("input_i"), "tp": g("input_tp"), "lra": g("input_lra")}
    print("MEAS", meas, flush=True)

    # PCM 采样峰与满刻度削波数
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", VID, "-vn",
                    "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "1", WAV], check=True)
    import numpy as np
    w = wave.open(WAV)
    a = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2")
    w.close()
    peak = int(np.abs(a.astype(np.int32)).max())
    fullscale = int(np.count_nonzero((a == -32768) | (a == 32767)))
    import math
    peak_db = round(20 * math.log10(peak / 32768.0), 3) if peak else None
    print("PCM peak", peak, peak_db, "dBFS fullscale samples", fullscale, flush=True)

    # 黑帧扫描（>50ms 纯黑）
    b = run(["ffmpeg", "-hide_banner", "-nostdin", "-v", "info", "-i", VID,
             "-vf", "blackdetect=d=0.05:pix_th=0.10", "-an", "-f", "null", "-"])
    blacks = re.findall(r"black_start:([0-9.]+)", b.stderr)
    print("BLACK starts", len(blacks), blacks[:20], flush=True)

    probe = json.loads(run(["ffprobe", "-v", "error", "-show_entries",
                            "stream=codec_type,duration", "-of", "json", VID]).stdout)
    vdur = max((float(s["duration"]) for s in probe["streams"] if s["codec_type"] == "video"), default=0)
    adur = max((float(s["duration"]) for s in probe["streams"] if s["codec_type"] == "audio"), default=0)
    rep = {
        "file": os.path.basename(VID),
        "bytes": os.path.getsize(VID),
        "video_duration_s": round(vdur, 3), "audio_duration_s": round(adur, 3),
        "measured": meas,
        "pcm_peak_sample": peak, "pcm_peak_dbfs": peak_db,
        "fullscale_samples": fullscale,
        "black_starts": blacks,
        "frames": [{"tag": t, "time_s": s, "check": what} for t, s, what in PICKS],
        "sheet": os.path.basename(sheet_p),
    }
    json.dump(rep, open(os.path.join(BASE, "ep03_fix10_qa_report.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    print("QA REPORT written", flush=True)


if __name__ == "__main__":
    main()
