from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

import pytest
from openai import AuthenticationError

from app.generation.llm_client import LLMAuthError, LLMClient, ModelInfo


@pytest.mark.asyncio
async def test_list_models_success():
    client = MagicMock()
    client.models = MagicMock()
    client.models.list = AsyncMock(
        return_value=SimpleNamespace(
            data=[
                SimpleNamespace(id="gpt-4o", owned_by="openai", created=1715367049),
                SimpleNamespace(id="text-embedding-3-small", owned_by="openai", created=1),
            ]
        )
    )
    llm = LLMClient(client=client, api_key="sk-test")

    models = await llm.list_models()

    assert models == [
        ModelInfo(id="gpt-4o", owned_by="openai", created=1715367049),
        ModelInfo(id="text-embedding-3-small", owned_by="openai", created=1),
    ]


@pytest.mark.asyncio
async def test_list_models_auth_error():
    client = MagicMock()
    client.models = MagicMock()
    client.models.list = AsyncMock(
        side_effect=AuthenticationError(
            "invalid key",
            response=MagicMock(status_code=401),
            body=None,
        )
    )
    llm = LLMClient(client=client, api_key="sk-bad")

    with pytest.raises(LLMAuthError):
        await llm.list_models()
