# -*- coding: utf-8 -*-
"""EP03 fix10 第2步：旁白母带 v6 —— 以 v5 为基线，只换 p67(s45)。
花酱 wb id=377：刚耳检过 s45(22.88s,sha d373283d…)，其余108段沿用v5；
混音链与v5相同（120Hz陷波 → loudnorm dynamic → 48k → afade → -0.25dB，禁压缩器/限幅器）。
输出 ep03_narration_master_v6.wav + ep03_durations_v6.json（逐段起止）+ 简报。
"""
import hashlib, json, os, re, subprocess, sys, time, wave

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

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

FIX = {
    "p067": {
        "file": os.path.abspath(os.path.join(BASE, "ep03_fix10_p67_s45.wav")).replace("\\", "/"),
        "duration_s": 22.88,
        "sha_prefix": "d373283d9b640fa2",
        "prev_duration_s": 22.72,
    }
}


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


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

for tag, f in FIX.items():
    p = f["file"]
    assert os.path.exists(p), p
    w = wave.open(p)
    sr, ch, sw = w.getframerate(), w.getnchannels(), w.getsampwidth()
    real = round(w.getnframes() / sr, 3)
    w.close()
    assert (sr, ch, sw) == (48000, 1, 2), (tag, sr, ch, sw)
    assert abs(real - f["duration_s"]) < 0.01, (tag, real, f["duration_s"])
    h = sha(p)
    assert h.startswith(f["sha_prefix"]), (tag, h, f["sha_prefix"])
    i = int(tag[1:])
    files[i] = os.path.abspath(p).replace("\\", "/")
    dur[i] = real
    print("fix10", tag, "dur", real, "sha", h[:16], os.path.getsize(p), "B", flush=True)

changed = set()
for i in range(1, 110):
    tag = "p%03d" % i
    if files[i] != D5[tag]["file"] or dur[i] != D5[tag]["duration_s"]:
        changed.add(tag)
assert changed == {"p067"}, ("意外改动段", changed)
print("UNCHANGED 108/109 segments: PASS", flush=True)

starts, ends = {}, {}
acc = 0.0
for i in range(1, 110):
    starts[i] = round(acc, 2)
    acc = round(acc + dur[i], 2)
    ends[i] = acc
TOTAL = acc
BELL = starts[73]
assert abs(starts[67] - 786.24) < 0.011, starts[67]
assert abs(ends[67] - 809.12) < 0.011, ends[67]
assert abs(TOTAL - 1524.48) < 0.011, TOTAL
assert abs(BELL - 892.96) < 0.011, BELL
assert abs(dur[67] - 22.88) < 0.011, dur[67]
print("TOTAL v6", TOTAL, "(v5 1524.32, delta +0.16)", flush=True)
print("p67 %.2f-%.2f  BELL p73 start %.2f (v5 892.80, delta +0.16)" %
      (starts[67], ends[67], BELL), flush=True)

# 时长表 v6：沿用 v5 的 duration_s/file，另加逐段 start_s/end_s（花酱点名要起止）
d6 = {}
for i in range(1, 110):
    d6["p%03d" % i] = {
        "start_s": starts[i], "end_s": ends[i],
        "duration_s": dur[i], "file": files[i],
    }
json.dump(d6, open(os.path.join(BASE, "ep03_durations_v6.json"), "w", encoding="utf-8"),
          ensure_ascii=False, indent=2)

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

OUT = os.path.join(BASE, "ep03_narration_master_v6.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", RAW, "-af", af, "-c:a", "pcm_s16le", OUT],
               check=True, cwd=BASE)
w = wave.open(OUT)
out_dur = round(w.getnframes() / w.getframerate(), 3)
w.close()
assert abs(out_dur - TOTAL) < 0.05, (out_dur, TOTAL)
print("master v6 done %.1fs" % (time.time() - t), os.path.getsize(OUT), "B", 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")}


m6 = meas(OUT)
V5WAV = os.path.join(BASE, "ep03_narration_master_v5.wav")
m5 = meas(V5WAV)
print("MASTER v6 LUFS/TP/LRA:", m6, flush=True)
print("MASTER v5 LUFS/TP/LRA:", m5, flush=True)
assert abs(m6["lufs"] - m5["lufs"]) < 0.12, (m6, m5)
assert m6["tp"] <= -1.0, m6

# 逐样本抽查：p67 前 3s（loudnorm 前瞻）之外应与 v5 完全一致
def prefix_equal(path_a, path_b, seconds):
    n = int(seconds * 48000)
    wa, wb = wave.open(path_a), wave.open(path_b)
    fa, fb = wa.readframes(n), wb.readframes(n)
    wa.close(); wb.close()
    return fa == fb


prefix_ok = prefix_equal(V5WAV, OUT, 783.0)
print("PREFIX 0-783s identical:", prefix_ok, flush=True)
assert prefix_ok, "p67 前样本被意外改动"

rep = {
    "step": "EP03 fix10 step2 - narration master v6",
    "order": "wb id=377 (gang ear-check p67 s45 PASS)",
    "baseline": "ep03_durations_v5.json / ep03_narration_master_v5.wav",
    "changed_segments": {
        "p067": {
            "file": FIX["p067"]["file"],
            "duration_s": dur[67], "sha256": sha(files[67]),
            "prev_duration_s": FIX["p067"]["prev_duration_s"],
            "start_s": starts[67], "end_s": ends[67],
        }
    },
    "unchanged_segments": 108,
    "total_s": TOTAL, "prev_total_s": 1524.32,
    "p67_start_s": starts[67], "p67_end_s": ends[67],
    "bell_p73_start_s": BELL, "prev_bell_p73_start_s": 892.80,
    "master": {"file": os.path.basename(OUT), "bytes": os.path.getsize(OUT),
               "sha256": sha(OUT), "duration_s": out_dur, "measured": m6},
    "master_v5_measured": m5,
    "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)",
    "sample_check": {
        "prefix_identical_until_s": 783.0,
        "note": "p67 前 0-783s 与 v5 逐样本完全一致（786s 起出现差异=loudnorm 动态 3s 前瞻进入 p67，属同链正常现象）；p67 后主体差异 0.2-0.5% 为同链量化/前瞻残留。",
    },
    "bed_note": "旁白母带无 BGM 底床；混音链与 v5 逐参数一致，底床比在 fix10 成片混音阶段复核（沿用 -0.5dB）",
}
json.dump(rep, open(os.path.join(BASE, "ep03_fix10_master_v6_report.json"), "w", encoding="utf-8"),
          ensure_ascii=False, indent=2)
print("REPORT ep03_fix10_master_v6_report.json", flush=True)
