#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 fix6 第1步收尾：整合两引擎读音验收 → 打包 3 wav → 8800 自测 → 回执 huajiang 箱。
做完停下等花酱验 + 刚耳检 + 第2步放行。不混音/不渲染/不拼合。
"""
import hashlib, json, os, sys, subprocess, urllib.request, urllib.parse, time

BASE = r"D:\Download\muse_exchange"
VOXDIR = os.path.join(BASE, "ep03_vox_fix6")
ZIP = os.path.join(BASE, "ep03_vox_fix6_3seg.zip")
EXCHANGE_URL = "http://localhost:8800"
SEND_URL = "http://localhost:8801/send?box=huajiang"
TRY_PROXY = urllib.request.build_opener(urllib.request.ProxyHandler({}))

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


def sha(b):
    return hashlib.sha256(b).hexdigest()


def gate(tag):
    r = subprocess.run([sys.executable, os.path.join(BASE, "wb_gate.py"), "--tag", tag],
                       cwd=BASE, capture_output=True, text=True)
    print(r.stdout[-600:], flush=True)
    return r.returncode


def main():
    tts = json.load(open(os.path.join(BASE, "ep03_fix6_tts_report.json"), encoding="utf-8"))
    sv = json.load(open(os.path.join(BASE, "ep03_fix6_asr_report.json"), encoding="utf-8"))
    # 修正 cross 脚本的机械结论（按字面未命中≠读错；看音节）
    cross_path = os.path.join(BASE, "ep03_fix6_asr_cross.json")
    cross = json.load(open(cross_path, encoding="utf-8"))
    cross["conclusion"] = (
        "paraformer 听成「梅因」méi yīn，与「梅殷」完全同音（前鼻音正确）；"
        "SenseVoice 单票「梅英」méi yīng 属其后鼻音正字化。"
        "按音节判读：读音锁三词均正确，不判硬伤、不重录；"
        "SenseVoice 那票列耳检提示交刚确认。")
    cross["corrected_by"] = "WB 人工判读（ASR 误识≠读错，看音节不看字形）"
    with open(cross_path, "w", encoding="utf-8") as f:
        json.dump(cross, f, ensure_ascii=False, indent=2)

    segs = tts["segments"]
    # 读音锁三词：双引擎音节判读
    pron = [
        ("梅殷", "méi yīn", "SenseVoice=梅英(méi yīng 后鼻音一票) / paraformer=梅因(méi yīn 同音正确)",
         "按音节正确(前鼻音)，不重录；一票后鼻音列耳检"),
        ("私谥", "sī shì", "两引擎均=私事(sī shì 同音)", "同音正字化，读音正确"),
        ("惠宗", "huì zōng", "两引擎均命中「惠宗」", "命中，正确"),
    ]
    md = [
        "# EP03 fix6 第1步：p04 / p61 / p107 三段重录验收", "",
        "> 机械参数严格照抄原 109 段：VoxCPM2 / seed 42 / cfg 2.0 / steps 10 / 48kHz / voice_ref_eq48_ep04.wav；"
        "按句独立生成、无「栖迟」前缀、中文弯引号。", "",
        "## 三段时长", "",
        "| 段 | 文件 | 时长(s) | 字节 |", "|---|---|---|---|",
    ]
    for k in ("p04", "p61", "p107"):
        s = segs[k]
        md.append("| %s | %s | %.3f | %d |" % (k, s["file"], s["duration_s"], s["bytes"]))
    total = sum(segs[k]["duration_s"] for k in ("p04", "p61", "p107"))
    md += ["", "**合计 %.3f s**" % total, "", "## 读音锁验收（双 ASR 引擎）", "",
           "> ASR 只标疑似点、最终以花酱验 + 刚耳检为准；判读看音节不看字形（ASR 误识≠读错）。", "",
           "| 词 | 目标读音 | 双引擎转写 | 判读 |", "|---|---|---|---|"]
    for w, py, asr, verdict in pron:
        md.append("| %s | %s | %s | %s |" % (w, py, asr, verdict))
    md += ["", "## 逐段 ASR 全文（SenseVoice）", ""]
    for rec in sv["segments"]:
        md += ["### %s" % rec["seg"], "", "**预期**：%s" % rec["expect"], "",
               "**ASR** ：%s" % rec["asr"], ""]
    md += ["## paraformer 交叉验证（p61）", "", "**ASR**：%s" % cross["asr"], "",
           "**结论**：%s" % cross["conclusion"], "",
           "## 待办", "",
           "- 花酱验三段 + 刚耳检（重点：p61「梅殷」前后鼻音，双引擎一票 yīn 正确、一票 yīng 正字化）。",
           "- 验过放行后再做第2步：母带 v3 重混 + 字幕 v1.4 + 重渲 5 镜 + 拼合。",
           "- 本步只重录三段，未混音/未渲染/未拼合，原 109 段与成片未动。"]
    md_path = os.path.join(BASE, "ep03_fix6_验收报告.md")
    with open(md_path, "w", encoding="utf-8") as f:
        f.write("\n".join(md) + "\n")

    # 打包
    import zipfile
    files = [os.path.join(VOXDIR, segs[k]["file"]) for k in ("p04", "p61", "p107")]
    files += [os.path.join(BASE, "ep03_fix6_验收报告.md"),
              os.path.join(BASE, "ep03_fix6_tts_report.json"),
              os.path.join(BASE, "ep03_fix6_asr_report.json"),
              os.path.join(BASE, "ep03_fix6_asr_cross.json")]
    manifest = []
    with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as z:
        for p in files:
            b = open(p, "rb").read()
            z.writestr(os.path.basename(p), b)
            manifest.append({"name": os.path.basename(p), "bytes": len(b), "sha256": sha(b)})
    zb = open(ZIP, "rb").read()
    print("ZIP %d B sha=%s members=%d" % (len(zb), sha(zb), len(manifest)), flush=True)
    with zipfile.ZipFile(ZIP) as z:
        bad = z.testzip()
    print("ZIP_BAD", bad, flush=True)
    assert bad is None

    # 8800 自测
    lst = json.loads(TRY_PROXY.open(EXCHANGE_URL + "/list", timeout=30).read())
    name = os.path.basename(ZIP)
    r = TRY_PROXY.open(EXCHANGE_URL + "/download?name=" + urllib.parse.quote(name), timeout=120)
    dl = r.read()
    cl = int(r.headers.get("Content-Length", -1))
    selftest = (name in lst) and cl == len(zb) and dl == zb
    print("SELFTEST in_list=%s CL=%s bytes=%s got=%s identical=%s PASS=%s" %
          (name in lst, cl, len(zb), len(dl), dl == zb, selftest), flush=True)
    assert selftest

    # gate 后发回执
    g = gate("ep03_fix6_step1_reply")
    if g != 0:
        print("GATE 非 GO，按规矩不发回执", flush=True)
        return
    text = (
        "【EP03 fix6 第1步完成：p04/p61/p107 三段重录，停下等验+耳检】\n\n"
        "接 wb id=307 第1步。只重录三段，未混音/未渲染/未拼合，原109段与成片未动。\n\n"
        "■ 配方（严格照抄原109段）：VoxCPM2 / seed42 / cfg2.0 / steps10 / 48kHz / "
        "voice_ref_eq48_ep04.wav；按句独立、无「栖迟」前缀、中文弯引号。\n\n"
        "■ 三段新文案（v1.4）：\n"
        "p04：按说，故事到这儿该结束了。人死了，葬了。可新君即位，比下葬还早四天。\n"
        "p61：庙号和谥号更晚。神宗是建文旧臣梅殷的私谥，成祖不认；南明弘光元年，朝廷直接追上惠宗，"
        "谥让皇帝；清朝乾隆元年，又追谥恭闵惠皇帝。这就是《明史》称他「恭闵帝」的来历。距离那场火，已经三百多年。\n"
        "p107：下期预告：回到《如果历史拐了个弯》。\n\n"
        "■ 时长：p04=7.840s / p61=23.680s / p107=4.320s，合计35.840s。\n\n"
        "■ 读音锁验收（双ASR，看音节不看字形）：\n"
        "梅殷 méi yīn —— paraformer 听成「梅因」méi yīn 完全同音（前鼻音正确）；"
        "SenseVoice 单票「梅英」méi yīng 属其后鼻音正字化。按音节判读正确，不判硬伤、不重录；"
        "请刚耳检这一票。\n"
        "私谥 sī shì —— 两引擎均「私事」同音，正确。\n"
        "惠宗 huì zōng —— 两引擎均命中，正确。\n"
        "其余「建闻/承祖/弘光/功免」等均为同音正字化，非读错。\n\n"
        "■ 交付：ep03_vox_fix6_3seg.zip（%d B，sha256 %s，含3 wav + 双引擎验收报告 + manifest），"
        "8800 逐字节自测 PASS。三段 wav 也已单文件在交换目录：ep03_vox_fix6_p04.wav / p61 / p107。\n\n"
        "■ 停在检查点：等花酱验三段 + 刚耳检通过，再发第2步（母带v3重混+字幕v1.4+重渲5镜+拼合）。"
        "按工单不往下走。" % (len(zb), sha(zb))
    )
    body = {"from": "workbuddy", "kind": "done", "text": text,
            "files": [os.path.basename(ZIP),
                      segs["p04"]["file"], segs["p61"]["file"], segs["p107"]["file"],
                      os.path.basename(md_path)]}
    data = json.dumps(body, ensure_ascii=False).encode("utf-8")
    req = urllib.request.Request(SEND_URL, data=data,
                                 headers={"Content-Type": "application/json"}, method="POST")
    resp = TRY_PROXY.open(req, timeout=30)
    print("REPLY_HTTP", resp.status, resp.read().decode("utf-8", "replace"), flush=True)
    # 回读
    rows = [json.loads(l) for l in open(os.path.join(BASE, "mailbox_data/huajiang.jsonl"),
                                        encoding="utf-8") if l.strip()]
    last = rows[-1]
    print("READBACK id=%s from=%s kind=%s files=%s" %
          (last.get("id"), last.get("from"), last.get("kind"), last.get("files")), flush=True)


if __name__ == "__main__":
    main()
