#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""只扫 loudnorm 的 TPGOAL（不加任何压缩器/限幅器），找 I 与 AAC 真峰都达标的点。

输入复用 moon03_master.py 已生成的 moon03_aligned.wav，不改旁白内容。
"""
import json
import os
import re
import subprocess
import sys

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

TMP = r"D:/WorkBuddyProd/moon03/loudfinal"
PRE = os.path.join(TMP, "moon03_aligned.wav")
FF = "ffmpeg"
IGOAL = -13.0
CANDS = [-1.2, -1.5, -1.8, -2.1, -2.4]


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


def tp_i(path):
    """用 loudnorm 的 json 读 input_i / input_tp（真峰 dBTP，非 ebur128 sample peak）。"""
    r = run(["-i", path, "-af",
             "loudnorm=I=-16.9:TP=-1.1:LRA=7:print_format=json", "-f", "null", "-"])
    m = re.findall(r"\{\s*\"input_i\".*?\}", r.stderr, re.S)
    assert m, "parse fail " + path
    d = json.loads(m[-1])
    return float(d["input_i"]), float(d["input_tp"])


def main():
    print("TPGOAL | master_I master_TP | aac_I aac_TP | I_OK TP_OK", flush=True)
    results = []
    for tpgoal in CANDS:
        wav = os.path.join(TMP, "scan_wav_tp%.1f.wav" % abs(tpgoal))
        m4a = os.path.join(TMP, "scan_aac_tp%.1f.m4a" % abs(tpgoal))
        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)
        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)
        q = run(["-i", PRE, "-af", af, "-ar", "48000", "-ac", "1",
                 "-c:a", "pcm_s16le", wav])
        assert q.returncode == 0, q.stderr[-800:]
        run(["-i", wav, "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "1", m4a])
        mI, mTP = tp_i(wav)
        aI, aTP = tp_i(m4a)
        okI = abs(mI + 16.9) <= 0.5
        okTP = aTP <= -1.0
        print("%5.1f | %8.2f %9.2f | %6.2f %6.2f | %s %s" %
              (tpgoal, mI, mTP, aI, aTP, okI, okTP), flush=True)
        results.append({"tpgoal": tpgoal, "master_I": mI, "master_TP": mTP,
                        "aac_I": aI, "aac_TP": aTP, "I_ok": okI, "TP_ok": okTP})
    json.dump(results, open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                         "moon03_master_scan.json"), "w",
                            encoding="utf-8"), ensure_ascii=False, indent=2)
    good = [r for r in results if r["I_ok"] and r["TP_ok"]]
    print("BOTH_OK", [r["tpgoal"] for r in good], flush=True)


if __name__ == "__main__":
    main()
