"""EP02 v6 干净音轨重混（花酱 id124/id125 + Tim id126）
复刻 Tim 本地 v5 build_ep2.py 的音频链，唯一改动：摘掉 acompressor 与 alimiter。
用法：python ep02_v6_mix.py
产出：ep02_v6_dry.wav / ep02_v6_master_dyn.wav / ep02_v6_master_lin.wav
      ep02_v6_mix_report.json
"""
import json
import os
import re
import subprocess
import sys

BASE = os.path.dirname(os.path.abspath(__file__))
FF = r"D:\tools\ffmpeg\bin\ffmpeg.exe"

THEME = os.path.join(BASE, "intro_theme.mp3")
NARR = os.path.join(BASE, "ep02_vox_v5_track.wav")
BED = os.path.join(BASE, "bed_b_pad.wav")

INTRO_LEN = 6.75
TOTAL = 1253.11                 # v5 旁白轨长度（Tim 本地脚本常量）
TOTAL_ABS = INTRO_LEN + TOTAL   # 1259.86s
BED_FADE_OUT_ST = TOTAL_ABS - 4.0

DRY = os.path.join(BASE, "ep02_v6_dry.wav")
DYN = os.path.join(BASE, "ep02_v6_master_dyn.wav")
LIN = os.path.join(BASE, "ep02_v6_master_lin.wav")
REPORT = os.path.join(BASE, "ep02_v6_mix_report.json")


def run(cmd, capture=False):
    if capture:
        return subprocess.run(cmd, capture_output=True, text=True, errors="replace")
    subprocess.run(cmd, check=True)
    return None


def mean_volume(path):
    r = run([FF, "-v", "info", "-i", path, "-af", "volumedetect", "-f", "null", "-"], True)
    m = re.findall(r"mean_volume:\s*(-?[\d.]+) dB", r.stderr)
    if not m:
        raise RuntimeError("volumedetect failed: " + path)
    return float(m[-1])


def lufs_tp(path):
    r = run([FF, "-hide_banner", "-i", path, "-af", "ebur128=peak=true", "-f", "null", "-"], True)
    txt = r.stderr
    ilines = re.findall(r"I:\s*(-?[\d.]+) LUFS", txt)
    tplines = re.findall(r"Peak:\s*(-?[\d.]+) dBFS", txt)
    # summary block is the last occurrence
    return (float(ilines[-1]) if ilines else None,
            float(tplines[-1]) if tplines else None)


def main():
    narr_rms = mean_volume(NARR)
    bed_rms = mean_volume(BED)
    theme_rms = mean_volume(THEME)
    bed_gain = (narr_rms - 19.0) - bed_rms
    theme_gain = (narr_rms + 3.0) - theme_rms
    print(f"rms narr {narr_rms:.1f} bed {bed_rms:.1f} theme {theme_rms:.1f} "
          f"-> bed_gain {bed_gain:.2f}dB theme_gain {theme_gain:.2f}dB", flush=True)

    # --- dry mix: v5 结构原样，仅无 acompressor/alimiter/loudnorm ---
    fc = (
        f"[0:a]atrim=0:6.4,afade=t=out:st=5.4:d=1.0,apad=whole_dur={INTRO_LEN},"
        f"volume={theme_gain:.2f}dB[theme];"
        f"[1:a]adelay=6750:all=1[narr];"
        f"[2:a]aloop=loop=-1:size=2e+09,atrim=0:{TOTAL_ABS:.2f},"
        f"volume={bed_gain:.2f}dB,afade=t=in:st=0:d=2.0,"
        f"afade=t=out:st={BED_FADE_OUT_ST:.2f}:d=4.0[bed];"
        f"[theme][narr][bed]amix=inputs=3:normalize=0,"
        f"highpass=f=80,atrim=0:{TOTAL_ABS:.2f}[drysum]"
    )
    print("building dry mix ...", flush=True)
    run([FF, "-v", "error", "-y", "-i", THEME, "-i", NARR, "-i", BED,
         "-filter_complex", fc, "-map", "[drysum]", "-ar", "48000", "-ac", "1",
         "-c:a", "pcm_s16le", DRY])

    # --- pass1: measure for two-pass linear loudnorm ---
    r = run([FF, "-hide_banner", "-i", DRY,
             "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], True)
    blocks = re.findall(r"\{\s*\"input_i\".*?\}", r.stderr, re.S)
    if not blocks:
        raise RuntimeError("loudnorm pass1 json not found")
    st = json.loads(blocks[-1])
    meas = {k: float(st[k]) for k in
            ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset")}
    print("loudnorm pass1 measured:", meas, flush=True)

    # --- candidate A: 单遍动态 loudnorm（最贴原单「末级只留一道 loudnorm」）---
    print("building candidate A (dynamic loudnorm) ...", flush=True)
    run([FF, "-v", "error", "-y", "-i", DRY,
         "-af", "loudnorm=I=-14:TP=-1:LRA=11",
         "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", DYN])

    # --- candidate B: 两遍线性 loudnorm（同为「一道 loudnorm」，但无动态泵高）---
    ln = (f"loudnorm=I=-14:TP=-1:LRA=11:linear=true:"
          f"measured_I={meas['input_i']:.2f}:measured_TP={meas['input_tp']:.2f}:"
          f"measured_LRA={meas['input_lra']:.2f}:measured_thresh={meas['input_thresh']:.2f}:"
          f"offset={meas['target_offset']:.2f}:print_format=summary")
    print("building candidate B (two-pass linear loudnorm) ...", flush=True)
    rb = run([FF, "-hide_banner", "-y", "-i", DRY, "-af", ln,
              "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", LIN], True)
    fallback = "dynamic" in rb.stderr.lower() and "linear" in rb.stderr.lower()
    if fallback:
        for l in rb.stderr.splitlines():
            if "loudnorm" in l.lower():
                print("  loudnorm note:", l.strip(), flush=True)

    out = {
        "narr_rms": narr_rms, "bed_rms": bed_rms, "theme_rms": theme_rms,
        "bed_gain": bed_gain, "theme_gain": theme_gain,
        "TOTAL": TOTAL, "TOTAL_ABS": TOTAL_ABS,
        "loudnorm_measured": meas,
        "filter_complex": fc,
        "candidates": {},
    }
    for name, path in (("dynamic", DYN), ("linear", LIN)):
        i, tp = lufs_tp(path)
        dur = None
        pr = run([r"D:\tools\ffmpeg\bin\ffprobe.exe", "-v", "error",
                  "-show_entries", "format=duration", "-of", "csv=p=0", path], True)
        try:
            dur = float(pr.stdout.strip().splitlines()[0])
        except Exception:
            pass
        out["candidates"][name] = {"file": os.path.basename(path), "bytes": os.path.getsize(path),
                                   "duration_s": dur, "LUFS": i, "true_peak_dBTP": tp}
        print(f"  {name}: {dur}s  I={i} LUFS  TP={tp} dBTP", flush=True)

    with open(REPORT, "w", encoding="utf-8") as f:
        json.dump(out, f, ensure_ascii=False, indent=2)
    print("report:", REPORT, flush=True)


if __name__ == "__main__":
    main()
