"""GPT-4o Mini TTS + voice cloning via manager-clones (uploaded sample, mocked OpenAI)."""

from __future__ import annotations

import base64
from pathlib import Path

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app
from app.services.voice.voice_store import voice_profile_store

client = TestClient(app)
HEADERS = {"X-Internal-Token": get_settings().internal_api_token}


def _audio_b64(tag: bytes = b"\x00") -> str:
    return base64.b64encode(b"RIFF" + tag * 200).decode()


@pytest.fixture(autouse=True)
def _reset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
    voice_profile_store.configure(persist_dir=tmp_path / "voices", backend="filesystem")
    voice_profile_store.clear()
    get_settings.cache_clear()
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)
    yield
    voice_profile_store.clear()
    get_settings.cache_clear()


def _clone_id() -> str:
    res = client.post(
        "/api/v1/manager-clones",
        headers=HEADERS,
        json={"company_id": "co-1", "sample_questions": ["Tell me about a win."]},
    )
    assert res.status_code == 200, res.text
    return res.json()["clone_id"]


def _mock_openai_voice(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_consent(**_k):
        return "cons_test123"

    async def fake_create(**_k):
        return {"id": "voice_openai_abc", "name": "Brand Voice", "object": "audio.voice"}

    monkeypatch.setattr(
        "app.services.enterprise.enterprise.create_voice_consent", fake_consent
    )
    monkeypatch.setattr(
        "app.services.enterprise.enterprise.create_custom_voice", fake_create
    )


def _voice_action(clone_id: str, body: dict) -> dict:
    res = client.post(
        f"/api/v1/manager-clones/{clone_id}/actions",
        headers=HEADERS,
        json={"module": "voice", "action": "generate_voice", "input": body},
    )
    assert res.status_code == 200, res.text
    return res.json()["result"]


def test_voice_clone_rejects_builtin_selection_without_upload() -> None:
    clone_id = _clone_id()
    res = client.post(
        f"/api/v1/manager-clones/{clone_id}/actions",
        headers=HEADERS,
        json={
            "module": "voice",
            "action": "generate_voice",
            "input": {
                "voice_name": "Brand Voice",
                "options": {"openai_voice": "coral"},
            },
        },
    )
    assert res.status_code == 422


def test_voice_clone_from_uploaded_sample(monkeypatch: pytest.MonkeyPatch) -> None:
    _mock_openai_voice(monkeypatch)
    clone_id = _clone_id()
    body = _voice_action(
        clone_id,
        {
            "voice_name": "Cloned",
            "sample_audio_base64": _audio_b64(b"\x00"),
            "consent_audio_base64": _audio_b64(b"\x01"),
        },
    )
    assert body["mode"] == "custom"
    assert body["openai_voice_id"] == "voice_openai_abc"
    assert body["consent_id"] == "cons_test123"
    assert body["voice_id"]
    assert voice_profile_store.get(body["voice_id"]) is not None


def test_tts_synthesize_builtin(monkeypatch: pytest.MonkeyPatch) -> None:
    """Generic TTS may still use a builtin name; manager cloning must not."""
    from app.services.voice.tts_openai import TtsResult

    async def fake_synth(**_k):
        return TtsResult(
            audio_bytes=b"FAKEMP3",
            model="gpt-4o-mini-tts",
            voice="coral",
            mime_type="audio/mpeg",
            format="mp3",
            message="ok",
        )

    monkeypatch.setattr("app.services.voice.tts_service.synthesize_speech", fake_synth)
    res = client.post(
        "/api/v1/tts/synthesize",
        headers=HEADERS,
        json={
            "text": "Welcome to your interview.",
            "voice": "coral",
            "response_format": "mp3",
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["status"] == "succeeded"
    assert body["model"] == "gpt-4o-mini-tts"
    assert body["audio_base64"]
    assert base64.b64decode(body["audio_base64"]) == b"FAKEMP3"


def test_tts_with_cloned_voice_id(monkeypatch: pytest.MonkeyPatch) -> None:
    from app.services.voice.tts_openai import TtsResult

    _mock_openai_voice(monkeypatch)
    clone_id = _clone_id()
    voice = _voice_action(
        clone_id,
        {
            "voice_name": "Interviewer",
            "sample_audio_base64": _audio_b64(b"\x02"),
            "consent_audio_base64": _audio_b64(b"\x03"),
        },
    )
    vid = voice["voice_id"]

    captured: dict = {}

    async def fake_synth(*, text, voice, **_k):
        captured["voice"] = voice
        return TtsResult(
            audio_bytes=b"xx",
            model="gpt-4o-mini-tts",
            voice=voice if isinstance(voice, str) else voice,
            mime_type="audio/mpeg",
            format="mp3",
        )

    monkeypatch.setattr("app.services.voice.tts_service.synthesize_speech", fake_synth)
    res = client.post(
        "/api/v1/tts/synthesize",
        headers=HEADERS,
        json={
            "text": "Hello",
            "voice_id": vid,
            "response_format": "mp3",
        },
    )
    assert res.status_code == 200
    # Resolved OpenAI custom voice id for synthesis
    assert captured.get("voice") == {"id": "voice_openai_abc"}
