"""Tests for BotManifoldClient."""

import os
from unittest.mock import MagicMock, patch

import pytest

from botmanifold import BotManifoldClient, BotManifoldError, AuthenticationError


class TestBotManifoldClient:
    """Tests for unified client."""

    def test_init_with_api_key(self):
        """Client initializes with explicit API key."""
        client = BotManifoldClient(api_key="test_key")
        assert client.api_key == "test_key"
        assert "Bearer test_key" in client._session.headers.get("Authorization", "")

    def test_init_from_env_botmanifold(self):
        """Client reads BOTMANIFOLD_API_KEY from environment."""
        with patch.dict(os.environ, {"BOTMANIFOLD_API_KEY": "env_key"}, clear=False):
            # Ensure BOTARENA_API_KEY doesn't interfere
            os.environ.pop("BOTARENA_API_KEY", None)
            client = BotManifoldClient()
            assert client.api_key == "env_key"

    def test_init_from_env_botarena_fallback(self):
        """Client falls back to BOTARENA_API_KEY for backwards compat."""
        with patch.dict(os.environ, {"BOTARENA_API_KEY": "legacy_key"}, clear=False):
            os.environ.pop("BOTMANIFOLD_API_KEY", None)
            client = BotManifoldClient()
            assert client.api_key == "legacy_key"

    def test_has_verify_property(self):
        """Client has verify property."""
        client = BotManifoldClient()
        assert hasattr(client, "verify")
        assert client.verify is not None

    def test_has_arena_property(self):
        """Client has arena property."""
        client = BotManifoldClient()
        assert hasattr(client, "arena")
        assert client.arena is not None

    def test_user_agent_header(self):
        """Client sets User-Agent header."""
        client = BotManifoldClient()
        ua = client._session.headers.get("User-Agent", "")
        assert ua.startswith("botmanifold-sdk/")

    def test_custom_base_url(self):
        """Client accepts custom base URL."""
        client = BotManifoldClient(base_url="https://custom.api.com")
        assert client.base_url == "https://custom.api.com"

    def test_base_url_strips_trailing_slash(self):
        """Base URL strips trailing slash."""
        client = BotManifoldClient(base_url="https://api.com/")
        assert client.base_url == "https://api.com"

    @patch("requests.Session.request")
    def test_request_adds_timeout(self, mock_request):
        """Requests include timeout."""
        mock_response = MagicMock()
        mock_response.ok = True
        mock_response.json.return_value = {"status": "ok"}
        mock_request.return_value = mock_response

        client = BotManifoldClient(timeout=60)
        client._request("GET", "/test")

        mock_request.assert_called_once()
        _, kwargs = mock_request.call_args
        assert kwargs.get("timeout") == 60

    @patch("requests.Session.request")
    def test_request_handles_401(self, mock_request):
        """401 response raises AuthenticationError."""
        mock_response = MagicMock()
        mock_response.status_code = 401
        mock_response.ok = False
        mock_request.return_value = mock_response

        client = BotManifoldClient()
        with pytest.raises(AuthenticationError, match="Invalid API key"):
            client._request("GET", "/test")

    @patch("requests.Session.request")
    def test_request_handles_403(self, mock_request):
        """403 response raises AuthenticationError."""
        mock_response = MagicMock()
        mock_response.status_code = 403
        mock_response.ok = False
        mock_request.return_value = mock_response

        client = BotManifoldClient()
        with pytest.raises(AuthenticationError, match="Access denied"):
            client._request("GET", "/test")

    @patch("requests.Session.request")
    def test_request_handles_server_error(self, mock_request):
        """500 response raises BotManifoldError."""
        mock_response = MagicMock()
        mock_response.status_code = 500
        mock_response.ok = False
        mock_response.json.return_value = {"detail": "Internal error"}
        mock_request.return_value = mock_response

        client = BotManifoldClient()
        with pytest.raises(BotManifoldError, match="API error.*500.*Internal error"):
            client._request("GET", "/test")
