# -*- coding: utf-8 -*-
"""诊断：重建 v2 拼接轨，与 v2 母带逐样本比对，反推混音链真实参数。"""
import json, wave, os, subprocess, numpy as np

BASE = r"D:/Download/muse_exchange"
RAW = os.path.join(BASE, "ep03_raw_v2_concat.wav")
MASTER = os.path.join(BASE, "ep03_package/ep03_package/ep03_narration_master_v2.wav")

d = json.load(open(os.path.join(BASE, "ep3_build/ep03_vox_full/extracted/docs/ep03_durations.json"), encoding="utf-8"))
r = json.load(open(os.path.join(BASE, "ep3_build/ep03_vox_rerecord9/docs/ep03_resynth_durations.json"), encoding="utf-8"))
# 原始段：ep03_vox/ep03_vox_pXXX.wav
files = {}
for k in d:
    pid = "p%03d" % int(k[1:])
    files[int(pid[1:])] = os.path.join(BASE, "ep03_vox", "ep03_vox_%s.wav" % pid)
# resynth 9 段覆盖（seed43 目录；p024 seed45 已提升进该目录）
for k, v in r.items():
    if v.get("alt"):
        continue
    idx = int(v["id"][1:])
    p = os.path.join(BASE, "ep03_vox_resynth_seed43", "ep03_vox_%s.wav" % v["id"])
    if os.path.exists(p):
        files[idx] = p
        print("override", v["id"], "->", os.path.basename(p), round(v["duration_s"], 2))

# 按 1..109 拼接
concat = os.path.join(BASE, "ep03_raw_v2_concat.txt")
with open(concat, "w", encoding="utf-8") as f:
    for i in range(1, 110):
        f.write("file '%s'\n" % files[i].replace("\\", "/"))

# concat demuxer 拼接（48k/mono/s16 原生，无重编码）
subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0",
                "-i", concat, "-c", "copy", RAW], check=True, cwd=BASE)

wr = wave.open(RAW, "rb"); wm = wave.open(MASTER, "rb")
raw = np.frombuffer(wr.readframes(wr.getnframes()), dtype="<i2").astype(np.float64)
mst = np.frombuffer(wm.readframes(wm.getnframes()), dtype="<i2").astype(np.float64)
print("raw frames", len(raw), "master frames", len(mst), "diff", len(raw) - len(mst))
n = min(len(raw), len(mst)); raw = raw[:n]; mst = mst[:n]
# 相关性 & 比例
corr = np.corrcoef(raw, mst)[0, 1]
scale = (raw @ mst) / (raw @ raw)
print("corr", round(corr, 6), "scale master/raw", round(scale, 6),
      "dB", round(20 * np.log10(abs(scale)), 3))
# 逐样本残差（比例后）
resid = mst - scale * raw
print("resid rms dBFS", round(20 * np.log10(np.sqrt((resid**2).mean()) / 32768 + 1e-12), 2),
      "master rms dBFS", round(20 * np.log10(np.sqrt((mst**2).mean()) / 32768), 2))
# 前 30s 每秒相关性（看是否全程同一比例 / 有无淡入淡出）
for sec in [0, 1, 2, 5, 30, 700, 1500, 1518, 1519]:
    a = raw[sec*48000:(sec+1)*48000]; b = mst[sec*48000:(sec+1)*48000]
    if len(a) < 1000: continue
    c = np.corrcoef(a, b)[0, 1]
    s = (a @ b) / (a @ a) if (a @ a) else 0
    print("  sec", sec, "corr", round(c, 5), "scale", round(s, 5))
