#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 重录准备（wb id160/162/163）

只改喂给 TTS 的合成输入；不动 EP03_讲稿_v1.3_final.md（花酱推来的终稿/字幕源在对方侧）。
按行号取段，只改内容、不加行、不删行。
"""
import hashlib
import json
import os
import re
import time

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "ep03_synth_script.txt")
BACKUP = os.path.join(HERE, "ep03_synth_script_pre_resynth.txt")
PATCH_MD = os.path.join(HERE, "ep03_script_patches_p100_p101.md")
MANIFEST = os.path.join(HERE, "ep03_resynth_manifest.json")

# 刚定新文本（逐字照抄 wb id162 / id163，锁音已应用）
NEW = {
    100: "先说我信什么、不信什么。云南狮山、苏州琼隆山、福建的墓，以及所有排得像旅行日程的出亡图，我都不信。那是明中叶以后长出来的故事，不是被证实的行踪。",
    101: "郑和下西洋为了找他，也不信它是史实。《明史》里有这句话，现代通说不把它当作那场航海的主因。",
}

# 9 段重录清单与原因
SEGMENTS = [
    {"n": 24,  "reason": "刚耳检：四番王名（周/齐/代/岷）顿号间隔不均，齐、代连读",   "kind": "rhythm",  "text_change": False},
    {"n": 27,  "reason": "ASR 双解码听成「不宜逞一成报」，全包唯一成段含糊",            "kind": "asr",     "text_change": False},
    {"n": 33,  "reason": "ASR 听成「说我又和面目相见」，有何→又和",                     "kind": "asr",     "text_change": False},
    {"n": 50,  "reason": "ASR 听成「开门人」，看→开",                                    "kind": "asr",     "text_change": False},
    {"n": 54,  "reason": "ASR 听成「贵于光华……往外找」，两处偏离",                       "kind": "asr",     "text_change": False},
    {"n": 92,  "reason": "ASR 听成「活得这么小」，响→小，意思全变",                      "kind": "asr",     "text_change": False},
    {"n": 100, "reason": "刚定改字：「买」直译生硬，全段改「信」；字幕同步改信",          "kind": "rewrite", "text_change": True},
    {"n": 101, "reason": "刚定改字：「也不买成史实」→「也不信它是史实」；字幕同步改信",     "kind": "rewrite", "text_change": True},
    {"n": 102, "reason": "刚耳检：开头「那」听成 lái/来，应读 nà 四声（原句不动）",       "kind": "tone",    "text_change": False},
]


def main():
    lines = open(SRC, encoding="utf-8").read().splitlines()
    assert len(lines) == 109, "合成源稿必须 109 行，实际 %d" % len(lines)
    if not os.path.exists(BACKUP):
        open(BACKUP, "w", encoding="utf-8").write("\n".join(lines) + "\n")
    before = list(lines)
    old = {n: lines[n - 1] for n in NEW}
    for n, t in NEW.items():
        lines[n - 1] = t
    # 硬校验：行数不变、其余 107 行逐字不变、新行无违禁字符
    assert len(lines) == 109
    for i in range(109):
        if (i + 1) not in NEW:
            assert lines[i] == before[i], "第 %d 行被误改" % (i + 1)
    for n, t in NEW.items():
        assert not re.search(r"\d", t), "p%03d 新文本残留阿拉伯数字" % n
        assert "栖迟:" not in t and "栖迟：" not in t
        assert '"' not in t and "'" not in t and "〇" not in t
    open(SRC, "w", encoding="utf-8").write("\n".join(lines) + "\n")

    md = [
        "# EP03 合成稿补丁 · p100 / p101 改字（wb id162 / id163，刚定）", "",
        "只改喂给 TTS 的合成输入 `ep03_synth_script.txt`（按行号取段，109 行不变、其余 107 行逐字未动）。",
        "**字幕源 `EP03_讲稿_v1.3_final.md` 未改** —— 它是花酱推来的终稿 v1.3，字幕同步改「信」由花酱/Tim 侧执行；",
        "本补丁列出两处需改的字，供对方同步。原合成稿已备份 `ep03_synth_script_pre_resynth.txt`。", "",
        "## p100", "",
        "- 原（字幕/旧合成）：" + old[100], "",
        "- 新（合成输入，字幕须同步改「信」）：" + NEW[100], "",
        "## p101", "",
        "- 原（字幕/旧合成）：" + old[101], "",
        "- 新（合成输入，字幕须同步改「信」）：" + NEW[101], "",
        "> 注意 p101 不只是「买→信」：「也不买成史实」整句改为「也不信它是史实」。",
        "> 另：p100 的「苏州琼隆山」是锁音表「穹窿→琼隆」的合成输入，字幕仍用本字「穹窿山」。",
    ]
    open(PATCH_MD, "w", encoding="utf-8").write("\n".join(md) + "\n")

    manifest = {
        "task": "EP03 旁白重录 9 段（接 wb id160 + id162 + id163）",
        "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
        "recipe": "VoxCPM2 / seed 43 / cfg 2.0 / steps 10 / 48kHz / voice_ref_eq48_ep04.wav",
        "policy": "只合成，不做响度/混音/QC；只换 seed 不换字（p100/p101 按刚定新文本改字）",
        "outdir": "ep03_vox_resynth_seed43/",
        "replace_rule": "同名替换 ep03_vox_full_109.zip 内 wav/ 对应文件；ep03_vox/ 与全量包均不覆盖",
        "script_patch": {"file": "ep03_script_patches_p100_p101.md",
                         "p100_old": old[100], "p100_new": NEW[100],
                         "p101_old": old[101], "p101_new": NEW[101]},
        "synth_script_sha256": hashlib.sha256(
            ("\n".join(lines) + "\n").encode("utf-8")).hexdigest(),
        "segments": [dict(s, id="p%03d" % s["n"]) for s in SEGMENTS],
        "wavs": [], "validation": {},
    }
    json.dump(manifest, open(MANIFEST, "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)

    print("synth script lines:", len(lines), "| sha256:", manifest["synth_script_sha256"][:16])
    for n in NEW:
        print("p%03d: %d -> %d chars" % (n, len(old[n]), len(NEW[n])))
    print("wrote:", os.path.basename(PATCH_MD), os.path.basename(MANIFEST),
          os.path.basename(BACKUP))


if __name__ == "__main__":
    main()
