"""Tests for POST /v1/messages (Anthropic-compatible endpoint)."""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
    from httpx import AsyncClient

# -------------------------------------------------------------------
# Error responses when no backends are available
# -------------------------------------------------------------------


@pytest.mark.unit
async def test_messages_no_backends_returns_error(client: AsyncClient) -> None:
    """Without backends, a valid Anthropic request should get an error."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [{"role": "user", "content": "Hello"}],
            "max_tokens": 256,
        },
    )
    assert resp.status_code in (500, 502, 503)
    data = resp.json()
    # Anthropic error format: {"type": "error", "error": {...}}
    assert "error" in data


@pytest.mark.unit
async def test_messages_error_is_anthropic_format(client: AsyncClient) -> None:
    """Error body should follow Anthropic's envelope."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [{"role": "user", "content": "Hi"}],
            "max_tokens": 100,
        },
    )
    data = resp.json()
    assert data.get("type") == "error"
    err = data["error"]
    assert "type" in err
    assert "message" in err


# -------------------------------------------------------------------
# Request validation
# -------------------------------------------------------------------


@pytest.mark.unit
async def test_messages_missing_model_returns_422(client: AsyncClient) -> None:
    """Omitting 'model' should be rejected by Pydantic."""
    resp = await client.post(
        "/v1/messages",
        json={
            "messages": [{"role": "user", "content": "Hello"}],
            "max_tokens": 100,
        },
    )
    assert resp.status_code == 422


@pytest.mark.unit
async def test_messages_missing_messages_returns_422(client: AsyncClient) -> None:
    """Omitting 'messages' should be rejected by Pydantic."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "max_tokens": 100,
        },
    )
    assert resp.status_code == 422


@pytest.mark.unit
async def test_messages_empty_messages_returns_400(client: AsyncClient) -> None:
    """Empty messages list should be rejected."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [],
            "max_tokens": 100,
        },
    )
    assert resp.status_code == 400


@pytest.mark.unit
async def test_messages_accepts_system_param(client: AsyncClient) -> None:
    """Anthropic 'system' field should be accepted."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [{"role": "user", "content": "Test"}],
            "system": "You are helpful.",
            "max_tokens": 100,
        },
    )
    # Should not 422 -- only backend error is expected
    assert resp.status_code != 422


@pytest.mark.unit
async def test_messages_accepts_content_blocks(client: AsyncClient) -> None:
    """Anthropic content-block format should be accepted."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Hello from block content"},
                    ],
                }
            ],
            "max_tokens": 100,
        },
    )
    assert resp.status_code != 422


@pytest.mark.unit
async def test_messages_accepts_stream_flag(client: AsyncClient) -> None:
    """Request with stream=true should pass validation."""
    resp = await client.post(
        "/v1/messages",
        json={
            "model": "claude-3-5-sonnet-20241022",
            "messages": [{"role": "user", "content": "Test"}],
            "max_tokens": 100,
            "stream": True,
        },
    )
    assert resp.status_code != 422
