# -*- coding: utf-8 -*-
"""EP03 fix6 第2步 验证帧+母带数据 打包回传（验过再拼合）。"""
import os, hashlib, json, zipfile, subprocess, sys

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

EX = r"D:/Download/muse_exchange"
QA = os.path.join(EX, "ep03_fix6_qa")
ZIP = os.path.join(EX, "ep03_fix6_5shots_qa.zip")
SHEET = os.path.join(QA, "ep03_fix6_5shots_qa_sheet.png")

def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()

# 打包 QA 目录全部 png
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as z:
    for fn in sorted(os.listdir(QA)):
        if fn.lower().endswith(".png"):
            z.write(os.path.join(QA, fn), "ep03_fix6_qa/" + fn)
print("zip", os.path.getsize(ZIP), sha(ZIP), flush=True)

# QA 拼图也单独放根目录（方便直接取）
ROOT_SHEET = os.path.join(EX, "ep03_fix6_5shots_qa_sheet.png")
import shutil
shutil.copy2(SHEET, ROOT_SHEET)
print("sheet", os.path.getsize(ROOT_SHEET), sha(ROOT_SHEET), flush=True)

# 8800 /list + 下载逐字节自测
import urllib.request
base = "http://localhost:8800"
lst = json.load(urllib.request.urlopen(base + "/list", timeout=10))
for remote, local in [("ep03_fix6_5shots_qa.zip", ZIP),
                      ("ep03_fix6_5shots_qa_sheet.png", ROOT_SHEET)]:
    assert remote in lst, "list 未列 " + remote
    data = urllib.request.urlopen(base + "/download?name=" + remote, timeout=60).read()
    assert data == open(local, "rb").read(), "下载字节不符 " + remote
    print("8800 SELFTEST PASS", remote, len(data), flush=True)

# 写数据包（母带三项实测）
report = {
    "step": "ep03_fix6_step2_master_v3_and_qa_frames",
    "master_v3": {
        "file": "ep03_narration_master_v3.wav",
        "duration_s": 1524.48,
        "bytes": os.path.getsize(os.path.join(EX, "ep03_narration_master_v3.wav")),
        "sha256": sha(os.path.join(EX, "ep03_narration_master_v3.wav")),
        "loudness_lufs": -16.36, "true_peak_dbtp": -1.17,
        "v2_reference": {"lufs": -15.73, "tp": -1.16},
        "chain": "bandreject=f=120:w=50 -> loudnorm dynamic I=-14:TP=-1:LRA=11 -> aresample=48000 -> afade(0.05s head/tail) -> volume=-0.25dB; no compressor/limiter",
        "note": "换三段后整轨 loudnorm dynamic 重算，LUFS 比 v2 低 0.63 dB（已接受例外口径，未硬凑）；真峰 -1.17 未超 -1 线。",
    },
    "changed_segments": {
        "p04": {"new_dur": 7.84, "old_dur": 7.04},
        "p61": {"new_dur": 23.68, "old_dur": 20.32},
        "p107": {"new_dur": 4.32, "old_dur": 4.32},
        "total_delta_s": 4.16,
    },
    "subs": {"ass": "subs_ep03_fix6.ass", "srt": "ep03_subs_zh_fix6.srt",
             "cues": 458, "validation": "OK", "bell_p73_start_s": 892.96},
    "qa_frames_zip": {"file": "ep03_fix6_5shots_qa.zip",
                      "bytes": os.path.getsize(ZIP), "sha256": sha(ZIP)},
    "status": "QA frames delivered; waiting for huajiang verification before assemble",
}
rp = os.path.join(EX, "ep03_fix6_qa_report.json")
json.dump(report, open(rp, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
print("report", rp, flush=True)
