# -*- coding: utf-8 -*-
"""EP03 fix7 第2步：母带 v4 —— 沿用 v2/v3 链，在 v3 基线上只换 fix7 定稿六段。
六段定稿（id=337 刚耳检）：p05 s42 / p38 s42 / p40 s43 / p61 s42 / p25 s45 / p84 s44。
"""
import json, wave, os, subprocess, re, sys, time

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

BASE = r"D:/Download/muse_exchange"
DUR = json.load(open(os.path.join(BASE,"ep3_build/ep03_vox_full/extracted/docs/ep03_durations.json"),encoding="utf-8"))
RES = json.load(open(os.path.join(BASE,"ep3_build/ep03_vox_rerecord9/docs/ep03_resynth_durations.json"),encoding="utf-8"))

files = {i: os.path.join(BASE,"ep03_vox","ep03_vox_p%03d.wav"%i) for i in range(1,110)}
dur = {i: DUR["p%03d"%i]["duration_s"] for i in range(1,110)}
# 9 段重录（seed43；p024 取 alt=False=seed45 已在主目录，这里 RES 只覆盖非 alt）
for k,v in RES.items():
    if v.get("alt"): continue
    i=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[i]=p; dur[i]=v["duration_s"]
# fix6 三段（v3 基线保留 p04/p107；p61 会被 fix7 覆盖）
FIX6 = {"p04":("ep03_vox_fix6_p04.wav",4),
        "p61":("ep03_vox_fix6_p61.wav",61),
        "p107":("ep03_vox_fix6_p107.wav",107)}
for tag,(fn,i) in FIX6.items():
    p=os.path.join(BASE,fn); assert os.path.exists(p),fn
    files[i]=p; dur[i]=round(wave.open(p).getnframes()/48000,3)

# fix7 定稿六段（覆盖）
FIX7 = {
 "p05":("ep03_vox_fix7/ep03_fix7_p05_s42.wav",5,5.60),
 "p38":("ep03_vox_fix7/ep03_fix7_p38_s42.wav",38,13.12),
 "p40":("ep03_vox_fix7/ep03_fix7_p40_s43.wav",40,15.52),
 "p61":("ep03_vox_fix7/ep03_fix7_p61_s42.wav",61,24.64),
 "p25":("ep03_vox_fix7b/ep03_fix7b_p25_s45.wav",25,10.08),
 "p84":("ep03_vox_fix7c/ep03_fix7c_p84_s44.wav",84,20.32),
}
for tag,(rel,i,exp) in FIX7.items():
    p=os.path.join(BASE,rel); assert os.path.exists(p),rel
    w=wave.open(p); real=round(w.getnframes()/w.getframerate(),3)
    assert abs(real-exp)<0.01,(tag,real,exp)
    files[i]=p; dur[i]=real
    print("fix7",tag,"idx",i,"dur",real,os.path.getsize(p),flush=True)

TOTAL=round(sum(dur.values()),2)
# 铃铛 p73 起点 = 前 72 段累计
BELL=round(sum(dur[i] for i in range(1,73)),2)
print("TOTAL v4",TOTAL,"(v3 1524.48, delta %.2f)"%(TOTAL-1524.48),flush=True)
print("BELL p73 start",BELL,"(v3 892.96, delta %.2f)"%(BELL-892.96),flush=True)

# 写时长表 v4
d4={}
for i in range(1,110):
    d4["p%03d"%i]={"duration_s":dur[i],"file":os.path.abspath(files[i]).replace("\\","/")}
json.dump(d4,open(os.path.join(BASE,"ep03_durations_v4.json"),"w",encoding="utf-8"),
          ensure_ascii=False,indent=2)

# 拼接 109 段 -> raw_v4
concat=os.path.join(BASE,"ep03_raw_v4_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("\\","/"))
RAW4=os.path.join(BASE,"ep03_raw_v4_concat.wav")
subprocess.run(["ffmpeg","-y","-v","error","-f","concat","-safe","0","-i",concat,
                "-c","copy",RAW4],check=True,cwd=BASE)
w=wave.open(RAW4); print("raw_v4 dur",round(w.getnframes()/w.getframerate(),3),flush=True)

# 过 v2/v3 链（无压缩/限幅）
OUT=os.path.join(BASE,"ep03_narration_master_v4.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",RAW4,"-af",af,"-c:a","pcm_s16le",OUT],
               check=True,cwd=BASE)
print("master v4 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)
    i=re.search(r'"input_i"\s*:\s*"([-\d.]+)"',r.stderr)
    tp=re.search(r'"input_tp"\s*:\s*"([-\d.]+)"',r.stderr)
    return (float(i.group(1)) if i else None,float(tp.group(1)) if tp else None)
print("MASTER v4 LUFS/TP:",meas(OUT),flush=True)
print("MASTER v3 LUFS/TP:",meas(os.path.join(BASE,"ep03_narration_master_v3.wav")),flush=True)
