"""Tests for RunBlob client initialization, config, and auth."""
from __future__ import annotations

import os
import pytest

from runblob import RunBlob
from runblob._config import resolve_api_key


class TestResolveApiKey:
    def test_explicit_key(self):
        assert resolve_api_key("rb_test") == "rb_test"

    def test_env_var(self, monkeypatch):
        monkeypatch.setenv("RUNBLOB_API_KEY", "rb_from_env")
        assert resolve_api_key(None) == "rb_from_env"

    def test_missing_raises(self, monkeypatch):
        monkeypatch.delenv("RUNBLOB_API_KEY", raising=False)
        with pytest.raises(ValueError, match="API key is required"):
            resolve_api_key(None)


class TestClientInit:
    async def test_default_config(self, api_key):
        async with RunBlob(api_key=api_key) as client:
            assert client.config.api_key == api_key
            assert client.config.base_url == "https://platform.runblob.io"
            assert client.config.timeout == 120.0
            assert client.config.max_retries == 3

    async def test_custom_config(self, api_key):
        async with RunBlob(
            api_key=api_key,
            base_url="https://custom.api.io",
            timeout=30.0,
            max_retries=5,
            max_connections=200,
            rate_limit_rps=100.0,
        ) as client:
            assert client.config.base_url == "https://custom.api.io"
            assert client.config.timeout == 30.0
            assert client.config.max_retries == 5
            assert client.config.max_connections == 200

    async def test_no_api_key_raises(self, monkeypatch):
        monkeypatch.delenv("RUNBLOB_API_KEY", raising=False)
        with pytest.raises(ValueError, match="API key is required"):
            RunBlob()

    async def test_has_nanobanana_resource(self, client):
        assert hasattr(client, "nanobanana")

    async def test_context_manager(self, api_key):
        client = RunBlob(api_key=api_key)
        async with client:
            assert client.config.api_key == api_key
        # After exit, client should be closed
