#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix10 真峰修正交付：新成片 + 修正报告 + 扫值表，8800 逐字节自测后回执。"""
import hashlib, json, os, sys, urllib.parse, urllib.request

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")
REP = os.path.join(BASE, "ep03_fix10_tp09_report.json")
SWEEP = os.path.join(BASE, "ep03_fix10_tp_sweep.json")
FILES = [VID, REP, SWEEP]


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


def upload_check(fn, data):
    req = urllib.request.Request("http://localhost:8800/upload?name=" + urllib.parse.quote(fn),
                                 data=data, headers={"Content-Type": "application/octet-stream"})
    urllib.request.urlopen(req, timeout=240).read()
    dl = urllib.request.urlopen("http://localhost:8800/download?name=" + urllib.parse.quote(fn),
                                timeout=240).read()
    assert dl == data, ("MISMATCH", fn, len(data), len(dl))
    print("%-40s %10d B  sha=%s  PASS" % (fn, len(data), sha(data)), flush=True)
    return sha(data)


def main():
    rep = json.load(open(REP, encoding="utf-8"))
    sw = json.load(open(SWEEP, encoding="utf-8"))
    assert rep["tp_ok"] and rep["measured"]["tp"] <= -1.0
    assert rep["video_stream_identical"] and not rep["black_starts"]
    assert rep["fullscale_samples"] == 0
    shas = {}
    for p in FILES:
        shas[os.path.basename(p)] = upload_check(os.path.basename(p), open(p, "rb").read())
    listed = json.loads(urllib.request.urlopen("http://localhost:8800/list", timeout=20).read())
    for p in FILES:
        assert os.path.basename(p) in listed, ("NOT LISTED", os.path.basename(p))

    m = rep["measured"]
    sweep_lines = "\n".join(
        "  - 总增益 %.1fdB delta %.1f -> I=%.2f / TP=%.2f / LRA=%.1f  %s" %
        (r["target_gain_db"], r["delta_from_base_db"],
         r["measured_aac"]["lufs"], r["measured_aac"]["tp"], r["measured_aac"]["lra"],
         "过线" if r["pass_tp_minus1"] else "超线(炸)")
        for r in sw["sweep"])
    TEXT = """【EP03 fix10 · 真峰修正版 · 接 id=379，已压回 -1 以内】

按你 379 做：只动音频，画面零改动。

■ ep03_final_fix10.mp4（覆盖上一版 -1.41）
字节 **%d B** / sha256 **%s**
视频 %.2fs / 音频 %.2fs（目标 1524.48）。
**成片三项实测：I=%.2f LUFS / 真峰 %.2f dBTP / LRA=%.1f LU** —— 真峰 %.2f ≤ -1，过硬线；较上一版 -1.41 降了 0.42dB。
PCM 采样峰 %.3f dBFS，满刻度削波 **0 样本**；黑帧扫描 **0 处**。
底床（成片混音母带层）低于旁白 20.5dB（≥20 达标）——整体增益等比缩放，底床比未变；链内无压缩器/限幅器。

■ 做法（严格照 379）
- 成片混音总增益 -0.5dB → **-0.9dB**（再降 0.4dB），其余音频参数逐项不变；旁白母带 v6 未动，p67 相对电平未动。
- **视频流直接 copy**，不含二次编码：新旧裸 H.264 视频流 sha256 逐字节一致（%s）。s7_2 未重渲、12 镜未动、字幕（已烧死在画面）未动、铃铛 892.96s 未动。
- 用扫值里实测过的那支 AAC 音频流原样 mux，无二次编码。

■ AAC 真峰扫值（twoloop 非单调，逐档实测，未推算）
%s
-0.9 就过线（与你 fix9 扫值 -1.86 一致），取 -0.9；**-1.2 反而炸到 -0.64 超线**，坚决不用；-0.7 历史异常未纳入。

■ 删片口径（id=380 已确认）
旧 fix7 你已删、我不再提；fix10 验过后频道上那条未公开 fix9（UgE6x2XmuHA）由你在 Studio 删，我不动 YouTube。

■ 交付（8800 根目录逐字节 PASS）
ep03_final_fix10.mp4 / ep03_fix10_tp09_report.json / ep03_fix10_tp_sweep.json

未上传、未发布、未设定时——等你验片转未公开。球传你，重点核真峰 -1.83 与画面逐字节一致。""" % (
        rep["bytes"], rep["sha256"], rep["video_duration_s"], rep["audio_duration_s"],
        m["lufs"], m["tp"], m["lra"], m["tp"],
        rep["pcm_peak_dbfs"],
        rep["video_stream_sha256_new"][:16] + "…", sweep_lines)

    data = json.dumps({"from": "wb", "kind": "done", "text": TEXT, "files": []},
                      ensure_ascii=False).encode("utf-8")
    req = urllib.request.Request("http://localhost:8801/send?box=huajiang",
                                 data=data, headers={"Content-Type": "application/json"})
    print("REPLY:", urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "replace"), flush=True)


if __name__ == "__main__":
    main()
