#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 全渲收尾：成片三项实测 + 逐镜抽帧触发 + 分块回传。

三项实测（tim 箱 id=166）：
  1) 成片 mp4 的 I（LUFS）与真峰（dBTP）—— 必测成片，不拿母带值代替
  2) 间隙底床比人声低 >= 20 dB —— 沿用 EP02 v6 验收窗口口径
     （段起点 +0.6s 起 1.5s 为人声窗；段起点 -0.30s 起 0.20s 为间隙窗）
  3) 编码 Rec.709/limited（tv,bt709,bt709,bt709）、1280x720/30、时长
分块：ep03_final.mp4.part_00..NN（20 MiB/块）+ subs_ep03.ass 单独放根目录。
"""
import hashlib
import json
import os
import re
import subprocess
import sys

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(PKG, "ep03_final.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
FF = "ffmpeg"


def run(a, capture=True):
    return subprocess.run([FF, "-hide_banner", "-nostdin"] + a,
                          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: " + path
    d = json.loads(m[-1])
    return float(d["input_i"]), float(d["input_tp"])


def rms_window(path, t, dur):
    p = subprocess.run([FF, "-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 v.get("alt"):
            continue
        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


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

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

    S = seg_starts()
    idx = (15, 35, 55, 75, 95)          # EP02 v6 同口径的 5 个采样段
    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]
    diff = float(np.mean(v) - np.mean(g))
    print("MEASURE voice=%.2f dBFS  gap=%.2f dBFS  diff=%.2f dB (>=20 达标)" %
          (np.mean(v), np.mean(g), diff), 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(s for s in probe["streams"] if s["codec_type"] == "video")
    ast = next(s for s in probe["streams"] if s["codec_type"] == "audio")
    print("MEASURE video %s %sx%s %s color_range=%s space=%s prim=%s transfer=%s" %
          (vst["codec_name"], vst["width"], vst["height"], vst["r_frame_rate"],
           vst.get("color_range"), vst.get("color_space"),
           vst.get("color_primaries"), vst.get("color_transfer")), flush=True)
    print("MEASURE audio %s dur=%s" % (ast["codec_name"], ast["duration"]), flush=True)

    # 分块回传（根目录，8800 只认根目录文件名）
    parts = []
    for i in range(0, total, PART):
        chunk = b[i:i + PART]
        name = "ep03_final.mp4.part_%02d" % (i // PART)
        open(os.path.join(HERE, name), "wb").write(chunk)
        parts.append({"file": name, "bytes": len(chunk),
                      "sha256": hashlib.sha256(chunk).hexdigest()})
    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)

    report = {
        "mp4_bytes": total, "mp4_sha256": sha,
        "I_LUFS": I, "TP_dBTP": TP,
        "voice_rms_dBFS": float(np.mean(v)), "gap_rms_dBFS": float(np.mean(g)),
        "bed_below_voice_dB": diff, "bed_ok_ge_20dB": diff >= 20.0,
        "video": vst, "audio": ast,
        "parts": parts, "ass_bytes": len(ass_bytes),
        "note": "全部实测自成片 mp4（非母带）；响度低于 -14 为刚 2026-11-14 已接受的例外",
    }
    json.dump(report, open(os.path.join(HERE, "ep03_final_qa_report.json"), "w",
                           encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE report -> ep03_final_qa_report.json", flush=True)


if __name__ == "__main__":
    main()
