from __future__ import annotations

import json
import os
from pathlib import Path

APP_DIR_NAME = "TiHiY Voice Translator"
LEGACY_DIR_NAME = "TiHiY Voice Translator v9"


def _migrate_legacy_config(old_config: Path, new_config: Path) -> None:
    """Migrate old preferences without ever copying a private API key."""
    try:
        payload = json.loads(old_config.read_text(encoding="utf-8"))
        if not isinstance(payload, dict):
            return
        payload["api_key"] = ""
        temporary = new_config.with_suffix(".tmp")
        temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
        temporary.replace(new_config)
    except (OSError, ValueError, TypeError):
        pass


def user_data_dir() -> Path:
    base = Path(os.environ.get("LOCALAPPDATA", Path.home()))
    path = base / APP_DIR_NAME
    path.mkdir(parents=True, exist_ok=True)

    # One-time migration keeps normal preferences from previous v9 test builds,
    # but deliberately does not migrate a private OpenAI API key.
    legacy = base / LEGACY_DIR_NAME
    old_config = legacy / "settings.json"
    new_config = path / "settings.json"
    if not new_config.exists() and old_config.exists():
        _migrate_legacy_config(old_config, new_config)
    return path


def config_path() -> Path:
    return user_data_dir() / "settings.json"


def crash_log_path() -> Path:
    return user_data_dir() / "crash.log"
