#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学·03《月亮错觉》TTS（花酱 wb 箱 id=195 开工令）
配方与 02 完全一致（skill 铁律）：a_identity.wav 克隆 / seed42 / cfg2.0 / steps10 / 48k CPU。
合成文本来自 moon03_synth_script.txt（24 行，已做读音标注与结构性修正），
字幕来自 moon03_subs.json（讲稿原文，一字不改）。
**绝不加「栖迟:」前缀**（EP03 铁律）。
段间 0.20s 呼吸停顿（02 语速快，不加会低于 60s 下限），不变速不改样本。
支持断点续跑：已存在 wav 按 SKIP 处理。
生产数据写 D:/WorkBuddyProd/moon03/（老李存储规矩）。
"""
import json, os, sys, time, traceback

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

HERE = os.path.dirname(os.path.abspath(__file__))
PROD = r"D:/WorkBuddyProd/moon03"
VOX = os.path.join(PROD, "vox_moon03")
RAW = os.path.join(PROD, "moon03_voice_raw.wav")
SRT = os.path.join(HERE, "moon03.srt")
SEG_JSON = os.path.join(HERE, "moon03_segments.json")
TL_JSON = os.path.join(HERE, "moon03_timeline.json")
REPORT = os.path.join(HERE, "moon03_tts_report.json")
LOG = os.path.join(HERE, "moon03_tts.log")

MODEL_DIR = r"D:\voxcpm\models\models\OpenBMB--VoxCPM2\snapshots\master"
SEED_WAV = r"D:/Download/muse_exchange/_vox_design/candidates/a_identity.wav"
SEED_TEXT = ("Okay, so let me get this straight. You wake up, you open your phone, "
             "and before you even get out of bed, you have already seen three different "
             "versions of today. Is that right? That sounds exhausting, honestly.")

SEED, CFG, STEPS = 42, 2.0, 10
TAIL_S = 2.5
PAUSE = 0.20  # 段间呼吸停顿

SYNTH = os.path.join(HERE, "moon03_synth_script.txt")
SUBS = os.path.join(HERE, "moon03_subs.json")
# 9 张底图占位（按讲稿视觉提示分配，底图另行生成）
IMG_MAP = {
    1: "moon01.png", 2: "moon02.png", 3: "moon03.png", 4: "moon02.png",
    5: "moon01.png", 6: "moon01.png", 7: "moon04.png", 8: "moon04.png",
    9: "moon04.png", 10: "moon04.png", 11: "moon04.png", 12: "moon05.png",
    13: "moon05.png", 14: "moon05.png", 15: "moon07.png", 16: "moon07.png",
    17: "moon07.png", 18: "moon06.png", 19: "moon06.png", 20: "moon06.png",
    21: "moon06.png", 22: "moon06.png", 23: "moon08.png", 24: "moon09.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 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) == 24 and len(subs) == 24, "段落数不对"
    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=24" % (time.time() - t0, sr))

    pieces, cursor, recs = [], 0.0, []
    for i, (tts, sub) in enumerate(zip(synth, subs), 1):
        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))
        else:
            torch.manual_seed(SEED)
            t = time.time()
            wav = model.generate(text=tts,
                                 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(tts), time.time() - t, sub["text"]))
        dur = len(wav) / sr
        start, end = cursor, cursor + dur
        recs.append({"key": key, "idx": i, "sub": sub["text"], "tts": tts,
                     "img": IMG_MAP[i], "wav": os.path.relpath(path, 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

    # SRT：字幕起点严格等于各段语音起点
    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 * 24, 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": 24, "total_s": round(total, 4),
               "sr": sr, "voice": "02_a_warm", "seed": SEED,
               "raw": RAW, "raw_bytes": os.path.getsize(RAW)},
              open(REPORT, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    log("DONE total=%.2fs speech=%.2fs raw=%d bytes" % (total, cursor - PAUSE * 24, os.path.getsize(RAW)))


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