#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Short 1 v2 质检：片头标题/音频流逐字节/非片头画面/时长响度真峰/黑帧。"""
import hashlib, json, os, re, subprocess
from PIL import Image, ImageChops, ImageStat

BASE = r"D:/Download/muse_exchange"
V1 = os.path.join(BASE, "ep03_short1.mp4")
V2 = os.path.join(BASE, "ep03_short1_v2.mp4")
QA = os.path.join(BASE, "ep03_short1_v2_qa")
os.makedirs(QA, exist_ok=True)


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


def extract_audio(path, tag):
    p = os.path.join(QA, tag + ".m4a")
    run(["ffmpeg", "-v", "error", "-y", "-i", path, "-map", "0:a:0", "-c", "copy", p])
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def frame(path, t, name):
    p = os.path.join(QA, name + ".png")
    run(["ffmpeg", "-v", "error", "-y", "-ss", "%.2f" % t, "-i", path, "-frames:v", "1", p])
    return p


def loud(path):
    r = subprocess.run(["ffmpeg", "-v", "info", "-i", path,
                        "-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 black(path):
    r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", path,
                        "-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 main():
    pr = json.loads(run(["ffprobe", "-v", "error", "-show_entries",
        "stream=codec_name,codec_type,width,height,r_frame_rate,nb_frames,sample_rate,channels,duration",
        "-show_entries", "format=duration,size", "-of", "json", V2]).stdout)
    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]
    a1, a2 = extract_audio(V1, "v1_audio"), extract_audio(V2, "v2_audio")
    intro = frame(V2, 0.40, "v2_intro")
    comps = []
    for t, name in [(6.0, "notbj"), (13.0, "dispatch"), (20.0, "burial"),
                    (28.5, "fivechars"), (32.0, "taken"), (37.0, "question")]:
        p1 = frame(V1, t, "v1_" + name)
        p2 = frame(V2, t, "v2_" + name)
        d = ImageChops.difference(Image.open(p1).convert("RGB"), Image.open(p2).convert("RGB"))
        st = ImageStat.Stat(d)
        comps.append({"t": t, "name": name, "mean_abs_diff": round(sum(st.mean) / 3, 4),
                      "max_diff": max(x[1] for x in st.extrema)})
    lm1, lm2 = loud(V1), loud(V2)
    b2 = black(V2)
    rep = {"probe": pr, "video": v, "audio": a,
           "audio_sha_v1": a1, "audio_sha_v2": a2, "audio_identical": a1 == a2,
           "loudness_v1": lm1, "loudness_v2": lm2, "black": b2,
           "nonintro_frame_compare": comps, "intro_frame": intro,
           "checks": {
               "audio_identical": a1 == a2,
               "loudness_identical": lm1 == lm2,
               "tp_le_minus1": lm2["tp"] is not None and lm2["tp"] <= -1.0,
               "duration_40_8": abs(float(pr["format"]["duration"]) - 40.8) < 0.1,
               "no_black": not b2,
               "nonintro_visually_identical": all(x["mean_abs_diff"] < 0.5 for x in comps),
           }}
    json.dump(rep, open(os.path.join(BASE, "ep03_short1_v2_qa_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("AUDIO", a1[:16], a2[:16], "identical", a1 == a2, flush=True)
    print("LOUD v1", lm1, "v2", lm2, flush=True)
    print("NONINTRO", comps, flush=True)
    print("BLACK", b2, "INTRO_FRAME", intro, flush=True)
    print("CHECKS", rep["checks"], flush=True)

if __name__ == "__main__":
    main()
