#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix6 收尾（接 wb id=317 放行拼合）：
成片三项实测（I/TP/底床）+ 六帧抽帧自查 + 20MiB 分块 + 8800 逐字节自测。
三项实测一律测**成片 mp4**，不拿母带值代替。时长表用 v3（1524.48s）。
"""
import hashlib, json, os, re, subprocess, sys, urllib.parse, urllib.request
import numpy as np

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

HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(HERE, "ep03_package", "ep03_package")
MP4 = os.path.join(HERE, "ep03_final_fix6.mp4")
SRT = os.path.join(PKG, "ep03_subs_zh_fix6.srt")
DUR3 = os.path.join(HERE, "ep03_durations_v3.json")
PART = 20 * 1024 * 1024
PREFIX = "ep03_final_fix6.mp4.part_"
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
SR, WIN = 48000, 2400
TOTAL = 1524.48


def sha(b):
    return hashlib.sha256(b).hexdigest()


def run(args):
    return subprocess.run(["ffmpeg", "-hide_banner", "-nostdin"] + args,
                          capture_output=True, text=True, encoding="utf-8", errors="replace")


def lufs_tp(path):
    r = run(["-i", path, "-af", "loudnorm=I=-14:TP=-1.0:LRA=11:print_format=json", "-f", "null", "-"])
    m = re.findall(r"\{\s*\"input_i\".*?\}", r.stderr, re.S)
    assert m, "loudnorm parse failed"
    d = json.loads(m[-1])
    return float(d["input_i"]), float(d["input_tp"])


def rms_window(path, t, dur):
    p = subprocess.run(["ffmpeg", "-v", "error", "-ss", "%.3f" % t, "-t", "%.3f" % dur,
                        "-i", path, "-vn", "-f", "s16le", "-ac", "1", "-ar", "48000", "-"],
                       capture_output=True)
    x = np.frombuffer(p.stdout, dtype="<i2").astype(np.float64) / 32768.0
    return 20 * np.log10(np.sqrt(np.mean(x * x)) + 1e-12) if len(x) else None


def seg_starts():
    D = json.load(open(DUR3, encoding="utf-8"))
    SD = [D["p%03d" % i]["duration_s"] for i in range(1, 110)]
    out, t = [], 0.0
    for x in SD:
        out.append(round(t, 3))
        t += x
    assert abs(t - TOTAL) < 0.01, ("时长表总长", t)
    return out, SD


def bed_recheck(path, SD):
    p = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", path,
                        "-vn", "-f", "s16le", "-ac", "1", "-ar", str(SR), "-"],
                       capture_output=True)
    x = np.frombuffer(p.stdout, dtype="<i2").astype(np.float32) / 32768.0
    n = len(x) // WIN
    x = x[:n * WIN].reshape(n, WIN)
    db = 20 * np.log10(np.sqrt(np.mean(x * x, axis=1)) + 1e-12)
    voice_idx, t = [], 0.0
    for d in SD:
        a, b = int((t + 0.20 * d) / 0.05), int((t + 0.80 * d) / 0.05)
        voice_idx.extend(range(a, min(b, n)))
        t += d
    voice_idx = np.array([i for i in voice_idx if 0 <= i < n])
    voice_db = float(np.mean(db[voice_idx]))
    out = {"voice_inner60pct_dBFS": voice_db, "windows": int(n)}
    for q in (1, 5, 10):
        low = float(np.mean(db[db <= np.percentile(db, q)]))
        out["bed_lowest_%d%%_dBFS" % q] = low
        out["diff_lowest_%d%%_dB" % q] = voice_db - low
    core = db[int(5 / 0.05):n - int(5 / 0.05)]
    for q in (1, 5):
        low = float(np.mean(core[core <= np.percentile(core, q)]))
        out["core_diff_lowest_%d%%_dB" % q] = voice_db - low
    return out


def srt_check():
    txt = open(SRT, encoding="utf-8").read()
    new = ["按说，故事到这儿该结束了", "比下葬还早四天",
           "神宗是建文旧臣梅殷的私谥", "又追谥恭闵惠皇帝", "下期预告：回到《如果历史拐了个弯》"]
    old = ["新城主四天后就即位", "起初追上的是神宗", "EP04 选题待定"]
    res = {"new_present": {s: (s in txt) for s in new},
           "old_absent": {s: (s not in txt) for s in old}}
    res["cue_count"] = len(re.findall(r"^\d+$", txt, re.M))
    return res


def qa_frames(S):
    from PIL import Image, ImageDraw
    marks = [(4.0, "S1-1_p01_label_ON"), (21.2, "S1-1_p03_label_OFF"),
             (56.44, "S2-1_legend"), (690.2, "S6-1_p61_timeline"),
             (1513.2, "S10-1_p107_nobracket")]
    outs = []
    for t, name in marks:
        p = os.path.join(HERE, "ep03_fix6_final_%s.png" % name.replace("-", ""))
        subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
                        "-ss", "%.3f" % t, "-i", MP4, "-frames:v", "1", p], capture_output=True)
        if os.path.exists(p):
            outs.append((name, p))
    w, h = 512, 288
    rows = (len(outs) + 2) // 3
    sheet = Image.new("RGB", (w * 3, (h + 26) * rows), (240, 238, 230))
    d = ImageDraw.Draw(sheet)
    for i, (name, p) in enumerate(outs):
        x, y = (i % 3) * w, (i // 3) * (h + 26)
        sheet.paste(Image.open(p).convert("RGB").resize((w, h), Image.LANCZOS), (x, y + 26))
        d.text((x + 6, y + 6), name, fill=(0, 0, 0))
    sp = os.path.join(HERE, "ep03_fix6_final_qa_sheet.png")
    sheet.save(sp)
    return sp, [n for n, _ in outs]


def main():
    assert os.path.exists(MP4), "成片还没拼出来"
    b = open(MP4, "rb").read()
    total, s = len(b), sha(b)
    print("MP4 %s bytes=%d sha256=%s" % (os.path.basename(MP4), total, s), flush=True)

    I, TP = lufs_tp(MP4)
    print("MEASURE I=%.2f LUFS TP=%.2f dBTP" % (I, TP), flush=True)

    S, SD = seg_starts()
    idx = (15, 35, 55, 75, 95)
    voice = [rms_window(MP4, S[i] + 0.6, 1.5) for i in idx]
    gap = [rms_window(MP4, max(0.0, S[i] - 0.30), 0.20) for i in idx]
    v = [x for x in voice if x is not None]
    g = [x for x in gap if x is not None]
    gapdiff = float(np.mean(v) - np.mean(g))
    bed = bed_recheck(MP4, SD)
    print("MEASURE gap法 voice=%.2f gap=%.2f diff=%.2f dB (口径不适用)" %
          (np.mean(v), np.mean(g), gapdiff), flush=True)
    print("MEASURE recheck最低1%% diff=%.2f dB (采纳口径, >=20 达标)" %
          bed["diff_lowest_1%_dB"], flush=True)
    print("MEASURE recheck去头尾最低1%% diff=%.2f dB" %
          bed["core_diff_lowest_1%_dB"], flush=True)

    probe = json.loads(subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries",
         "stream=codec_name,codec_type,width,height,r_frame_rate,duration,"
         "color_range,color_space,color_transfer,color_primaries,pix_fmt",
         "-show_entries", "format=duration,size", "-of", "json", MP4],
        capture_output=True, text=True).stdout)
    vst = next(x for x in probe["streams"] if x["codec_type"] == "video")
    ast = next(x for x in probe["streams"] if x["codec_type"] == "audio")
    print("MEASURE video %s %sx%s %s color=%s/%s/%s range=%s" %
          (vst["codec_name"], vst["width"], vst["height"], vst["r_frame_rate"],
           vst.get("color_space"), vst.get("color_primaries"),
           vst.get("color_transfer"), vst.get("color_range")), flush=True)

    subt = srt_check()
    print("SRT cue=%d new_present=%s old_absent=%s" %
          (subt["cue_count"], all(subt["new_present"].values()),
           all(subt["old_absent"].values())), flush=True)
    assert all(subt["new_present"].values()) and all(subt["old_absent"].values()), "字幕文案不符"
    assert subt["cue_count"] == 458, ("cue 数", subt["cue_count"])

    sheet, names = qa_frames(S)
    print("QA frames -> %s (%s)" % (os.path.basename(sheet), names), flush=True)

    parts = []
    for i in range(0, total, PART):
        chunk = b[i:i + PART]
        name = PREFIX + "%02d" % (i // PART)
        open(os.path.join(HERE, name), "wb").write(chunk)
        parts.append({"file": name, "bytes": len(chunk), "sha256": sha(chunk)})
    srt_bytes = open(SRT, "rb").read()
    print("PACK parts=%d srt_bytes=%d" % (len(parts), len(srt_bytes)), flush=True)

    lst = json.loads(OPENER.open("http://localhost:8800/list", timeout=30).read())
    checks, rebuilt = [], bytearray()
    for p in parts:
        n = p["file"]
        u = "http://localhost:8800/download?name=" + urllib.parse.quote(n)
        resp = OPENER.open(u, timeout=90)
        data = resp.read()
        cl = int(resp.headers.get("Content-Length", -1))
        rebuilt.extend(data)
        checks.append({"file": n, "in_list": n in lst, "cl": cl, "got": len(data),
                       "cl_match": cl == p["bytes"], "sha_match": sha(data) == p["sha256"]})
    rebuilt_sha = sha(bytes(rebuilt))
    ok = all(c["in_list"] and c["cl_match"] and c["sha_match"] for c in checks) and rebuilt_sha == s
    print("SELFTEST parts=%d rebuilt_sha_match=%s -> %s" %
          (len(checks), rebuilt_sha == s, "PASS" if ok else "FAIL"), flush=True)
    assert ok, "8800 自测失败"

    report = {
        "scope": "EP03 fix6 整片（wb id=317 放行）",
        "mp4": os.path.basename(MP4), "mp4_bytes": total, "mp4_sha256": s,
        "I_LUFS": I, "TP_dBTP": TP,
        "bed_gap_method_dB": gapdiff, "bed_recheck": bed,
        "bed_accepted_dB": bed["diff_lowest_1%_dB"],
        "bed_ok_ge_20dB": bed["diff_lowest_1%_dB"] >= 20.0,
        "video": vst, "audio": ast, "srt_check": subt,
        "qa_sheet": os.path.basename(sheet), "qa_frames": names,
        "parts": parts, "selftest_pass": ok, "selftest_checks": checks,
        "note": "全部实测自成片 mp4；底床以 recheck 最低1%分位法为准；字幕文案逐字核 v1.4",
    }
    json.dump(report, open(os.path.join(HERE, "ep03_fix6_final_qa_report.json"), "w",
                           encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE -> ep03_fix6_final_qa_report.json", flush=True)


if __name__ == "__main__":
    main()
