import os
import pytest
from anyfast import AnyFast, AnyFastError


class TestAnyFastClient:
    def test_create_with_api_key(self):
        client = AnyFast(api_key="test-key")
        assert client.api_key == "test-key"

    def test_create_from_env(self):
        original = os.environ.get("ANYFAST_API_KEY")
        os.environ["ANYFAST_API_KEY"] = "env-key"
        try:
            client = AnyFast()
            assert client.api_key == "env-key"
        finally:
            if original:
                os.environ["ANYFAST_API_KEY"] = original
            else:
                del os.environ["ANYFAST_API_KEY"]

    def test_api_key_param_over_env(self):
        original = os.environ.get("ANYFAST_API_KEY")
        os.environ["ANYFAST_API_KEY"] = "env-key"
        try:
            client = AnyFast(api_key="param-key")
            assert client.api_key == "param-key"
        finally:
            if original:
                os.environ["ANYFAST_API_KEY"] = original
            else:
                del os.environ["ANYFAST_API_KEY"]

    def test_missing_api_key_raises(self):
        original = os.environ.get("ANYFAST_API_KEY")
        if "ANYFAST_API_KEY" in os.environ:
            del os.environ["ANYFAST_API_KEY"]
        try:
            with pytest.raises(AnyFastError, match="API key is required"):
                AnyFast()
        finally:
            if original:
                os.environ["ANYFAST_API_KEY"] = original

    def test_sub_modules_initialized(self):
        client = AnyFast(api_key="test-key")
        assert hasattr(client, "chat")
        assert hasattr(client, "image")
        assert hasattr(client, "video")
        assert hasattr(client, "asset")

    def test_custom_base_url(self):
        client = AnyFast(api_key="test-key", base_url="https://custom.example.com")
        assert client._base_client.base_url == "https://custom.example.com"

    def test_custom_timeout(self):
        client = AnyFast(api_key="test-key", timeout=60.0)
        assert client._base_client.timeout == 60.0
