#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 修片版收尾：成片三项实测 + 五镜关键帧自查 + 分块回传 + 8800 逐字节自测。

接 wb id=205/206（放行拼合）/ id=303（11-19 催办）。
三项实测一律测**成片 mp4**（不拿母带值代替）：
  1) I (LUFS) / 真峰 (dBTP)
  2) 底床：并列报两种口径
       - EP02 v6 gap 法（段起点前 0.30s 起 0.20s）—— EP03 段间无留白，不达标属口径不适用
       - recheck 最低 1% 分位法（wb id=203 已采纳 21.62dB 为准）
  3) 编码 Rec.709/limited、1280x720/30、时长 1520.32s
分块 20MiB/块 + subs_ep03.ass；8800 只认根目录文件名，逐块下载比对。
"""
import hashlib
import json
import os
import re
import subprocess
import sys
import urllib.parse
import 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_fix5.mp4")
ASS = os.path.join(PKG, "subs_ep03.ass")
DUR = os.path.join(HERE, "ep3_build", "ep03_vox_full", "extracted", "docs",
                   "ep03_durations.json")
RES = os.path.join(HERE, "ep3_build", "ep03_vox_rerecord9", "docs",
                   "ep03_resynth_durations.json")
PART = 20 * 1024 * 1024
PREFIX = "ep03_final_fix5.mp4.part_"
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
SR, WIN = 48000, 2400  # 50ms


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


def run(args, capture=True):
    return subprocess.run(["ffmpeg", "-hide_banner", "-nostdin"] + args,
                          capture_output=capture, 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(DUR, encoding="utf-8"))
    R = json.load(open(RES, encoding="utf-8"))
    SD = [D["p%03d" % i]["duration_s"] for i in range(1, 110)]
    for v in R.values():
        if not v.get("alt"):
            SD[int(v["id"][1:]) - 1] = v["duration_s"]
    out, t = [], 0.0
    for x in SD:
        out.append(round(t, 3))
        t += x
    assert abs(t - 1520.32) < 0.01
    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 qa_frames():
    """从新成片抽五镜问题时刻，拼图供人眼复验。"""
    from PIL import Image, ImageDraw
    marks = [(329.0, "S3-1"), (743.0, "S6-1"), (779.4, "S7-1"),
             (1327.0, "S9-1"), (1463.0, "S10-1")]
    outs = []
    for t, name in marks:
        p = os.path.join(HERE, "ep03_fix5_final_%s.png" % name.replace("-", ""))
        r = subprocess.run(
            ["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
             "-ss", str(t), "-i", MP4, "-frames:v", "1", p], capture_output=True)
        if os.path.exists(p):
            outs.append((name, p))
    w, h = 512, 288
    sheet = Image.new("RGB", (w * 3, (h + 26) * 2), (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_fix5_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)

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

    # 分块（根目录，8800 只认根目录文件名）
    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)})
    ass_bytes = open(ASS, "rb").read()
    open(os.path.join(HERE, "subs_ep03.ass"), "wb").write(ass_bytes)
    print("PACK parts=%d ass_bytes=%d" % (len(parts), len(ass_bytes)), flush=True)

    # 8800 逐块自测：在列 + Content-Length + 下载字节/sha 一致 + 重组 sha 一致
    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"]})
    ass_u = "http://localhost:8800/download?name=subs_ep03.ass"
    ass_dl = OPENER.open(ass_u, timeout=60).read()
    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 and ass_dl == ass_bytes)
    print("SELFTEST parts=%d rebuilt_sha_match=%s ass_match=%s -> %s" %
          (len(checks), rebuilt_sha == s, ass_dl == ass_bytes,
           "PASS" if ok else "FAIL"), flush=True)
    assert ok, "8800 自测失败"

    report = {
        "scope": "EP03 修片版整片（wb id=205/206 放行 + id=303 催办）",
        "mp4": os.path.basename(MP4), "mp4_bytes": total, "mp4_sha256": s,
        "I_LUFS": I, "TP_dBTP": TP,
        "bed_gap_method_dB": gapdiff,
        "bed_gap_voice_dBFS": float(np.mean(v)),
        "bed_gap_rms_dBFS": float(np.mean(g)),
        "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,
        "qa_sheet": os.path.basename(sheet), "qa_frames": names,
        "parts": parts, "ass_bytes": len(ass_bytes),
        "ass_sha256": sha(ass_bytes),
        "selftest_pass": ok, "selftest_checks": checks,
        "note": ("全部实测自成片 mp4；底床以 recheck 最低 1% 分位法为准（wb id=203 "
                 "已采纳 21.62dB），EP02 v6 gap 法对 EP03 段间无留白不适用，并列报数"),
    }
    json.dump(report, open(os.path.join(HERE, "ep03_fix5_final_qa_report.json"),
                           "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE -> ep03_fix5_final_qa_report.json", flush=True)


if __name__ == "__main__":
    main()
