# -*- coding: utf-8 -*-
"""EP03 fix9 第2步：旁白母带 v5 —— 以 v4 为基线，只换 p62(s42) + p67(s44)。
花酱 wb id=364：刚耳检通过 p62 s42(18.56s,sha aca26d52..)、p67 s44(22.72s,sha 0a973d23..)，
其余 107 段一律沿用母带 v4；混音链与 v4 相同（120Hz 陷波 → loudnorm dynamic → 48k
→ afade → -0.25dB，禁压缩器/限幅器）。输出 ep03_narration_master_v5.wav + 全109段时长表。
"""
import json, wave, os, subprocess, re, sys, time, hashlib

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

BASE = r"D:/Download/muse_exchange"
D4 = json.load(open(os.path.join(BASE, "ep03_durations_v4.json"), encoding="utf-8"))

# fix9 第1步定稿两段（花酱 id=364 点名）
FIX9 = {
    "p062": ("ep03_vox_fix9/ep03_fix9_p62_s42.wav", 18.56, "aca26d52cbbb7f537e0d"),
    "p067": ("ep03_vox_fix9/ep03_fix9_p67_s44.wav", 22.72, "0a973d237652dc991557"),
}

def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()

dur, files = {}, {}
for i in range(1, 110):
    tag = "p%03d" % i
    base = D4[tag]
    dur[i] = base["duration_s"]
    files[i] = base["file"]

for tag, (rel, exp_dur, exp_sha) in FIX9.items():
    p = os.path.join(BASE, rel)
    assert os.path.exists(p), rel
    w = wave.open(p)
    real = round(w.getnframes() / w.getframerate(), 3)
    w.close()
    assert abs(real - exp_dur) < 0.01, (tag, real, exp_dur)
    h = sha(p)
    assert h.startswith(exp_sha), (tag, h, exp_sha)
    i = int(tag[1:])
    files[i] = os.path.abspath(p).replace("\\", "/")
    dur[i] = real
    print("fix9", tag, "dur", real, "sha", h[:16], os.path.getsize(p), "B", flush=True)

# 硬断言：除 p62/p67 外，逐段 file+duration 与 v4 完全一致（证明其余107段沿用v4）
changed = set()
for i in range(1, 110):
    tag = "p%03d" % i
    same_file = (files[i] == D4[tag]["file"])
    same_dur = (dur[i] == D4[tag]["duration_s"])
    if not (same_file and same_dur):
        changed.add(tag)
assert changed == {"p062", "p067"}, ("意外改动段", changed)
print("UNCHANGED 107/109 segments: PASS", flush=True)

TOTAL = round(sum(dur.values()), 2)
BELL = round(sum(dur[i] for i in range(1, 73)), 2)
print("TOTAL v5", TOTAL, "(v4 1525.92, delta %.2f)" % (TOTAL - 1525.92), flush=True)
print("BELL p73 start", BELL, "(v4 894.40, delta %.2f)" % (BELL - 894.40), flush=True)

# 写时长表 v5（结构同 v4）
d5 = {}
for i in range(1, 110):
    d5["p%03d" % i] = {"duration_s": dur[i], "file": files[i]}
json.dump(d5, open(os.path.join(BASE, "ep03_durations_v5.json"), "w", encoding="utf-8"),
          ensure_ascii=False, indent=2)

# 拼接 109 段 -> raw_v5
concat = os.path.join(BASE, "ep03_raw_v5_concat.txt")
with open(concat, "w", encoding="utf-8") as f:
    for i in range(1, 110):
        f.write("file '%s'\n" % files[i])
RAW5 = os.path.join(BASE, "ep03_raw_v5_concat.wav")
subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", concat,
                "-c", "copy", RAW5], check=True, cwd=BASE)
w = wave.open(RAW5); raw_dur = round(w.getnframes() / w.getframerate(), 3); w.close()
print("raw_v5 dur", raw_dur, flush=True)
assert abs(raw_dur - TOTAL) < 0.05, (raw_dur, TOTAL)

# 过 v4 同链（无压缩/限幅）
OUT = os.path.join(BASE, "ep03_narration_master_v5.wav")
af = ("bandreject=f=120:w=50,loudnorm=I=-14:TP=-1:LRA=11,aresample=48000,"
      "afade=t=in:st=0:d=0.05,afade=t=out:st=%.2f:d=0.05,volume=-0.25dB" % (TOTAL - 0.05))
t = time.time()
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", RAW5, "-af", af, "-c:a", "pcm_s16le", OUT],
               check=True, cwd=BASE)
print("master v5 done %.1fs" % (time.time() - t), os.path.getsize(OUT), flush=True)

def meas(p):
    r = subprocess.run(["ffmpeg", "-v", "info", "-i", p,
       "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"],
       capture_output=True, text=True)
    def g(k):
        m = re.search(r'"%s"\s*:\s*"([-\d.]+)"' % k, r.stderr)
        return float(m.group(1)) if m else None
    return {"lufs": g("input_i"), "tp": g("input_tp"), "lra": g("input_lra")}

m5 = meas(OUT)
m4 = meas(os.path.join(BASE, "ep03_narration_master_v4.wav"))
print("MASTER v5 LUFS/TP/LRA:", m5, flush=True)
print("MASTER v4 LUFS/TP/LRA:", m4, flush=True)

rep = {
    "step": "EP03 fix9 step2 - narration master v5",
    "order": "wb id=364 (gang ear-check p62 s42 / p67 s44)",
    "baseline": "ep03_durations_v4.json / ep03_narration_master_v4.wav",
    "changed_segments": {
        "p062": {"file": FIX9["p062"][0], "duration_s": dur[62], "sha256": sha(files[62]),
                 "prev_duration_s": D4["p062"]["duration_s"]},
        "p067": {"file": FIX9["p067"][0], "duration_s": dur[67], "sha256": sha(files[67]),
                 "prev_duration_s": D4["p067"]["duration_s"]},
    },
    "unchanged_segments": 107,
    "total_s": TOTAL, "prev_total_s": 1525.92,
    "bell_p73_start_s": BELL, "prev_bell_p73_start_s": 894.40,
    "master": {"file": os.path.basename(OUT), "bytes": os.path.getsize(OUT),
               "sha256": sha(OUT), "measured": m5},
    "master_v4_measured": m4,
    "chain": "bandreject f=120 w=50 -> loudnorm I=-14 TP=-1 LRA=11 -> aresample 48000 -> afade in/out 0.05 -> volume -0.25dB (no compressor/limiter)",
}
json.dump(rep, open(os.path.join(BASE, "ep03_fix9_master_v5_report.json"), "w", encoding="utf-8"),
          ensure_ascii=False, indent=2)
print("REPORT ep03_fix9_master_v5_report.json", flush=True)
