"""Tests for configuration management."""

from agentcenter.config import Settings, get_settings


def test_settings_default_values(monkeypatch):
    """Test Settings with default values."""
    # Clear any environment variables that might interfere
    monkeypatch.delenv("APP_NAME", raising=False)
    monkeypatch.delenv("DEBUG", raising=False)
    monkeypatch.delenv("LOG_LEVEL", raising=False)
    monkeypatch.delenv("API_KEY", raising=False)

    # Create Settings without .env file
    settings = Settings(_env_file=None)
    assert settings.app_name == "Agent Center"
    assert settings.debug is False
    assert settings.log_level == "INFO"
    assert settings.api_key is None


def test_settings_custom_values():
    """Test Settings with custom values."""
    settings = Settings(
        app_name="Custom App",
        debug=True,
        log_level="DEBUG",
        api_key="test-key-123",
    )
    assert settings.app_name == "Custom App"
    assert settings.debug is True
    assert settings.log_level == "DEBUG"
    assert settings.api_key == "test-key-123"


def test_settings_partial_override(monkeypatch):
    """Test Settings with partial override."""
    # Clear environment variables
    monkeypatch.delenv("APP_NAME", raising=False)
    monkeypatch.delenv("DEBUG", raising=False)
    monkeypatch.delenv("LOG_LEVEL", raising=False)
    monkeypatch.delenv("API_KEY", raising=False)

    settings = Settings(_env_file=None, app_name="Partial App", debug=True)
    assert settings.app_name == "Partial App"
    assert settings.debug is True
    assert settings.log_level == "INFO"  # default
    assert settings.api_key is None  # default


def test_settings_from_env_vars(monkeypatch):
    """Test Settings reads from environment variables."""
    monkeypatch.setenv("APP_NAME", "Env App")
    monkeypatch.setenv("DEBUG", "true")
    monkeypatch.setenv("LOG_LEVEL", "WARNING")
    monkeypatch.setenv("API_KEY", "env-key-456")

    settings = Settings()
    assert settings.app_name == "Env App"
    assert settings.debug is True
    assert settings.log_level == "WARNING"
    assert settings.api_key == "env-key-456"


def test_settings_env_vars_override_defaults(monkeypatch):
    """Test environment variables override defaults."""
    monkeypatch.setenv("DEBUG", "true")

    settings = Settings()
    assert settings.debug is True  # from env, not default False


def test_settings_boolean_conversion(monkeypatch):
    """Test boolean value conversion from env vars."""
    # Test various boolean representations
    test_cases = [
        ("true", True),
        ("True", True),
        ("1", True),
        ("yes", True),
        ("on", True),
        ("false", False),
        ("False", False),
        ("0", False),
        ("no", False),
        ("off", False),
    ]

    for env_value, expected in test_cases:
        monkeypatch.setenv("DEBUG", env_value)
        settings = Settings()
        assert settings.debug == expected, f"Failed for {env_value}"


def test_settings_case_insensitive(monkeypatch):
    """Test case insensitive environment variable names."""
    # These should all work due to case_sensitive=False
    monkeypatch.setenv("app_name", "lowercase")
    settings = Settings()
    assert settings.app_name == "lowercase"

    monkeypatch.setenv("App_Name", "mixedcase")
    settings = Settings()
    assert settings.app_name == "mixedcase"


def test_settings_model_dump():
    """Test model_dump returns all settings."""
    settings = Settings(
        app_name="Test App",
        debug=True,
        log_level="DEBUG",
        api_key="test-key",
    )

    data = settings.model_dump()
    assert isinstance(data, dict)
    assert data["app_name"] == "Test App"
    assert data["debug"] is True
    assert data["log_level"] == "DEBUG"
    assert data["api_key"] == "test-key"


def test_settings_optional_api_key(monkeypatch):
    """Test api_key can be None."""
    # Clear environment variables
    monkeypatch.delenv("API_KEY", raising=False)

    settings = Settings(_env_file=None)
    assert settings.api_key is None

    settings_with_key = Settings(_env_file=None, api_key="my-key")
    assert settings_with_key.api_key == "my-key"


def test_get_settings():
    """Test get_settings function returns Settings instance."""
    settings = get_settings()
    assert isinstance(settings, Settings)
    assert hasattr(settings, "app_name")
    assert hasattr(settings, "debug")
    assert hasattr(settings, "log_level")
    assert hasattr(settings, "api_key")


def test_get_settings_returns_new_instance():
    """Test get_settings returns a new instance each time."""
    settings1 = get_settings()
    settings2 = get_settings()

    # They should be different instances
    assert settings1 is not settings2

    # But have the same values
    assert settings1.app_name == settings2.app_name


def test_settings_field_descriptions():
    """Test that fields have descriptions."""
    settings = Settings()
    schema = settings.model_json_schema()

    assert "properties" in schema
    assert "app_name" in schema["properties"]
    assert "description" in schema["properties"]["app_name"]
    assert schema["properties"]["app_name"]["description"] == "Application name"


def test_settings_validation():
    """Test that Settings validates types."""
    # This should work
    settings = Settings(debug=True)
    assert settings.debug is True

    # Pydantic should convert string to bool
    settings = Settings(debug="true")
    assert settings.debug is True


def test_settings_with_env_file(tmp_path, monkeypatch):
    """Test Settings reads from .env file."""
    # Create a temporary .env file
    env_file = tmp_path / ".env"
    env_file.write_text(
        "APP_NAME=From Env File\n" "DEBUG=true\n" "LOG_LEVEL=ERROR\n" "API_KEY=file-key-789\n"
    )

    # Change to temp directory
    monkeypatch.chdir(tmp_path)

    # Create Settings instance (it will read the .env file)
    settings = Settings()

    assert settings.app_name == "From Env File"
    assert settings.debug is True
    assert settings.log_level == "ERROR"
    assert settings.api_key == "file-key-789"
