#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""04 声音纠正候选：中文 prompt 版全量 23 段 + TRPV1「一」读法候选（花酱 id=219/220）

背景：A/B 复现实验证明 04 与 03 引擎/参考音/参数 100% 相同（corr=1.000000, mse=0），
洋腔不是配置错。当前假设=英文 prompt 的英语韵律渗透进中文续写，故改用
03 已录的中文段 wav（仍是 02 暖男音色说的中文）+ 对应中文文本作 prompt。

⚠ id=221 已定案：C/F 中文 prompt 全量重录＝**04 正式音轨**（不再是候选）。
⚠ id=224 追加定案：s04 用刚耳检通过的 `yī_tight`（TRPV 一的受体。）、
   s16 按同连写口径重录（鸟的 TRPV 一长得不一样，）；两段 wav 已覆盖进 VOX。
⚠ TRPV1 的数字 1 按汉语读「一」(yi1)，不读英文 one；字幕 chili04_subs.json 一字不改。

输出：D:/WorkBuddyProd/chili04/vox_chili04_zh/、probe_trpv1_v2/、
      chili04_timeline_zh.json / chili04_tts_report_zh.json / chili04_zh.srt
"""
import json, os, sys, time, traceback
sys.path.insert(0, r"D:/Download/muse_exchange")
import numpy as np
import soundfile as sf
import torch
from voice_seed_zh import MODEL_DIR, SEED, CFG, STEPS, SEED_WAV, SEED_TEXT, assert_ready
from voxcpm import VoxCPM

HERE = r"D:/Download/muse_exchange"
PROD = r"D:/WorkBuddyProd/chili04"
VOX = os.path.join(PROD, "vox_chili04_zh")
PROBE = os.path.join(PROD, "probe_trpv1_v2")
LOG = os.path.join(HERE, "chili04_tts_zh.log")

ZH_WAV, ZH_TEXT = SEED_WAV, SEED_TEXT  # 固定中文底子（voice_seed_zh.py，花酱 id=223 定案）
SYNTH = os.path.join(HERE, "chili04_synth_script_v2.txt")
SUBS = os.path.join(HERE, "chili04_subs.json")

NSEG, PAUSE, TAIL_S = 23, 0.20, 2.5
MOTION = "MOTION"
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 main():
    assert_ready()
    os.makedirs(VOX, exist_ok=True)
    os.makedirs(PROBE, exist_ok=True)
    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(ZH_WAV), "中文参考音不存在"

    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 prompt=zh segs=%d" % (time.time() - t0, sr, NSEG))

    def gen(text, seed, path):
        torch.manual_seed(seed)
        t = time.time()
        wav = model.generate(text=text,
                             prompt_wav_path=ZH_WAV, prompt_text=ZH_TEXT,
                             reference_wav_path=ZH_WAV,
                             cfg_value=CFG, inference_timesteps=STEPS)
        wav = np.asarray(wav, dtype=np.float32).reshape(-1)
        sf.write(path, wav, sr)
        log("GEN %s dur=%.2fs cost=%.0fs  %s" %
            (os.path.basename(path), len(wav) / sr, time.time() - t, text))
        return wav

    # 1) TRPV1 数字「一」读法候选（供花酱耳检；字母仍按字母读）
    # ⚠ id=224 定稿：yī_tight = 正式 s04；s16_yī_tight = 正式 s16（同连写口径）。
    #   正式 wav 已覆盖进 vox_chili04_zh/，合成稿 chili04_synth_script_v2.txt 同步改连写。
    probes = {
        "s16_yī_tight": "鸟的 TRPV 一长得不一样，",
        "yī_spaces": "T R P V 一 的受体。",
        "yī_clothed": "T R P V 衣 的受体。",
        "yī_tight": "TRPV 一的受体。",
        "s16_yī": "鸟的 T R P V 一 长得不一样，",
    }
    for name, text in probes.items():
        p = os.path.join(PROBE, name + ".wav")
        if not os.path.exists(p):
            gen(text, SEED, p)

    # 2) 全量 23 段（中文 prompt）
    pieces, cursor, recs = [], 0.0, []
    for i in range(1, NSEG + 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:
            wav = gen(synth[i - 1], SEED, path)
        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(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

    pieces.append(np.zeros(int(TAIL_S * sr), np.float32))
    raw = np.concatenate(pieces)
    sf.write(os.path.join(PROD, "chili04_voice_raw_zh.wav"), raw, sr)
    total = len(raw) / sr

    with open(os.path.join(HERE, "chili04_zh.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(os.path.join(HERE, "chili04_segments_zh.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(os.path.join(HERE, "chili04_timeline_zh.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_zh_prompt", "seed": SEED,
               "durs": {r["key"]: r["dur"] for r in recs},
               "motion_span_s": round(recs[7]["end"] - recs[2]["start"], 4)},
              open(os.path.join(HERE, "chili04_tts_report_zh.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    log("DONE total=%.2fs motion(s3-s8)=%.2fs" % (total, recs[7]["end"] - recs[2]["start"]))


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