#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学线 05/06/07 母带（通用版，参数化自 chili04_master_zh.py）

用法: python sci_master.py 05
链：逐段恒定增益对齐（段 RMS -> -30 dBFS）-> 整轨两遍 loudnorm
     (Igoal=-13 过冲 / TPgoal=-1.2 / linear=true)。
**不加 acompressor / alimiter / 任何独立压缩器限幅器**。
成片交付前还要实测 mp4 的 I 与真峰（AAC 会抬真峰，不能拿母带值当交付值）。
"""
import json
import os
import re
import subprocess
import sys

import numpy as np
import soundfile as sf

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

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sci_cfg import ep_paths, EPS

EP = sys.argv[1]
P = ep_paths(EP)
CFG = EPS[EP]
TMP = os.path.join(P["prod"], "loudfinal")
FF = "ffmpeg"
TARGET_RMS_DB = -30.0
IGOAL, TPGOAL = -13.0, -1.2
TAIL_S = 2.5
PEAK_CEIL_DBFS = -6.0


def run(a):
    return subprocess.run([FF, "-hide_banner", "-nostdin", "-y"] + a,
                          capture_output=True, text=True, encoding="utf-8", errors="replace")


def meas(p):
    e = run(["-i", p, "-af", "ebur128=peak=true", "-f", "null", "-"]).stderr
    try:
        I = float(re.findall(r"I:\s*(-?[\d.]+)\s*LUFS", e)[-1])
    except Exception:
        I = None
    try:
        tp = float(re.findall(r"Peak:\s*(-?[\d.]+)\s*dBFS", e)[-1])
    except Exception:
        tp = None
    return I, tp


def main():
    os.makedirs(TMP, exist_ok=True)
    segs = json.load(open(P["segments"], encoding="utf-8"))
    tl = json.load(open(P["timeline"], encoding="utf-8"))
    sr = tl["sr"]
    assert len(segs) == CFG["nseg"] and sr == 48000

    gains, peak_trims, pieces = [], [], []
    for i, s in enumerate(segs, 1):
        p = os.path.join(P["vox"], "s%02d.wav" % i)
        x, srr = sf.read(p, dtype="float64")
        assert srr == sr, (p, srr)
        rms = np.sqrt(np.mean(x * x))
        g_db = TARGET_RMS_DB - 20 * np.log10(rms + 1e-12)
        peak_db = 20 * np.log10(np.max(np.abs(x)) + 1e-12)
        extra = min(0.0, PEAK_CEIL_DBFS - (peak_db + g_db))
        g_db += extra
        gains.append(round(g_db, 2))
        peak_trims.append(round(extra, 2))
        pieces.append((x * 10 ** (g_db / 20.0)).astype(np.float64))
        pieces.append(np.zeros(int(round(s["pause_after"] * sr))))
    pieces.append(np.zeros(int(round(TAIL_S * sr))))
    aligned = np.concatenate(pieces)
    dur = len(aligned) / sr
    print("ALIGNED dur=%.3fs expect=%.3fs" % (dur, tl["total_s"]), flush=True)
    assert abs(dur - tl["total_s"]) < 0.02, "重拼时长与时间轴不一致"

    pre = os.path.join(TMP, "sci%s_aligned.wav" % EP)
    sf.write(pre, aligned.astype(np.float32), sr)
    aI, aTP = meas(pre)
    print("ALIGNED I=%s TP=%s  gains %.2f..%.2f dB" %
          (aI, aTP, min(gains), max(gains)), flush=True)

    target = "loudnorm=I=%.1f:TP=%.1f:LRA=7:print_format=json" % (IGOAL, TPGOAL)
    p = run(["-i", pre, "-af", target, "-f", "null", "-"])
    b = re.findall(r"\{\s*\"input_i\".*?\}", p.stderr, re.S)
    assert b, "loudnorm pass1 json parse failed"
    info = json.loads(b[-1])
    af = ("loudnorm=I={ig:.1f}:TP={tp:.1f}:LRA=7:"
          "measured_I={input_i}:measured_TP={input_tp}:measured_LRA={input_lra}:"
          "measured_thresh={input_thresh}:offset={target_offset}:"
          "linear=true:print_format=summary").format(ig=IGOAL, tp=TPGOAL, **info)
    assert "acompressor" not in af and "alimiter" not in af
    q = run(["-i", pre, "-af", af, "-ar", "48000", "-ac", "1",
             "-c:a", "pcm_s16le", P["master"]])
    assert q.returncode == 0, q.stderr[-1500:]
    norm_type = "Dynamic" if "Dynamic" in q.stderr else "Linear"

    mI, mTP = meas(P["master"])
    aac = os.path.join(TMP, "sci%s_master_aac.m4a" % EP)
    run(["-i", P["master"], "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "1", aac])
    aacI, aacTP = meas(aac)
    print("MASTER I=%s TP=%s  norm=%s  bytes=%d" %
          (mI, mTP, norm_type, os.path.getsize(P["master"])), flush=True)
    print("AAC    I=%s TP=%s" % (aacI, aacTP), flush=True)
    okTP = aacTP is not None and aacTP <= -1.0
    okI = mI is not None and abs(mI + 16.9) <= 0.5
    print("CHECK  AAC 真峰 %s (<= -1)   I %s (|-16.9|<=0.5)" %
          ("OK" if okTP else "*** FAIL ***", "OK" if okI else "*** 超容差 ***"), flush=True)

    json.dump({
        "ep": EP,
        "method": "per_segment_constant_gain_align + whole_track_loudnorm_two_pass",
        "compressor_used": False,
        "IGOAL": IGOAL, "TPGOAL": TPGOAL, "target_segment_rms_dbfs": TARGET_RMS_DB,
        "segment_gains_dB_range": [min(gains), max(gains)],
        "peak_ceiling_dbfs": PEAK_CEIL_DBFS,
        "peak_trims_dB": peak_trims,
        "peak_trimmed_segments": sum(1 for t in peak_trims if t < 0),
        "aligned_dur_s": round(dur, 3), "aligned_I": aI, "aligned_TP": aTP,
        "master_I": mI, "master_TP": mTP, "normalization_type": norm_type,
        "aac_I": aacI, "aac_TP": aacTP,
    }, open(P["loud"], "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    print("REPORT -> " + P["loud"], flush=True)


if __name__ == "__main__":
    main()
