#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 旁白合成源稿生成（接 wb 箱 id151）

铁律（沿用 EP02，已写入项目 MEMORY.md）：
1. 合成文本绝不加「栖迟:」前缀 —— 只喂纯旁白文本。
2. 数字双轨：讲稿/字幕用阿拉伯数字，合成稿一律中文读法，否则念出来会散。
3. 年份逐位读，用「零」不用「〇」（EP02 10-25 实测「〇」吞字）。
4. 合成文本禁用 ASCII 直引号（会被念成「杠」），讲稿用中文「」《》，天然满足。
5. 字幕一律本字，只改喂给 TTS 的合成输入。

本批三处按实测校准（详见 ep03_synth_report.md / manifest）：
A. 附录锁音表标注的「段」范围不全 —— 同一生僻字在表外段落还出现 8 处。
   按花酱「只改合成输入（字→字）」的口径，采用【全篇按字替换】，
   避免同集内同一个字有的段读对、有的段读错。
B. 数字双轨沿用 EP02 全系列铁律（id151 未提，但属既定工艺），13 段阿拉伯年份改中文读法。
C. p107 括号内「（EP04 选题待定）」是制作备注，不是旁白，剔除。

输出：
  ep03_synth_script.txt      109 行，每行一段纯旁白（按行号取段）
  ep03_synth_manifest.json   逐段原文/合成文本/替换记录
  ep03_synth_report.md       人类可读替换清单
"""
import json, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "EP03_讲稿_v1.3_final.md")
OUT_TXT = os.path.join(HERE, "ep03_synth_script.txt")
OUT_JSON = os.path.join(HERE, "ep03_synth_manifest.json")
OUT_MD = os.path.join(HERE, "ep03_synth_report.md")

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

# 锁音表：本字 -> 合成输入（全篇按字替换）
LOCK = [
    ("穹窿", "琼隆"),   # 二字词优先，避免单字误伤
    ("邋遢", "拉他"),
    ("炆", "文"),
    ("橞", "惠"),
    ("濙", "莹"),
    ("洽", "恰"),
    ("庶", "树"),
]

# 数字双轨：阿拉伯年份 -> 中文逐位读法（用「零」不用「〇」）
DIGIT = {"0": "零", "1": "一", "2": "二", "3": "三", "4": "四",
         "5": "五", "6": "六", "7": "七", "8": "八", "9": "九"}


def year_cn(s):
    return "".join(DIGIT[c] for c in s)


def main():
    raw = open(SRC, encoding="utf-8").read()
    segs = re.findall(r"^- (p\d{2,3})：(.+)$", raw, re.M)
    assert len(segs) == 109, "讲稿应为 109 段，实际 %d" % len(segs)
    assert [int(k[1:]) for k, _ in segs] == list(range(1, 110)), "段号不连续"

    records = []
    lock_hits, digit_hits, note_hits = [], [], []
    for key, orig in segs:
        t = orig
        changes = []

        # C. 剔除制作备注（全角括号内的非口播内容）
        for m in re.findall(r"（[^）]*）", t):
            if re.search(r"EP\d|选题|待定|待补|TODO|制作|备注", m):
                t = t.replace(m, "")
                changes.append({"type": "strip_production_note", "removed": m})
                note_hits.append((key, m))

        # B. 数字双轨：所有 4 位年份（含「1983 到 1990 年」这种区间，
        #    两端都不直接跟「年」，用 (?=年) 会漏掉 —— 10-12 实测踩过）
        def repl_year(m):
            n = m.group(0)
            cn = year_cn(n)
            changes.append({"type": "digit_to_cn", "from": n, "to": cn})
            digit_hits.append((key, n, cn))
            return cn

        # 先规范化区间空格：TTS 遇空格会误停顿，且「在 1983 到 1990 年间」需连读
        t = re.sub(r"\s*到\s*", "到", t)
        t = re.sub(r"\s+年", "年", t)
        t = re.sub(r"\d{4}", repl_year, t)
        # 中文数字与「在」之间若残留空格也清掉（原讲稿「在 1983」）
        t = re.sub(r"(?<=在)\s+(?=[一二三四五六七八九零])", "", t)
        # p107 括号制作备注已剔除；若仍有 EP04 之类残留属异常，直接拦下
        assert not re.search(r"EP\d{2}", t), "%s 仍有 EP 编号残留: %s" % (key, t)

        # A. 锁音表：全篇按字替换
        for a, b in LOCK:
            if a in t:
                cnt = t.count(a)
                t = t.replace(a, b)
                changes.append({"type": "lock_char", "from": a, "to": b, "count": cnt})
                lock_hits.append((key, a, b, cnt))

        # 硬校验
        assert "栖迟:" not in t and "栖迟：" not in t, "%s 出现前缀污染" % key
        assert '"' not in t and "'" not in t, "%s 出现 ASCII 直引号" % key
        assert "〇" not in t, "%s 出现「〇」（EP02 吞字 bug）" % key
        assert not re.search(r"\d", t), "%s 仍有未转换的阿拉伯数字: %s" % (key, t)
        assert t.strip(), "%s 合成文本为空" % key

        records.append({
            "id": key,
            "original": orig,
            "synth": t,
            "synth_chars": len(t),
            "changes": changes,
        })

    with open(OUT_TXT, "w", encoding="utf-8") as f:
        for r in records:
            f.write(r["synth"] + "\n")

    manifest = {
        "source": "EP03_讲稿_v1.3_final.md",
        "source_bytes": os.path.getsize(SRC),
        "segments": len(records),
        "total_synth_chars": sum(r["synth_chars"] for r in records),
        "policy": {
            "prefix": "无「栖迟:」前缀，纯旁白文本",
            "digit_dual_track": "讲稿/字幕阿拉伯数字，合成稿中文逐位读法，用「零」不用「〇」",
            "lock_table": "全篇按字替换（附录表段号不全，表外亦覆盖）",
            "quote": "中文「」《》，无 ASCII 直引号",
            "production_note": "p107 括号制作备注剔除",
        },
        "records": records,
    }
    with open(OUT_JSON, "w", encoding="utf-8") as f:
        json.dump(manifest, f, ensure_ascii=False, indent=2)

    # 人类可读报告
    lines = [
        "# EP03 旁白合成源稿 · 逐段替换清单",
        "",
        "源：`EP03_讲稿_v1.3_final.md`（28,531 B）｜输出：`ep03_synth_script.txt`（109 行，按行号取段）",
        "",
        "字幕/讲稿一律用本字；以下只改喂给 TTS 的合成输入。完整逐段对照见 `ep03_synth_manifest.json`。",
        "",
        "## 一、口径（沿用 EP02 全系列铁律）",
        "",
        "1. 合成文本**绝不加「栖迟:」前缀**，只喂纯旁白。",
        "2. **数字双轨**：讲稿/字幕用阿拉伯数字，合成稿一律中文读法（否则念出来会散）；年份逐位读，用「零」不用「〇」（EP02 实测「〇」吞字）。",
        "3. 合成文本禁用 ASCII 直引号；本讲稿通篇中文「」《》，天然满足。",
        "4. 锁音表按**字**替换，全篇覆盖。",
        "",
        "## 二、锁音表：全篇按字替换（附录段号范围不全）",
        "",
        "附录锁音表标注的段号只覆盖了部分出现位置；实测同一字在表外段落还出现。按「只改合成输入（字→字）」的口径全篇覆盖，避免同集内同一个字有的段读对、有的段读错。",
        "",
        "| 本字 | 合成输入 | 实际命中段 | 附录表标注 |",
        "|---|---|---|---|",
    ]
    table_range = {"炆": "p10", "橞": "p29", "濙": "p84–p86", "洽": "p81–p82",
                   "穹窿": "p75", "邋遢": "p84", "庶": "p48"}
    for a, b in LOCK:
        hits = [k for k, x, y, c in lock_hits if x == a]
        lines.append("| %s | %s | %s（%d 段） | %s |" % (a, b, "、".join(hits), len(hits), table_range[a]))
    lines += [
        "",
        "> 表外新增覆盖：炆 p11/p21/p69、濙 p89/p106、穹窿 p100、庶 p49/p51。",
        "> p10 原文「炆，这个字的读音跟「文」一样」按锁音表写成「文，这个字的读音跟「文」一样」——听感仍是 wén，字幕仍是本字「炆」，与附录末行「p10 口播已当场解释炆跟文同音」一致。",
        "",
        "## 三、数字双轨：13 段阿拉伯年份 → 中文读法",
        "",
        "| 段 | 原（字幕） | 合成输入 |",
        "|---|---|---|",
    ]
    for k, n, cn in digit_hits:
        lines.append("| %s | %s | %s |" % (k, n, cn))
    lines += [
        "",
        "**连读风险段（按 EP02 10-26 教训，请 QC 重点听）**：",
        "",
        "- p26「一三九九年」（九九连读）、p67「一四四零年」（四四连读）、p69「一三七七年」（七七连读）、p75「一九九零年」（九九连读）。",
        "- EP02 曾出现「二二〇年」两个二被念快连成一个二；当时改写「二百二十年」3/3 稳定。若本批 QC 发现同类吞字，我可按「一千三百九十九年」式按数值读法重录这 4 段（断点续跑，不必全批重来）。",
        "",
        "## 四、制作备注剔除",
        "",
    ]
    for k, m in note_hits:
        lines.append("- %s 剔除 `%s`（括号内容为制作备注，不是旁白，绝不能念出来）。" % (k, m))
    lines += [
        "",
        "## 五、逐段合成文本（前 5 段示例）",
        "",
    ]
    for r in records[:5]:
        lines.append("- **%s**：%s" % (r["id"], r["synth"]))
    lines += ["", "---", "", "完整 109 段见 `ep03_synth_manifest.json` 与 `ep03_synth_script.txt`。"]
    with open(OUT_MD, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")

    print("segments:", len(records))
    print("total synth chars:", manifest["total_synth_chars"])
    print("lock hits:", len(lock_hits), "segments:", len(set(k for k, *_ in lock_hits)))
    print("digit hits:", len(digit_hits), "segments:", len(set(k for k, *_ in digit_hits)))
    print("production notes stripped:", note_hits)
    print("script lines:", sum(1 for _ in open(OUT_TXT, encoding="utf-8")))
    print("files:", OUT_TXT, OUT_JSON, OUT_MD)


if __name__ == "__main__":
    main()
