#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学·04《辣椒"辣"是痛觉》TTS（花酱 wb id=209 开工令 / id=214/215 最新指示）

配方与 02/03 完全一致：a_identity.wav 克隆 / seed42 / cfg2.0 / steps10 / 48k CPU。
⚠⚠ 铁律（02 s17 探针翻车实证）：SEED_TEXT / SEED_WAV / MODEL_DIR / SEED / CFG / STEPS
   一律从正式脚本 moon03_tts.py **import**，绝不凭记忆手写；
   prompt_text 与参考音失配会让 VoxCPM2 输出英文乱码。

字幕来自 chili04_subs.json（讲稿原文，一字不改），合成文本来自 chili04_synth_script.txt。
**绝不加「栖迟:」前缀**（EP03 铁律）。
段间 0.20s 呼吸停顿（02 语速快，不加会低于 60s 下限），不变速不改样本。
支持断点续跑：已存在 wav 按 SKIP 处理；支持 `--only 4,16` 先录 TRPV1 两段验语言。
生产数据写 D:/WorkBuddyProd/chili04/（老李 D 盘规矩）。

图片映射：3 号 TRPV1 图不渲（花酱 Remotion 动效），s3–s8 标 MOTION 占位；
其余 8 张按视觉提示编号 chili01/02/04/05/06/07/08/09。
"""
import json, os, sys, time, traceback

# ⚠ 从正式脚本 import，不手写（铁律）
from moon03_tts import MODEL_DIR, SEED_WAV, SEED_TEXT, SEED, CFG, STEPS

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

HERE = os.path.dirname(os.path.abspath(__file__))
PROD = r"D:/WorkBuddyProd/chili04"
VOX = os.path.join(PROD, "vox_chili04")
RAW = os.path.join(PROD, "chili04_voice_raw.wav")
SRT = os.path.join(HERE, "chili04.srt")
SEG_JSON = os.path.join(HERE, "chili04_segments.json")
TL_JSON = os.path.join(HERE, "chili04_timeline.json")
REPORT = os.path.join(HERE, "chili04_tts_report.json")
LOG = os.path.join(HERE, "chili04_tts.log")

TAIL_S = 2.5
PAUSE = 0.20
NSEG = 23

SYNTH = os.path.join(HERE, "chili04_synth_script.txt")
SUBS = os.path.join(HERE, "chili04_subs.json")

MOTION = "MOTION"  # s3–s8：花酱 Remotion 动效 clip，静态图不渲
IMG_MAP = {
    1: "chili01.png", 2: "chili01.png",
    3: MOTION, 4: MOTION, 5: MOTION, 6: MOTION, 7: MOTION, 8: MOTION,
    9: "chili04.png", 10: "chili05.png", 11: "chili05.png",
    12: "chili02.png", 13: "chili02.png", 14: "chili02.png",
    15: "chili06.png", 16: "chili06.png",
    17: "chili07.png", 18: "chili07.png",
    19: "chili08.png", 20: "chili08.png", 21: "chili08.png",
    22: "chili09.png", 23: "chili09.png",
}


def log(msg):
    line = "[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
    print(line, flush=True)
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(line + "\n")


def ts(t):
    ms = int(round(t * 1000))
    h, ms = divmod(ms, 3600000)
    m, ms = divmod(ms, 60000)
    s, ms = divmod(ms, 1000)
    return "%02d:%02d:%02d,%03d" % (h, m, s, ms)


def parse_only():
    for a in sys.argv[1:]:
        if a.startswith("--only"):
            v = a.split("=", 1)[1] if "=" in a else sys.argv[sys.argv.index(a) + 1]
            return [int(x) for x in v.split(",") if x.strip()]
    return None


def main():
    import numpy as np
    import soundfile as sf
    import torch
    from voxcpm import VoxCPM

    synth = [l.rstrip("\n") for l in open(SYNTH, encoding="utf-8") if l.strip()]
    subs = json.load(open(SUBS, encoding="utf-8"))["subs"]
    assert len(synth) == NSEG and len(subs) == NSEG, "段落数不对"
    assert os.path.exists(SEED_WAV), "参考音不存在"
    for i, s in enumerate(subs, 1):
        assert len(s["text"]) <= 18, "字幕行超18字: %02d %s" % (i, s["text"])
    os.makedirs(VOX, exist_ok=True)

    t0 = time.time()
    model = VoxCPM.from_pretrained(MODEL_DIR, load_denoiser=False, device="cpu", optimize=False)
    sr = model.tts_model.sample_rate
    assert sr == 48000
    log("model loaded %.1fs sr=%d voice=02_a_warm segs=%d seed_text_imported=True" %
        (time.time() - t0, sr, NSEG))

    def gen(i):
        key = "s%02d" % i
        path = os.path.join(VOX, key + ".wav")
        if os.path.exists(path) and os.path.getsize(path) > 10000:
            wav, srr = sf.read(path, dtype="float32")
            assert srr == sr
            log("%s SKIP dur=%.2fs" % (key, len(wav) / sr))
            return wav
        torch.manual_seed(SEED)
        t = time.time()
        wav = model.generate(text=synth[i - 1],
                             prompt_wav_path=SEED_WAV, prompt_text=SEED_TEXT,
                             reference_wav_path=SEED_WAV,
                             cfg_value=CFG, inference_timesteps=STEPS)
        wav = np.asarray(wav, dtype=np.float32).reshape(-1)
        sf.write(path, wav, sr)
        log("%s OK dur=%.2fs chars=%d cost=%.0fs  %s" %
            (key, len(wav) / sr, len(synth[i - 1]), time.time() - t, subs[i - 1]["text"]))
        return wav

    only = parse_only()
    if only:
        for i in only:
            gen(i)
        log("ONLY mode done: %s" % only)
        return

    pieces, cursor, recs = [], 0.0, []
    for i in range(1, NSEG + 1):
        key = "s%02d" % i
        wav = gen(i)
        dur = len(wav) / sr
        start, end = cursor, cursor + dur
        recs.append({"key": key, "idx": i, "sub": subs[i - 1]["text"], "tts": synth[i - 1],
                     "img": IMG_MAP[i], "wav": os.path.relpath(os.path.join(VOX, key + ".wav"), PROD).replace("\\", "/"),
                     "start": round(start, 4), "end": round(end, 4),
                     "dur": round(dur, 4), "pause_after": PAUSE})
        pieces.append(wav)
        pieces.append(np.zeros(int(PAUSE * sr), np.float32))
        cursor = end + PAUSE

    tail = np.zeros(int(TAIL_S * sr), np.float32)
    pieces.append(tail)
    raw = np.concatenate(pieces)
    sf.write(RAW, raw, sr)
    total = len(raw) / sr

    with open(SRT, "w", encoding="utf-8", newline="\n") as f:
        for r in recs:
            f.write("%d\n%s --> %s\n%s\n\n" %
                    (r["idx"], ts(r["start"]), ts(r["end"]), r["sub"]))
    json.dump(recs, open(SEG_JSON, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    json.dump({"total_s": round(total, 4), "speech_s": round(cursor - PAUSE * NSEG, 4),
               "pause_s": PAUSE, "tail_s": TAIL_S, "sr": sr, "fps": 30,
               "segments": [{"key": r["key"], "start": r["start"], "end": r["end"],
                             "img": r["img"]} for r in recs]},
              open(TL_JSON, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    json.dump({"ok": True, "segs": NSEG, "total_s": round(total, 4),
               "sr": sr, "voice": "02_a_warm", "seed": SEED,
               "raw": RAW, "raw_bytes": os.path.getsize(RAW),
               "durs": {r["key"]: r["dur"] for r in recs},
               "motion_span_s": round(recs[7]["end"] - recs[2]["start"], 4)},
              open(REPORT, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    log("DONE total=%.2fs speech=%.2fs motion(s3-s8)=%.2fs raw=%d bytes" %
        (total, cursor - PAUSE * NSEG, recs[7]["end"] - recs[2]["start"], os.path.getsize(RAW)))


if __name__ == "__main__":
    try:
        main()
    except Exception:
        log("FATAL\n" + traceback.format_exc())
        raise
