from __future__ import annotations

import pytest

from rungate import AsyncRungate, Rungate
from rungate._exceptions import RungateError

MOCK_KEY = "rg_sk_test_key"
MOCK_URL = "http://test:8080"


class TestClientInit:
    def test_init_with_explicit_params(self):
        client = Rungate(api_key=MOCK_KEY, base_url=MOCK_URL)
        assert client.api_key == MOCK_KEY
        assert client.base_url == MOCK_URL
        client.close()

    def test_reads_api_key_from_env(self, monkeypatch):
        monkeypatch.setenv("RUNGATE_API_KEY", MOCK_KEY)
        client = Rungate(base_url=MOCK_URL)
        assert client.api_key == MOCK_KEY
        client.close()

    def test_reads_base_url_from_env(self, monkeypatch):
        monkeypatch.setenv("RUNGATE_API_KEY", MOCK_KEY)
        monkeypatch.setenv("RUNGATE_BASE_URL", "http://custom:9090")
        client = Rungate()
        assert client.base_url == "http://custom:9090"
        client.close()

    def test_raises_when_no_api_key(self, monkeypatch):
        monkeypatch.delenv("RUNGATE_API_KEY", raising=False)
        with pytest.raises(RungateError, match="API key is required"):
            Rungate(base_url=MOCK_URL)

    def test_default_base_url(self):
        client = Rungate(api_key=MOCK_KEY)
        assert client.base_url == "http://localhost:8080"
        client.close()

    def test_strips_trailing_slash_from_base_url(self):
        client = Rungate(api_key=MOCK_KEY, base_url="http://test:8080/")
        assert client.base_url == "http://test:8080"
        client.close()

    def test_default_timeout_and_retries(self):
        client = Rungate(api_key=MOCK_KEY)
        assert client.timeout == 60.0
        assert client.max_retries == 2
        client.close()

    def test_custom_timeout_and_retries(self):
        client = Rungate(api_key=MOCK_KEY, timeout=30.0, max_retries=5)
        assert client.timeout == 30.0
        assert client.max_retries == 5
        client.close()

    def test_has_chat_resource(self):
        client = Rungate(api_key=MOCK_KEY)
        assert hasattr(client, "chat")
        assert hasattr(client.chat, "completions")
        client.close()

    def test_async_client_has_same_interface(self):
        client = AsyncRungate(api_key=MOCK_KEY)
        assert hasattr(client, "chat")
        assert hasattr(client.chat, "completions")

    def test_context_manager(self):
        with Rungate(api_key=MOCK_KEY) as client:
            assert client.api_key == MOCK_KEY
        # Client should be closed after exiting

    @pytest.mark.asyncio
    async def test_async_context_manager(self):
        async with AsyncRungate(api_key=MOCK_KEY) as client:
            assert client.api_key == MOCK_KEY
