#!/usr/bin/env python3
"""
漫译声 · AnimeDub 本地高保真离线英文配音流水线 (animedub-local-pipeline.py)
==========================================================================

功能概览：
  1. [Demucs]  将动漫视频/音频分离为人声 (vocals.wav) 与纯背景音乐+音效 (no_vocals.wav)
  2. [Whisper] 使用 faster-whisper / whisper 转录带时间戳的中文台词（也支持直接传入 --srt）
  3. [LLM]     调用 OpenAI 兼容 / 从简平台模型接口，批量生成等时长口型对齐的英文配音剧本与多角色配置
  4. [EdgeTTS] 为不同角色匹配独立神经英文声线，按每句时间窗自动微调语速对口型
  5. [FFmpeg]  将合成的英文多角色人声精准对轨混入原片纯 BGM，输出：
               - <输出名>.dubpack.json （可直接导入漫译声 Web 剧场或 Chrome/Edge 插件）
               - <输出名>.en-dub.mp3   （保留原片 BGM 与音效的完整英文配音音轨）

依赖安装（推荐 Python 3.10+）：
  pip install edge-tts faster-whisper demucs
  # 系统需安装 ffmpeg（macOS: brew install ffmpeg / Ubuntu: sudo apt install ffmpeg）

使用示例：
  export OPENAI_API_KEY="sk-xxxx"
  export OPENAI_BASE_URL="https://api.openai.com/v1"   # 或从简平台兼容地址

  # 完整流程（视频 -> 分离BGM -> 转录 -> AI英译 -> 多角色配音 -> 混音）
  python3 animedub-local-pipeline.py episode01.mp4 --title "青云剑诀 EP.01" --platform youku --level cet6

  # 已有中文字幕时跳过 Whisper，仅分离 BGM + AI 英译 + 合成混音
  python3 animedub-local-pipeline.py episode01.mp4 --srt episode01.srt --title "青云剑诀 EP.01"

  # 仅由字幕生成 .dubpack.json 与纯英文人声音轨（无需 Demucs，极速）
  python3 animedub-local-pipeline.py --srt episode01.srt --skip-demucs --title "青云剑诀 EP.01"
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple


DEFAULT_VOICE_POOL = {
    "male": [
        "en-US-AndrewNeural",
        "en-GB-RyanNeural",
        "en-US-BrianNeural",
        "en-US-ChristopherNeural",
    ],
    "female": [
        "en-US-AvaNeural",
        "en-GB-SoniaNeural",
        "en-US-EmmaNeural",
        "en-US-JennyNeural",
    ],
    "neutral": [
        "en-US-AriaNeural",
        "en-US-GuyNeural",
    ],
}

LEVEL_PROMPTS = {
    "junior": "初中流畅英文（常用高频词、短句清晰、适合零压力跟读）",
    "cet6": "大学四六级实用英文（自然地道、结构利落、兼顾实用短语）",
    "ielts": "雅思高分地道英文（丰富习语与自然表达、情绪张力强）",
    "native": "母语热血动漫英文（原生美剧/英配质感、俚语连读自然）",
}


def run_cmd(cmd: List[str], check: bool = True) -> subprocess.CompletedProcess:
    print(f"[cmd] {' '.join(cmd)}")
    return subprocess.run(cmd, check=check)


def require_binary(name: str) -> None:
    if not shutil.which(name):
        raise RuntimeError(f"未检测到系统命令 `{name}`，请先安装后再运行。")


def parse_srt_timestamp(ts: str) -> float:
    ts = ts.strip().replace(",", ".")
    parts = ts.split(":")
    if len(parts) == 3:
        h, m, s = parts
        return int(h) * 3600 + int(m) * 60 + float(s)
    if len(parts) == 2:
        m, s = parts
        return int(m) * 60 + float(s)
    return float(ts)


def parse_srt_file(srt_path: Path) -> List[Dict[str, Any]]:
    text = srt_path.read_text(encoding="utf-8-sig", errors="replace")
    blocks = re.split(r"\r?\n\r?\n+", text.strip())
    cues: List[Dict[str, Any]] = []
    time_re = re.compile(
        r"(\d{1,2}:\d{2}:\d{2}[.,]\d{1,3}|\d{1,2}:\d{2}[.,]\d{1,3})\s*-->\s*"
        r"(\d{1,2}:\d{2}:\d{2}[.,]\d{1,3}|\d{1,2}:\d{2}[.,]\d{1,3})"
    )
    for block in blocks:
        lines = [ln.strip() for ln in block.splitlines() if ln.strip()]
        if not lines:
            continue
        match_idx = -1
        start = end = 0.0
        for i, ln in enumerate(lines):
            m = time_re.search(ln)
            if m:
                start = parse_srt_timestamp(m.group(1))
                end = parse_srt_timestamp(m.group(2))
                match_idx = i
                break
        if match_idx == -1:
            continue
        content = " ".join(lines[match_idx + 1 :]).strip()
        content = re.sub(r"<[^>]+>", "", content).strip()
        if not content:
            continue
        cues.append(
            {
                "id": f"c{len(cues) + 1}",
                "start": round(start, 2),
                "end": round(max(end, start + 1.0), 2),
                "zh": content,
            }
        )
    return cues


def extract_audio(media_path: Path, out_wav: Path) -> None:
    require_binary("ffmpeg")
    run_cmd(
        [
            "ffmpeg",
            "-y",
            "-i",
            str(media_path),
            "-vn",
            "-acodec",
            "pcm_s16le",
            "-ar",
            "44100",
            "-ac",
            "2",
            str(out_wav),
        ]
    )


def separate_with_demucs(audio_wav: Path, work_dir: Path, model: str = "htdemucs") -> Tuple[Path, Path]:
    """使用 Demucs 分离人声与伴奏 (vocals.wav, no_vocals.wav)。"""
    demucs_out = work_dir / "demucs_out"
    demucs_out.mkdir(parents=True, exist_ok=True)
    run_cmd(
        [
            sys.executable,
            "-m",
            "demucs",
            "--two-stems=vocals",
            "-n",
            model,
            "-o",
            str(demucs_out),
            str(audio_wav),
        ]
    )
    stem_dir = demucs_out / model / audio_wav.stem
    vocals = stem_dir / "vocals.wav"
    no_vocals = stem_dir / "no_vocals.wav"
    if not vocals.exists() or not no_vocals.exists():
        raise RuntimeError(f"Demucs 分离输出缺失：{stem_dir}")
    return vocals, no_vocals


def transcribe_with_whisper(audio_wav: Path, model_size: str = "small") -> List[Dict[str, Any]]:
    """优先使用 faster-whisper 转录带时间戳的中文台词。"""
    try:
        from faster_whisper import WhisperModel  # type: ignore
    except ImportError as exc:
        raise RuntimeError(
            "未安装 faster-whisper。请运行 `pip install faster-whisper`，或通过 `--srt` 直接传入中文字幕。"
        ) from exc

    print(f"[whisper] 加载 faster-whisper 模型: {model_size} ...")
    model = WhisperModel(model_size, device="auto", compute_type="int8")
    segments, _ = model.transcribe(str(audio_wav), language="zh", vad_filter=True)
    cues: List[Dict[str, Any]] = []
    for seg in segments:
        txt = seg.text.strip()
        if not txt:
            continue
        cues.append(
            {
                "id": f"c{len(cues) + 1}",
                "start": round(float(seg.start), 2),
                "end": round(max(float(seg.end), float(seg.start) + 1.0), 2),
                "zh": txt,
            }
        )
    return cues


def extract_json_payload(raw_text: str) -> Any:
    cleaned = raw_text.strip()
    fence = re.search(r"```(?:json)?\s*([\s\S]*?)```", cleaned)
    if fence:
        cleaned = fence.group(1).strip()
    return json.loads(cleaned)


def call_llm_translate_batch(
    batch: List[Dict[str, Any]],
    api_key: str,
    base_url: str,
    model: str,
    level: str,
    style: str,
    known_roles: List[Dict[str, Any]],
) -> Dict[str, Any]:
    endpoint = base_url.rstrip("/")
    if not endpoint.endswith("/v1"):
        endpoint = f"{endpoint}/v1"
    endpoint = f"{endpoint}/chat/completions"

    level_desc = LEVEL_PROMPTS.get(level, LEVEL_PROMPTS["cet6"])
    style_desc = (
        "严格等时长口型对齐（控制英文音节数与每句起止时长高度匹配，适合直接配音）"
        if style == "isochronic"
        else "自然地道口语表达（优先还原情绪与语感）"
    )

    system_prompt = (
        "你是资深动漫英文配音本地化导演（Anime Dubbing Scriptwriter）。"
        "请将输入的中文动漫台词翻译为适合直接配音的英文台词，识别不同说话角色，并输出严格合法的 JSON。\n"
        f"英语难度：{level_desc}\n"
        f"配音策略：{style_desc}\n"
        "严格返回 JSON 对象，不要附加任何解释，格式如下：\n"
        "{\n"
        '  "roles": [{"id": "role_1", "name": "角色名", "gender": "male|female|neutral", "pitch": 1.0, "rate": 1.0, "voiceHint": "en-US-male"}],\n'
        '  "cues": [{"id": "c1", "start": 0.5, "end": 4.2, "roleId": "role_1", "speaker": "角色名", '
        '"emotion": "determined", "zh": "原中文", "en": "English line", "notes": "口语/连读简析", '
        '"keywords": [{"word": "phrase", "phonetic": "/.../", "meaning": "中文释义"}]}]\n'
        "}"
    )

    user_payload = {
        "existingRoles": known_roles,
        "cues": batch,
    }

    req_body = json.dumps(
        {
            "model": model,
            "temperature": 0.4,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)},
            ],
        }
    ).encode("utf-8")

    req = urllib.request.Request(
        endpoint,
        data=req_body,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=90) as resp:
            data = json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")[:400]
        raise RuntimeError(f"LLM API 请求失败 ({exc.code}): {detail}") from exc

    content = data["choices"][0]["message"]["content"]
    return extract_json_payload(content)


def translate_cues(
    raw_cues: List[Dict[str, Any]],
    api_key: str,
    base_url: str,
    model: str,
    level: str,
    style: str,
    batch_size: int = 12,
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
    roles_map: Dict[str, Dict[str, Any]] = {}
    translated_cues: List[Dict[str, Any]] = []

    for offset in range(0, len(raw_cues), batch_size):
        batch = raw_cues[offset : offset + batch_size]
        print(f"[llm] 正在翻译第 {offset + 1} - {offset + len(batch)} / {len(raw_cues)} 句 ...")
        result = call_llm_translate_batch(
            batch=batch,
            api_key=api_key,
            base_url=base_url,
            model=model,
            level=level,
            style=style,
            known_roles=list(roles_map.values()),
        )
        for role in result.get("roles", []):
            rid = str(role.get("id") or "").strip()
            if rid and rid not in roles_map:
                roles_map[rid] = {
                    "id": rid,
                    "name": str(role.get("name") or rid),
                    "gender": role.get("gender") if role.get("gender") in ("male", "female", "neutral") else "neutral",
                    "pitch": float(role.get("pitch") or 1.0),
                    "rate": float(role.get("rate") or 1.0),
                    "voiceHint": str(role.get("voiceHint") or "en-US"),
                }

        batch_cues = result.get("cues", [])
        for idx, src in enumerate(batch):
            item = batch_cues[idx] if idx < len(batch_cues) else {}
            rid = str(item.get("roleId") or "role_1")
            speaker = str(item.get("speaker") or roles_map.get(rid, {}).get("name") or "主角")
            if rid not in roles_map:
                roles_map[rid] = {
                    "id": rid,
                    "name": speaker,
                    "gender": "neutral",
                    "pitch": 1.0,
                    "rate": 1.0,
                    "voiceHint": "en-US",
                }
            translated_cues.append(
                {
                    "id": src["id"],
                    "start": src["start"],
                    "end": src["end"],
                    "roleId": rid,
                    "speaker": speaker,
                    "emotion": str(item.get("emotion") or "neutral"),
                    "zh": str(item.get("zh") or src["zh"]),
                    "en": str(item.get("en") or src["zh"]),
                    "notes": str(item.get("notes") or ""),
                    "keywords": item.get("keywords") if isinstance(item.get("keywords"), list) else [],
                }
            )

    return list(roles_map.values()), translated_cues


def assign_edge_voices(roles: List[Dict[str, Any]]) -> Dict[str, str]:
    counters = {"male": 0, "female": 0, "neutral": 0}
    mapping: Dict[str, str] = {}
    for role in roles:
        gender = role.get("gender", "neutral")
        if gender not in DEFAULT_VOICE_POOL:
            gender = "neutral"
        pool = DEFAULT_VOICE_POOL[gender]
        voice = pool[counters[gender] % len(pool)]
        counters[gender] += 1
        mapping[role["id"]] = voice
        role["voiceHint"] = voice
    return mapping


def probe_duration(audio_path: Path) -> float:
    out = subprocess.check_output(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(audio_path),
        ],
        text=True,
    ).strip()
    return float(out)


async def synthesize_all_cues(
    cues: List[Dict[str, Any]],
    voice_map: Dict[str, str],
    clips_dir: Path,
) -> List[Tuple[Dict[str, Any], Path]]:
    try:
        import edge_tts  # type: ignore
    except ImportError as exc:
        raise RuntimeError("未安装 edge-tts，请运行 `pip install edge-tts`。") from exc

    clips_dir.mkdir(parents=True, exist_ok=True)
    results: List[Tuple[Dict[str, Any], Path]] = []

    for cue in cues:
        text = cue.get("en", "").strip()
        if not text:
            continue
        voice = voice_map.get(cue["roleId"], "en-US-AndrewNeural")
        raw_mp3 = clips_dir / f"{cue['id']}_raw.mp3"
        fit_wav = clips_dir / f"{cue['id']}_fit.wav"

        communicate = edge_tts.Communicate(text=text, voice=voice)
        await communicate.save(str(raw_mp3))

        target_dur = max(0.6, float(cue["end"]) - float(cue["start"]))
        actual_dur = probe_duration(raw_mp3)

        # 若朗读时间长于原台词时间窗，平滑加速以对齐口型（限制 1.0 - 1.45 倍速）
        tempo = 1.0
        if actual_dur > target_dur * 1.05:
            tempo = min(1.45, max(1.0, actual_dur / target_dur))

        filter_args = ["-af", f"atempo={tempo:.3f}"] if tempo > 1.01 else []
        run_cmd(
            [
                "ffmpeg",
                "-y",
                "-i",
                str(raw_mp3),
                *filter_args,
                "-ar",
                "44100",
                "-ac",
                "2",
                str(fit_wav),
            ]
        )
        results.append((cue, fit_wav))

    return results


def mix_dub_audio(
    clips: List[Tuple[Dict[str, Any], Path]],
    bgm_wav: Optional[Path],
    duration_sec: float,
    out_mp3: Path,
    bgm_volume: float = 0.85,
) -> None:
    """使用 ffmpeg 将多句英文配音按精确毫秒偏移混入 BGM 伴奏轨道。"""
    require_binary("ffmpeg")
    if not clips:
        raise RuntimeError("没有可混音的英文配音片段。")

    inputs: List[str] = []
    filter_parts: List[str] = []
    mix_labels: List[str] = []

    if bgm_wav and bgm_wav.exists():
        inputs.extend(["-i", str(bgm_wav)])
        filter_parts.append(f"[0:a]volume={bgm_volume:.2f}[bgm]")
        mix_labels.append("[bgm]")
        start_idx = 1
    else:
        inputs.extend(
            [
                "-f",
                "lavfi",
                "-t",
                f"{max(duration_sec, 5.0):.2f}",
                "-i",
                "anullsrc=r=44100:cl=stereo",
            ]
        )
        filter_parts.append("[0:a]volume=0.0[bgm]")
        mix_labels.append("[bgm]")
        start_idx = 1

    for i, (cue, clip_path) in enumerate(clips):
        in_idx = start_idx + i
        delay_ms = max(0, int(round(float(cue["start"]) * 1000)))
        label = f"v{i}"
        inputs.extend(["-i", str(clip_path)])
        filter_parts.append(f"[{in_idx}:a]adelay={delay_ms}|{delay_ms},volume=1.15[{label}]")
        mix_labels.append(f"[{label}]")

    amix_inputs = "".join(mix_labels)
    filter_parts.append(
        f"{amix_inputs}amix=inputs={len(mix_labels)}:duration=first:dropout_transition=0:normalize=0,"
        "alimiter=limit=0.95[out]"
    )
    filter_complex = ";".join(filter_parts)

    run_cmd(
        [
            "ffmpeg",
            "-y",
            *inputs,
            "-filter_complex",
            filter_complex,
            "-map",
            "[out]",
            "-codec:a",
            "libmp3lame",
            "-b:a",
            "192k",
            str(out_mp3),
        ]
    )


def upload_pack(api_base: str, pack: Dict[str, Any]) -> Optional[str]:
    endpoint = f"{api_base.rstrip('/')}/api/packs"
    body = json.dumps(pack, ensure_ascii=False).encode("utf-8")
    req = urllib.request.Request(
        endpoint,
        data=body,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=30) as resp:
        data = json.loads(resp.read().decode("utf-8"))
        return data.get("id")


def main() -> int:
    parser = argparse.ArgumentParser(
        description="漫译声 · AnimeDub 本地高保真离线英文配音脚本 (Demucs + Whisper + LLM + Edge-TTS + FFmpeg)"
    )
    parser.add_argument("media", nargs="?", help="输入动漫视频或音频文件路径（如 episode01.mp4）")
    parser.add_argument("--srt", help="可选：已有中文字幕 .srt 文件（提供后将跳过 Whisper 转录）")
    parser.add_argument("--title", default="本地离线英文配音包", help="配音包标题")
    parser.add_argument("--platform", default="youku", choices=["youku", "qq", "bilibili", "iqiyi", "youtube"])
    parser.add_argument("--episode-ref", default="", help="集数标签（如 EP.01）")
    parser.add_argument("--level", default="cet6", choices=["junior", "cet6", "ielts", "native"])
    parser.add_argument("--style", default="isochronic", choices=["isochronic", "natural"])
    parser.add_argument("--out-dir", default="./animedub_output", help="输出目录")
    parser.add_argument("--skip-demucs", action="store_true", help="跳过 Demucs BGM 分离（极速模式）")
    parser.add_argument("--skip-tts", action="store_true", help="仅生成 .dubpack.json，不合成 MP3 音轨")
    parser.add_argument("--demucs-model", default="htdemucs", help="Demucs 模型名（默认 htdemucs）")
    parser.add_argument("--whisper-model", default="small", help="faster-whisper 模型尺寸（默认 small）")
    parser.add_argument("--bgm-volume", type=float, default=0.85, help="混音时原片 BGM 音量比例（默认 0.85）")
    parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", ""), help="OpenAI 兼容 API Key")
    parser.add_argument(
        "--base-url",
        default=os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1"),
        help="OpenAI 兼容 API Base URL",
    )
    parser.add_argument("--llm-model", default=os.environ.get("OPENAI_MODEL", "gpt-4o-mini"), help="翻译模型名")
    parser.add_argument("--upload", default="", help="可选：自动上传配音包到漫译声服务地址（如 https://animedub.congjianai.com）")
    args = parser.parse_args()

    if not args.media and not args.srt:
        parser.error("请至少提供媒体文件 `media` 或 `--srt` 字幕文件。")

    if not args.api_key:
        print("[error] 未检测到 OPENAI_API_KEY，请通过环境变量或 `--api-key` 提供模型密钥。", file=sys.stderr)
        return 1

    out_dir = Path(args.out_dir).resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = Path(args.media).stem if args.media else Path(args.srt).stem

    with tempfile.TemporaryDirectory(prefix="animedub_") as tmp:
        work_dir = Path(tmp)
        vocals_wav: Optional[Path] = None
        bgm_wav: Optional[Path] = None

        if args.media:
            media_path = Path(args.media).resolve()
            if not media_path.exists():
                print(f"[error] 媒体文件不存在：{media_path}", file=sys.stderr)
                return 1
            raw_wav = work_dir / f"{stem}.wav"
            extract_audio(media_path, raw_wav)

            if not args.skip_demucs:
                print("[stage 1/5] 正在使用 Demucs 分离原声与 BGM 伴奏 ...")
                vocals_wav, bgm_wav = separate_with_demucs(raw_wav, work_dir, model=args.demucs_model)
            else:
                vocals_wav = raw_wav

        if args.srt:
            print("[stage 2/5] 正在解析中文字幕文件 ...")
            raw_cues = parse_srt_file(Path(args.srt).resolve())
        else:
            if not vocals_wav:
                print("[error] 缺少音频文件用于 Whisper 转录。", file=sys.stderr)
                return 1
            print("[stage 2/5] 正在使用 Whisper 转录中文台词 ...")
            raw_cues = transcribe_with_whisper(vocals_wav, model_size=args.whisper_model)

        if not raw_cues:
            print("[error] 未提取到任何有效台词。", file=sys.stderr)
            return 1
        print(f"[info] 共提取 {len(raw_cues)} 句中文台词。")

        print("[stage 3/5] 正在调用大模型生成多角色等时长英文配音剧本 ...")
        roles, cues = translate_cues(
            raw_cues=raw_cues,
            api_key=args.api_key,
            base_url=args.base_url,
            model=args.llm_model,
            level=args.level,
            style=args.style,
        )
        voice_map = assign_edge_voices(roles)
        duration_sec = max((float(c["end"]) for c in cues), default=60.0)

        dubpack: Dict[str, Any] = {
            "schemaVersion": "1.0",
            "title": args.title,
            "platform": args.platform,
            "episodeRef": args.episode_ref,
            "level": args.level,
            "style": args.style,
            "durationSec": round(duration_sec, 2),
            "offsetSec": 0,
            "author": "本地高保真离线流水线",
            "modelUsed": args.llm_model,
            "roles": roles,
            "cues": cues,
        }

        pack_path = out_dir / f"{stem}.dubpack.json"
        pack_path.write_text(json.dumps(dubpack, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"[ok] 已导出标准配音包：{pack_path}")

        if not args.skip_tts:
            print("[stage 4/5] 正在使用 Edge-TTS 合成多角色英文配音 ...")
            clips = asyncio.run(synthesize_all_cues(cues, voice_map, work_dir / "clips"))
            print("[stage 5/5] 正在混音输出完整英文配音音轨 (MP3) ...")
            mp3_path = out_dir / f"{stem}.en-dub.mp3"
            mix_dub_audio(
                clips=clips,
                bgm_wav=bgm_wav,
                duration_sec=duration_sec,
                out_mp3=mp3_path,
                bgm_volume=args.bgm_volume,
            )
            print(f"[ok] 已导出混音音轨：{mp3_path}")

        if args.upload:
            print(f"[upload] 正在上传配音包到 {args.upload} ...")
            pack_id = upload_pack(args.upload, dubpack)
            print(f"[ok] 上传成功！Chrome/Edge 插件 Pack ID: {pack_id}")

    print("\n全部完成！你可以将生成的 .dubpack.json 和 .en-dub.mp3 直接导入漫译声 Web 剧场或浏览器同步插件。")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
