"""Durable map of local voice profiles → OpenAI TTS voice refs."""

from __future__ import annotations

import json
import logging
import re
import threading
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from uuid import uuid4

from app.config import get_settings
from app.persistence import resolve_persist_backend

logger = logging.getLogger(__name__)
_SAFE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")


def _utc_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


@dataclass
class VoiceProfile:
    voice_id: str
    company_id: str
    voice_name: str
    tts_model: str
    mode: str  # custom | builtin
    openai_voice_id: str | None = None
    builtin_voice: str | None = None
    consent_id: str | None = None
    sample_sha256: str | None = None
    created_at: str = field(default_factory=_utc_iso)
    meta: dict[str, Any] = field(default_factory=dict)

    def speech_voice_param(self) -> str | dict[str, str]:
        if self.mode == "custom" and self.openai_voice_id:
            return {"id": self.openai_voice_id}
        return (self.builtin_voice or "coral").lower()


class VoiceProfileStore:
    def __init__(
        self,
        *,
        persist_dir: str | Path | None = None,
        backend: str | None = None,
    ) -> None:
        self._lock = threading.RLock()
        self._profiles: dict[str, VoiceProfile] = {}
        self._persist_dir = Path(persist_dir) if persist_dir else None
        self._backend = (backend or resolve_persist_backend()).strip().lower()
        if self._persist_dir is not None:
            self._persist_dir.mkdir(parents=True, exist_ok=True)

    def configure(
        self,
        *,
        persist_dir: str | Path | None = None,
        backend: str | None = None,
    ) -> None:
        with self._lock:
            if persist_dir is not None:
                self._persist_dir = Path(persist_dir) if persist_dir else None
                if self._persist_dir is not None:
                    self._persist_dir.mkdir(parents=True, exist_ok=True)
            if backend is not None:
                self._backend = backend.strip().lower()

    def _use_disk(self) -> bool:
        return self._backend in {"filesystem", "dual"}

    def _use_db(self) -> bool:
        return self._backend in {"postgres", "dual"}

    def _path(self, voice_id: str) -> Path | None:
        if self._persist_dir is None or not _SAFE.match(voice_id):
            return None
        safe = voice_id.replace(":", "_").replace("/", "_")
        return self._persist_dir / f"{safe}.json"

    def save(self, profile: VoiceProfile) -> VoiceProfile:
        with self._lock:
            self._profiles[profile.voice_id] = profile
            if self._use_disk():
                path = self._path(profile.voice_id)
                if path is not None:
                    try:
                        path.write_text(
                            json.dumps(asdict(profile), indent=2, ensure_ascii=False),
                            encoding="utf-8",
                        )
                    except Exception:  # noqa: BLE001
                        logger.warning(
                            "Failed to persist voice profile %s", profile.voice_id
                        )
            if self._use_db():
                try:
                    from app.services.voice.voice_db import upsert_profile

                    upsert_profile(profile)
                except Exception:  # noqa: BLE001
                    logger.warning(
                        "Failed to DB-persist voice profile %s",
                        profile.voice_id,
                        exc_info=True,
                    )
                    if self._backend == "postgres":
                        raise
            return profile

    def get(self, voice_id: str) -> VoiceProfile | None:
        with self._lock:
            if voice_id in self._profiles:
                return self._profiles[voice_id]
        if self._use_db():
            from app.services.voice.voice_db import get_profile

            profile = get_profile(voice_id)
            if profile is not None:
                with self._lock:
                    self._profiles[voice_id] = profile
                return profile
        path = self._path(voice_id)
        if path is None or not path.exists():
            return None
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            profile = VoiceProfile(
                **{k: data.get(k) for k in VoiceProfile.__dataclass_fields__}
            )
            with self._lock:
                self._profiles[voice_id] = profile
            if self._use_db():
                try:
                    from app.services.voice.voice_db import upsert_profile

                    upsert_profile(profile)
                except Exception:  # noqa: BLE001
                    pass
            return profile
        except Exception:  # noqa: BLE001
            logger.warning("Failed to load voice profile %s", voice_id, exc_info=True)
            return None

    def clear(self) -> None:
        with self._lock:
            self._profiles.clear()


def new_voice_id() -> str:
    return f"voice-{uuid4().hex[:16]}"


def build_voice_store() -> VoiceProfileStore:
    try:
        settings = get_settings()
        persist = getattr(settings, "voice_profile_dir", None) or ".data/voice_profiles"
    except Exception:  # noqa: BLE001
        persist = ".data/voice_profiles"
    return VoiceProfileStore(persist_dir=persist)


voice_profile_store = build_voice_store()
