#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 旁白重录（wb id160 / id162 / id163）

配方：VoxCPM2 / seed 43 / cfg 2.0 / steps 10 / 48kHz / voice_ref_eq48_ep04.wav
只合成指定 9 段，输出到独立目录，不覆盖 ep03_vox/ 与已交付全量包。

用法：
  python ep03_resynth_batch.py --segments 27                 # 样张
  python ep03_resynth_batch.py                              # 默认 9 段（断点续跑）
  python ep03_resynth_batch.py --segments 24 --seed 44 --alt  # 换 seed 试抽，放 alt_takes/
"""
import argparse
import json
import os
import sys
import time

import soundfile as sf
import torch

HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPT = os.path.join(HERE, "ep03_synth_script.txt")
REF = os.path.join(HERE, "voice_ref_eq48_ep04.wav")
OUTDIR = os.path.join(HERE, "ep03_vox_resynth_seed43")
ALT_DIR = os.path.join(OUTDIR, "alt_takes")
MODEL_DIR = r"D:\voxcpm\models\models\OpenBMB--VoxCPM2\snapshots\master"
LOG = os.path.join(HERE, "ep03_resynth.log")
RESULT = os.path.join(HERE, "ep03_resynth_durations.json")

SEGMENTS = [24, 27, 33, 50, 54, 92, 100, 101, 102]
CFG, STEPS, SR_EXPECT = 2.0, 10, 48000

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


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 main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--segments", default=",".join(map(str, SEGMENTS)))
    ap.add_argument("--seed", type=int, default=43)
    ap.add_argument("--alt", action="store_true", help="试抽：输出到 alt_takes/ 并带 seed 后缀")
    a = ap.parse_args()

    segs = [int(x) for x in a.segments.split(",") if x.strip()]
    texts = open(SCRIPT, encoding="utf-8").read().splitlines()
    assert len(texts) == 109, "合成源稿应为 109 行"
    assert os.path.exists(REF), "参考音不存在: " + REF
    os.makedirs(OUTDIR, exist_ok=True)
    os.makedirs(ALT_DIR, exist_ok=True)

    result = json.load(open(RESULT, encoding="utf-8")) if os.path.exists(RESULT) else {}
    log("=== resynth start | segs=%s | seed=%d | alt=%s | ref=%s ===" % (
        ",".join("%03d" % n for n in segs), a.seed, a.alt, os.path.basename(REF)))

    from voxcpm import VoxCPM
    t0 = time.time()
    model = VoxCPM.from_pretrained(MODEL_DIR, load_denoiser=False,
                                   device="cpu", optimize=False)
    sr = model.tts_model.sample_rate
    assert sr == SR_EXPECT, "采样率 %d != %d" % (sr, SR_EXPECT)
    log("model loaded in %.1fs, sr=%d" % (time.time() - t0, sr))

    done = skipped = failed = 0
    for n in segs:
        key = "p%03d" % n
        text = texts[n - 1]
        name = "ep03_vox_%s%s.wav" % (key, ("_seed%d" % a.seed) if a.alt else "")
        path = os.path.join(ALT_DIR if a.alt else OUTDIR, name)

        if os.path.exists(path) and os.path.getsize(path) > 0:
            r = result.get(name)
            if r and r.get("bytes") == os.path.getsize(path) and r.get("seed") == a.seed:
                log("%s SKIP (exists %.2fs, seed %d)" % (name, r["duration_s"], a.seed))
                skipped += 1
                continue

        try:
            torch.manual_seed(a.seed)
            ts = time.time()
            wav = model.generate(text=text, reference_wav_path=REF,
                                 cfg_value=CFG, inference_timesteps=STEPS)
            sf.write(path, wav, sr)
            dur, size, cost = len(wav) / sr, os.path.getsize(path), time.time() - ts
            result[name] = {
                "id": key, "file": name, "seed": a.seed, "alt": a.alt,
                "text": text, "duration_s": round(dur, 3),
                "sample_rate": sr, "bytes": size, "chars": len(text),
                "cost_s": round(cost, 1), "rtf": round(cost / dur, 2) if dur else None,
            }
            json.dump(result, open(RESULT, "w", encoding="utf-8"),
                      ensure_ascii=False, indent=2)
            log("%s OK seed=%d chars=%d audio=%.2fs cost=%.0fs rtf=%.2f bytes=%d" % (
                name, a.seed, len(text), dur, cost, cost / dur if dur else 0, size))
            done += 1
        except Exception as e:
            log("%s FAILED: %s: %s" % (name, type(e).__name__, str(e)[:300]))
            failed += 1

    log("=== resynth end | new=%d skipped=%d failed=%d | total %.1f min ===" % (
        done, skipped, failed, (time.time() - t0) / 60))
    if failed:
        raise SystemExit("有 %d 段失败，见 %s" % (failed, LOG))


if __name__ == "__main__":
    main()
