#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 重录 9 段 · 定向验收（wb id162 / id163）

p024：四个番王名（周/齐/代/岷）顿号间隔均匀、齐代之间必须有停顿。
p102：开头「那」读 nà 四声，不得像 lái/来。
其余 7 段：只做文件级完整性。

手段（代理验收，非人耳）：
  1) 能量分段（20ms 帧 RMS）找静音间隙；
  2) paraformer 字级时间戳看相邻字间隔（时间戳有系统偏移，只看相对 gap）；
  3) SenseVoice + paraformer 双解码识别整段文本。
局限：ASR 有误识可能，最终听感仍归花酱/刚耳检。
"""
import json
import os
import re
import time
import wave

import numpy as np
import soundfile as sf

HERE = os.path.dirname(os.path.abspath(__file__))
OUTDIR = os.path.join(HERE, "ep03_vox_resynth_seed43")
RESULT = os.path.join(HERE, "ep03_resynth_durations.json")
REPORT_JSON = os.path.join(HERE, "ep03_resynth_validation.json")
REPORT_MD = os.path.join(HERE, "ep03_resynth_validation.md")
IDS = ["p024", "p027", "p033", "p050", "p054", "p092", "p100", "p101", "p102"]


def file_check(path, rec):
    out = {"file": os.path.basename(path), "exists": os.path.exists(path)}
    if not out["exists"]:
        out["ok"] = False
        return out
    out["bytes"] = os.path.getsize(path)
    with wave.open(path, "rb") as w:
        sr, ch, sw, nf = (w.getframerate(), w.getnchannels(),
                          w.getsampwidth(), w.getnframes())
    out.update(sr=sr, ch=ch, sw=sw, duration_s=round(nf / sr, 3))
    out["ok"] = (sr == 48000 and ch == 1 and sw == 2
                 and out["bytes"] == rec.get("bytes")
                 and abs(nf / sr - rec.get("duration_s", 0)) < 0.02)
    return out


def energy_gaps(path, frame_ms=20, thr_db=-38, min_gap_ms=60):
    w, sr = sf.read(path, dtype="float32")
    hop = int(sr * frame_ms / 1000)
    n = len(w) // hop
    rms = np.array([np.sqrt(np.mean(w[i * hop:(i + 1) * hop] ** 2) + 1e-12)
                    for i in range(n)])
    thr = 10 ** (thr_db / 20.0)
    quiet = rms < thr
    gaps, i = [], 0
    while i < len(quiet):
        if quiet[i]:
            j = i
            while j < len(quiet) and quiet[j]:
                j += 1
            ms = (j - i) * frame_ms
            if ms >= min_gap_ms:
                gaps.append({"start_s": round(i * hop / sr, 3),
                             "end_s": round(j * hop / sr, 3),
                             "ms": int(ms)})
            i = j
        else:
            i += 1
    return {"sr": sr, "duration_s": round(len(w) / sr, 3),
            "threshold_db": thr_db, "gaps": gaps,
            "peak_rms": round(float(rms.max()), 5)}


def clean_sense(t):
    return re.sub(r"<\|[^|]*\|>", "", t or "").strip()


def main():
    result = json.load(open(RESULT, encoding="utf-8"))
    paths = {k: os.path.join(OUTDIR, "ep03_vox_%s.wav" % k) for k in IDS}
    checks = {}
    for k in IDS:
        rec = result.get("ep03_vox_%s.wav" % k, {})
        checks[k] = file_check(paths[k], rec)

    from funasr import AutoModel
    print("loading ASR models ...", flush=True)
    t0 = time.time()
    sense = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                      device="cpu", disable_update=True)
    para = AutoModel(model="iic/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
                     device="cpu", disable_update=True)
    print("ASR loaded in %.1fs" % (time.time() - t0), flush=True)

    def asr_sense(p):
        r = sense.generate(input=p, cache={}, language="auto",
                           use_itn=True, batch_size_s=60)
        return clean_sense(r[0]["text"])

    def asr_para(p):
        r = para.generate(input=p, language="zh", use_itn=True)
        return r[0].get("text", ""), r[0].get("timestamp", [])

    # ---- p024 停顿 ----
    p24 = paths["p024"]
    eg = energy_gaps(p24)
    t24s = asr_sense(p24)
    t24p, ts24 = asr_para(p24)
    # 字级时间戳找「齐」「代」相邻字间隔
    chars = list(t24p.replace(" ", ""))
    qi_gap = None
    try:
        iq = chars.index("齐")
        idai = chars.index("代", iq)
        if idai < len(ts24) and iq < len(ts24):
            qi_gap = {
                "qi_char_window_ms": [ts24[iq][0], ts24[iq][1]],
                "dai_char_window_ms": [ts24[idai][0], ts24[idai][1]],
                "gap_ms": int(ts24[idai][0] - ts24[iq][1]),
            }
    except (ValueError, IndexError) as e:
        qi_gap = {"error": "未在 paraformer 结果中定位到齐/代: %s" % e}
    # 四名字是否落在四个独立有声块：用静音间隙数做代理
    gaps_in_names_region = [g for g in eg["gaps"] if 2.0 <= g["start_s"] <= 9.0]
    p024 = {
        "id": "p024", "requirement": "四番王名顿号间隔均匀，齐、代之间必须有停顿",
        "energy": eg,
        "sensevoice": t24s, "paraformer": t24p,
        "timestamp_gap": qi_gap,
        "gaps_in_names_region": gaps_in_names_region,
        "proxy_verdict": None, "note": "",
    }
    if qi_gap and "gap_ms" in qi_gap:
        p024["proxy_verdict"] = "PASS" if qi_gap["gap_ms"] >= 80 else "RISK"
        p024["note"] = "齐→代字级间隔 %d ms（阈值 80ms）；时间戳有系统偏移，只看相对 gap" % qi_gap["gap_ms"]
    else:
        p024["proxy_verdict"] = "UNDETERMINED"
        p024["note"] = "ASR 未定位到齐/代，无法量化，需人耳复核"

    # ---- p102 「那」 ----
    p102 = paths["p102"]
    t102s = asr_sense(p102)
    t102p, _ = asr_para(p102)
    head_s, head_p = t102s[:8], t102p[:8]
    def reads_na(t):
        return ("那" in t) and ("来" not in t)
    p102d = {
        "id": "p102", "requirement": "开头「那」读 nà 四声，不得读成 lái/来",
        "sensevoice": t102s, "paraformer": t102p,
        "head_sensevoice": head_s, "head_paraformer": head_p,
        "na_both": reads_na(head_s) and reads_na(head_p),
        "proxy_verdict": None, "note": "",
    }
    if reads_na(head_s) and reads_na(head_p):
        p102d["proxy_verdict"] = "PASS"
        p102d["note"] = "双解码开头均为「那」、无「来」"
    elif "来" in head_s or "来" in head_p:
        p102d["proxy_verdict"] = "RISK"
        p102d["note"] = "至少一路解码开头识别出「来」，按派单应换 seed 再抽"
    else:
        p102d["proxy_verdict"] = "UNDETERMINED"
        p102d["note"] = "双解码开头均无法确定，需人耳复核"

    rep = {
        "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
        "scope": "代理验收（能量分段 + SenseVoice/paraformer 双解码），非人耳听感",
        "recipe": "VoxCPM2 / seed 43 / cfg 2.0 / steps 10 / 48kHz / voice_ref_eq48_ep04.wav",
        "file_checks": checks,
        "all_files_ok": all(c["ok"] for c in checks.values()),
        "p024": p024, "p102": p102d,
        "caveat": "ASR 存在误识（Whisper/paraformer 偏见），最终读音与节奏以花酱/刚耳检为准",
    }
    json.dump(rep, open(REPORT_JSON, "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)

    lines = [
        "# EP03 重录 9 段 · 定向验收报告", "",
        "时间：%s｜配方：%s" % (rep["ts"], rep["recipe"]), "",
        "**范围**：代理验收（能量分段 + SenseVoice/paraformer 双解码），**非人耳听感**；"
        "ASR 有误识可能，最终以花酱/刚耳检为准。", "",
        "## 一、9 段文件级完整性", "",
        "| 段 | 时长(s) | 采样率 | 声道 | 字节 | 结果 |", "|---|---|---|---|---|---|",
    ]
    for k in IDS:
        c = checks[k]
        lines.append("| %s | %s | %s | %s | %s | %s |" % (
            k, c.get("duration_s"), c.get("sr"), c.get("ch"), c.get("bytes"),
            "OK" if c["ok"] else "BAD"))
    lines += ["", "全部通过：**%s**" % rep["all_files_ok"], "",
              "## 二、p024 四番王名停顿", "",
              "- 要求：%s" % p024["requirement"],
              "- SenseVoice：%s" % p024["sensevoice"],
              "- paraformer：%s" % p024["paraformer"],
              "- 字级间隔：%s" % json.dumps(p024["timestamp_gap"], ensure_ascii=False),
              "- 名字区间静音段：%s" % json.dumps(p024["gaps_in_names_region"], ensure_ascii=False),
              "- **代理判读：%s** — %s" % (p024["proxy_verdict"], p024["note"]), "",
              "## 三、p102 开头「那」读音", "",
              "- 要求：%s" % p102d["requirement"],
              "- SenseVoice 开头：%s" % p102d["head_sensevoice"],
              "- paraformer 开头：%s" % p102d["head_paraformer"],
              "- 双解码均为「那」：%s" % p102d["na_both"],
              "- **代理判读：%s** — %s" % (p102d["proxy_verdict"], p102d["note"]), "",
              "## 四、局限", "", rep["caveat"], "",
              "脚本：ep03_resynth_validate.py（可复现）。",
    ]
    open(REPORT_MD, "w", encoding="utf-8").write("\n".join(lines) + "\n")

    print("all_files_ok:", rep["all_files_ok"])
    print("p024:", p024["proxy_verdict"], "|", p024["note"])
    print("  sense:", t24s)
    print("  para :", t24p)
    print("  ts_gap:", qi_gap)
    print("p102:", p102d["proxy_verdict"], "|", p102d["note"])
    print("  sense head:", head_s)
    print("  para  head:", head_p)


if __name__ == "__main__":
    main()
