from __future__ import annotations

import json
import shutil
from pathlib import Path


ALIASES = {
    "zh_female_mizai_uranus_bigtts": "mizai",
    "zh_female_tianmeitaozi_uranus_bigtts": "taozi",
    "zh_male_dayi_uranus_bigtts": "dayi",
    "zh_female_wanwanxiaohe_moon_bigtts": "wanwan",
}


def main() -> None:
    home = Path.home()
    target = home / ".config" / "ivox"
    target.mkdir(parents=True, exist_ok=True)
    voices_dir = target / "voices"
    voices_dir.mkdir(exist_ok=True)

    old_voices_paths = [
        home / "iCode" / "iTTS" / "voices" / "voices.json",
        home / "iTTS" / "voices" / "voices.json",
    ]
    old_ispeak = home / ".config" / "ispeak" / "config.json"
    old_data = {}
    for old_voices in old_voices_paths:
        if old_voices.exists():
            old_data = json.loads(old_voices.read_text(encoding="utf-8"))
            for info in old_data.values():
                src = old_voices.parent / info.get("audio", "")
                if src.exists():
                    shutil.copy2(src, voices_dir / src.name)
            break

    voices = []
    for old_id, info in old_data.items():
        local_id = ALIASES.get(old_id, old_id)
        voices.append({
            "id": local_id,
            "name": info.get("description", local_id),
            "refAudio": f"voices/{info.get('audio', '')}",
            "refText": info.get("reference_text", ""),
            "description": info.get("description", ""),
        })

    source_voices = {"claude": "taozi", "codex": "wanwan", "pi": "dayi"}
    default_voice = "mizai"
    if old_ispeak.exists():
        old_cfg = json.loads(old_ispeak.read_text(encoding="utf-8"))
        if old_cfg.get("defaultVoice", {}).get("voice_type") in ALIASES:
            default_voice = ALIASES[old_cfg["defaultVoice"]["voice_type"]]
        for source, voice in old_cfg.get("sourceVoices", {}).items():
            old_id = voice.get("voice_type")
            if old_id in ALIASES:
                source_voices[source] = ALIASES[old_id]

    cfg = {
        "model": {"path": str(target / "models" / "Qwen3-TTS-12Hz-0.6B-Base-4bit")},
        "runtime": {"python": str(target / "py" / ".venv" / "bin" / "python")},
        "defaultVoice": default_voice,
        "sourceVoices": source_voices,
        "voices": voices,
    }
    (target / "config.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
