"""Tests for configuration."""

from unittest.mock import patch

from llm_observatory.config import configure, get_config


def test_configure_direct():
    configure(api_key="sk-test", base_url="http://localhost:8080")
    cfg = get_config()
    assert cfg["api_key"] == "sk-test"
    assert cfg["base_url"] == "http://localhost:8080"
    assert cfg["enabled"] is True
    assert cfg["flush_interval"] == 5.0
    assert cfg["flush_batch_size"] == 50


def test_configure_env_vars(monkeypatch):
    monkeypatch.setenv("LLM_OBSERVATORY_API_KEY", "sk-env-key")
    monkeypatch.setenv("LLM_OBSERVATORY_BASE_URL", "http://env-host:9090")
    monkeypatch.setenv("LLM_OBSERVATORY_ENABLED", "false")

    configure()
    cfg = get_config()
    assert cfg["api_key"] == "sk-env-key"
    assert cfg["base_url"] == "http://env-host:9090"
    assert cfg["enabled"] is False


def test_configure_direct_overrides_env(monkeypatch):
    monkeypatch.setenv("LLM_OBSERVATORY_API_KEY", "sk-env")

    configure(api_key="sk-direct")
    cfg = get_config()
    assert cfg["api_key"] == "sk-direct"


def test_configure_disabled():
    configure(api_key="sk-test", base_url="http://localhost", enabled=False)
    cfg = get_config()
    assert cfg["enabled"] is False


def test_configure_custom_params():
    configure(
        api_key="sk-test",
        base_url="http://localhost",
        flush_interval=1.0,
        flush_batch_size=10,
        max_queue_size=500,
        redact_messages=True,
    )
    cfg = get_config()
    assert cfg["flush_interval"] == 1.0
    assert cfg["flush_batch_size"] == 10
    assert cfg["max_queue_size"] == 500
    assert cfg["redact_messages"] is True


def test_configure_invalidates_transport():
    """Calling configure() should shut down the existing transport singleton."""
    with patch("llm_observatory.transport.shutdown_transport") as mock_shutdown:
        configure(api_key="sk-test", base_url="http://localhost:8080")
        mock_shutdown.assert_called_once()


def test_reconfigure_picks_up_new_settings():
    """A new Transport created after reconfigure() should use the new settings."""
    from llm_observatory.transport import Transport

    configure(
        api_key="sk-test",
        base_url="http://localhost:8080",
        flush_interval=1.0,
        flush_batch_size=10,
        max_queue_size=100,
    )
    t1 = Transport()
    assert t1._flush_interval == 1.0
    assert t1._flush_batch_size == 10

    configure(
        api_key="sk-test",
        base_url="http://localhost:8080",
        flush_interval=2.0,
        flush_batch_size=20,
        max_queue_size=200,
    )
    t2 = Transport()
    assert t2._flush_interval == 2.0
    assert t2._flush_batch_size == 20
