"""Tests for transcription.providers.openrouter."""

from types import SimpleNamespace

import pytest

from transcription.config import Settings
from transcription.providers.base import ProviderError
from transcription.providers.base import ProviderResponseError
from transcription.providers.openrouter import DEFAULT_OPENROUTER_MODEL
from transcription.providers.openrouter import OpenRouterTranscriptionProvider


class _FakeChat:
    def __init__(self, response=None, error: Exception | None = None):
        self._response = response
        self._error = error
        self.calls = []

    async def send_async(self, **kwargs):
        self.calls.append(kwargs)
        if self._error:
            raise self._error
        return self._response


class _FakeClient:
    def __init__(self, response=None, error: Exception | None = None):
        self.chat = _FakeChat(response=response, error=error)


@pytest.mark.unit
class TestOpenRouterProviderInit:
    """Verify OpenRouter provider initialization behavior."""

    def test_model_falls_back_to_default_when_unset(self):
        """Provider uses adapter default model when provider_model is None."""
        settings = Settings(openrouter_api_key="test-key", provider_model=None)
        provider = OpenRouterTranscriptionProvider(settings=settings, client=_FakeClient())
        assert provider.model == DEFAULT_OPENROUTER_MODEL

    def test_model_uses_configured_value(self):
        """Provider uses configured provider_model when present."""
        settings = Settings(openrouter_api_key="test-key", provider_model="vendor/custom-model")
        provider = OpenRouterTranscriptionProvider(settings=settings, client=_FakeClient())
        assert provider.model == "vendor/custom-model"


@pytest.mark.unit
class TestOpenRouterProviderTranscribe:
    """Verify OpenRouter request construction and response parsing."""

    @pytest.mark.asyncio
    async def test_includes_optional_referer_and_title_when_set(self):
        """Transcribe sends app attribution fields when configured."""
        response = {"model": "vendor/model-a", "choices": [{"message": {"content": "Transcript text"}}]}
        client = _FakeClient(response=response)
        settings = Settings(
            openrouter_api_key="test-key",
            openrouter_http_referer="https://example.test",
            openrouter_app_title="Transcription App",
        )
        provider = OpenRouterTranscriptionProvider(settings=settings, client=client)

        result = await provider.transcribe(
            prompt_text="Prompt body",
            image_bytes=b"img-bytes",
            mime_type="image/png",
        )

        send_call = client.chat.calls[0]
        assert send_call["http_referer"] == "https://example.test"
        assert send_call["x_open_router_title"] == "Transcription App"
        assert result.text == "Transcript text"

    @pytest.mark.asyncio
    async def test_parses_successful_response_text(self):
        """Transcribe returns normalized text from a valid response payload."""
        response = {
            "model": "vendor/model-b",
            "choices": [{"message": {"content": [{"text": "Line 1"}, {"text": "Line 2"}]}}],
        }
        provider = OpenRouterTranscriptionProvider(
            settings=Settings(openrouter_api_key="test-key"),
            client=_FakeClient(response=response),
        )

        result = await provider.transcribe(
            prompt_text="Prompt body",
            image_bytes=b"img-bytes",
            mime_type="image/jpeg",
        )

        assert result.text == "Line 1\nLine 2"
        assert result.provider == "openrouter"
        assert result.model == "vendor/model-b"

    @pytest.mark.asyncio
    async def test_maps_sdk_exception_to_provider_error(self):
        """Transcribe converts SDK failures to ProviderError."""
        provider = OpenRouterTranscriptionProvider(
            settings=Settings(openrouter_api_key="test-key"),
            client=_FakeClient(error=RuntimeError("network down")),
        )

        with pytest.raises(ProviderError):
            await provider.transcribe(
                prompt_text="Prompt body",
                image_bytes=b"img-bytes",
                mime_type="image/png",
            )

    @pytest.mark.asyncio
    async def test_raises_on_empty_or_invalid_response(self):
        """Transcribe raises ProviderResponseError for missing completion text."""
        provider = OpenRouterTranscriptionProvider(
            settings=Settings(openrouter_api_key="test-key"),
            client=_FakeClient(response=SimpleNamespace(choices=[])),
        )

        with pytest.raises(ProviderResponseError):
            await provider.transcribe(
                prompt_text="Prompt body",
                image_bytes=b"img-bytes",
                mime_type="image/png",
            )
