# -*- coding: utf-8 -*-
"""EP03 fix6 第2步：母带 v3 —— 沿用 v2 链，只换 p04/p61/p107 三段。"""
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"))

# 109 段源文件：默认 ep03_vox/；9 段重录用 seed43 目录；三段 fix6 用新 wav
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)}
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"]

FIX = {"p04":("ep03_vox_fix6_p04.wav",4,7.84),
       "p61":("ep03_vox_fix6_p61.wav",61,23.68),
       "p107":("ep03_vox_fix6_p107.wav",107,4.32)}
for tag,(fn,i,dd) in FIX.items():
    p=os.path.join(BASE,fn)
    assert os.path.exists(p), fn
    w=wave.open(p); real=round(w.getnframes()/w.getframerate(),3)
    assert abs(real-dd)<0.01,(tag,real,dd)
    files[i]=p; dur[i]=real
    print("fix",tag,"idx",i,"dur",real,os.path.getsize(p),flush=True)

TOTAL=round(sum(dur.values()),2)
print("TOTAL v3",TOTAL,"(v2 1520.32, delta %.2f)"%(TOTAL-1520.32),flush=True)

# 写时长表 v3（供字幕/渲染用）
d3={}
for i in range(1,110):
    d3["p%03d"%i]={"duration_s":dur[i],"file":os.path.basename(files[i])}
json.dump(d3,open(os.path.join(BASE,"ep03_durations_v3.json"),"w",encoding="utf-8"),
          ensure_ascii=False,indent=2)

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

# 过 v2 链
OUT=os.path.join(BASE,"ep03_narration_master_v3.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",RAW3,"-af",af,"-c:a","pcm_s16le",OUT],
               check=True,cwd=BASE)
print("master v3 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 v3 LUFS/TP:",meas(OUT),flush=True)
print("MASTER v2 LUFS/TP:",meas(os.path.join(BASE,"ep03_package/ep03_package/ep03_narration_master_v2.wav")),flush=True)
