"""Tests for CaliperClient."""

import os
from unittest.mock import patch

import pytest

from timeback_caliper import CaliperClient


class TestCaliperClientInit:
    """Tests for client initialization."""

    def test_staging_environment(self):
        """Staging environment should use staging URL."""
        with patch.dict(os.environ, {"CALIPER_CLIENT_ID": "id", "CALIPER_CLIENT_SECRET": "secret"}):
            client = CaliperClient(env="staging")
            # BEYOND_AI (default) uses "staging" subdomain; LEARNWITH_AI uses "dev"
            assert "staging" in client._transport.base_url

    def test_production_environment(self):
        """Production environment should use production URL."""
        with patch.dict(os.environ, {"CALIPER_CLIENT_ID": "id", "CALIPER_CLIENT_SECRET": "secret"}):
            client = CaliperClient(env="production")
            # Production URLs don't contain "dev" or "staging"
            assert "dev" not in client._transport.base_url
            assert "staging" not in client._transport.base_url

    def test_custom_base_url(self):
        """Custom base URL should override environment."""
        with patch.dict(
            os.environ,
            {
                "CALIPER_CLIENT_ID": "id",
                "CALIPER_CLIENT_SECRET": "secret",
                "CALIPER_TOKEN_URL": "https://auth.example.com/oauth2/token",
            },
        ):
            client = CaliperClient(
                base_url="https://custom.example.com",
                auth_url="https://auth.example.com/oauth2/token",
            )
            assert client._transport.base_url == "https://custom.example.com"

    def test_explicit_credentials(self):
        """Explicit credentials should work."""
        client = CaliperClient(
            env="staging",
            client_id="my-id",
            client_secret="my-secret",
        )
        assert client._provider is not None
        tm = client._provider.get_token_manager("caliper")
        assert tm is not None
        assert tm._config.client_id == "my-id"
        assert tm._config.client_secret == "my-secret"

    def test_missing_credentials_raises(self):
        """Missing credentials should raise AuthenticationError."""
        with patch.dict(os.environ, {}, clear=True):
            # Remove any env vars that might be set
            os.environ.pop("CALIPER_CLIENT_ID", None)
            os.environ.pop("CALIPER_CLIENT_SECRET", None)
            with pytest.raises(ValueError, match="Missing required environment variable"):
                CaliperClient(env="staging")


class TestCaliperClientContextManager:
    """Tests for context manager support."""

    @pytest.mark.asyncio
    async def test_context_manager(self):
        """Client should work as async context manager."""
        async with CaliperClient(env="staging", client_id="id", client_secret="secret") as client:
            assert client._provider is not None
        # Client should be closed after exiting context
