"""OpenAI custom voice creation (consent + sample) for gpt-4o-mini-tts."""

from __future__ import annotations

import base64
import hashlib
import logging
from typing import Any

import httpx

from app.config import get_settings
from app.services.voice.tts_openai import BUILTIN_VOICES

logger = logging.getLogger(__name__)


class VoiceCloneError(Exception):
    def __init__(self, message: str, *, code: str = "voice_clone_error") -> None:
        self.code = code
        super().__init__(message)


def decode_audio_b64(b64: str | None) -> bytes | None:
    if not b64 or not str(b64).strip():
        return None
    raw = str(b64).strip()
    if "," in raw and raw.lower().startswith("data:"):
        raw = raw.split(",", 1)[1]
    try:
        data = base64.b64decode(raw, validate=False)
    except Exception as exc:  # noqa: BLE001
        raise VoiceCloneError("Invalid sample_audio_base64", code="invalid_audio") from exc
    if len(data) < 64:
        raise VoiceCloneError("Audio sample too small", code="invalid_audio")
    return data


async def _fetch_url(url: str) -> bytes:
    async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
        res = await client.get(url)
        res.raise_for_status()
        return res.content


async def create_voice_consent(
    *,
    recording: bytes,
    name: str,
    language: str = "en",
    mime_type: str = "audio/wav",
) -> str:
    settings = get_settings()
    api_key = (settings.openai_api_key or "").strip()
    if not api_key:
        raise VoiceCloneError("OPENAI_API_KEY not configured", code="tts_not_configured")

    filename = "consent.webm" if "webm" in mime_type else "consent.wav"
    async with httpx.AsyncClient(timeout=120.0) as client:
        res = await client.post(
            "https://api.openai.com/v1/audio/voice_consents",
            headers={"Authorization": f"Bearer {api_key}"},
            # All multipart fields via `files` — avoid AsyncClient + files/data mix.
            files=[
                ("recording", (filename, recording, mime_type)),
                ("name", (None, name)),
                ("language", (None, language)),
            ],
        )
        if res.status_code >= 400:
            raise VoiceCloneError(
                f"Consent upload HTTP {res.status_code}: {res.text[:400]}",
                code="consent_failed",
            )
        body = res.json()
    consent_id = body.get("id") or body.get("consent_id")
    if not consent_id:
        raise VoiceCloneError("Consent response missing id", code="consent_failed")
    return str(consent_id)


async def create_custom_voice(
    *,
    name: str,
    audio_sample: bytes,
    consent_id: str,
    mime_type: str = "audio/wav",
) -> dict[str, Any]:
    settings = get_settings()
    api_key = (settings.openai_api_key or "").strip()
    if not api_key:
        raise VoiceCloneError("OPENAI_API_KEY not configured", code="tts_not_configured")

    filename = "sample.webm" if "webm" in mime_type else "sample.wav"
    async with httpx.AsyncClient(timeout=180.0) as client:
        res = await client.post(
            "https://api.openai.com/v1/audio/voices",
            headers={"Authorization": f"Bearer {api_key}"},
            files=[
                ("audio_sample", (filename, audio_sample, mime_type)),
                ("name", (None, name)),
                ("consent", (None, consent_id)),
            ],
        )
        if res.status_code >= 400:
            raise VoiceCloneError(
                f"Voice create HTTP {res.status_code}: {res.text[:400]}",
                code="voice_create_failed",
            )
        return res.json()


async def resolve_sample_bytes(
    *,
    sample_audio_base64: str | None,
    sample_url: str | None,
) -> tuple[bytes | None, str | None]:
    data = decode_audio_b64(sample_audio_base64)
    sha = hashlib.sha256(data).hexdigest() if data else None
    if data:
        return data, sha
    if sample_url:
        data = await _fetch_url(sample_url)
        if len(data) < 64:
            raise VoiceCloneError("Downloaded sample too small", code="invalid_audio")
        return data, hashlib.sha256(data).hexdigest()
    return None, None


def pick_builtin_voice(options: dict[str, Any] | None) -> str:
    settings = get_settings()
    requested = str((options or {}).get("openai_voice") or settings.tts_default_voice or "coral")
    requested = requested.strip().lower()
    if requested in BUILTIN_VOICES:
        return requested
    return (settings.tts_default_voice or "coral").lower()
