"""Tests for configuration management."""

import pytest

from bilgeai.core.config import BilgeConfig
from bilgeai.core.constants import SCHEMA_VERSION
from bilgeai.core.exceptions import ConfigError


class TestBilgeConfig:
    def test_default_creation(self):
        config = BilgeConfig()
        assert config.schema_version == SCHEMA_VERSION
        assert config.model.name == "meta-llama/Llama-3-8B"
        assert config.privacy.scan_pii is True

    def test_load_from_yaml_legacy_migrates(self, sample_config_yaml):
        """Loading a legacy config should auto-migrate to v0.1.0."""
        config = BilgeConfig.load(sample_config_yaml)
        assert config.model.name == "meta-llama/Llama-3-8B"
        assert config.llm.provider == "anthropic"
        assert config.schema_version == SCHEMA_VERSION

    def test_load_nonexistent(self, tmp_path):
        with pytest.raises(ConfigError) as exc_info:
            BilgeConfig.load(tmp_path / "nonexistent.yaml")
        assert "bilge init" in exc_info.value.suggestion

    def test_save_and_load(self, tmp_path):
        config = BilgeConfig(model={"name": "test-model"})
        save_path = tmp_path / "bilge.yaml"
        config.save(save_path)

        loaded = BilgeConfig.load(save_path)
        assert loaded.model.name == "test-model"

    def test_get_overrides_empty(self):
        config = BilgeConfig()
        assert config.get_overrides() == {}

    def test_get_overrides_partial(self):
        config = BilgeConfig(training={"batch_size": 8})
        overrides = config.get_overrides()
        assert overrides == {"batch_size": 8}

    def test_provider_config(self):
        config = BilgeConfig(
            llm={
                "provider": "openai",
                "model": "gpt-4o",
                "api_key_env": "OPENAI_API_KEY",
            }
        )
        assert config.llm.provider == "openai"
        assert config.llm.model == "gpt-4o"

    def test_local_provider_config(self):
        config = BilgeConfig(
            llm={
                "provider": "local",
                "model": "llama3.1",
                "api_key_env": "",
                "base_url": "http://localhost:11434/v1",
            }
        )
        assert config.llm.provider == "local"
        assert config.llm.base_url == "http://localhost:11434/v1"

    def test_load_v2_config(self, sample_config_yaml_v2):
        """Loading a v0.1.0 config should work directly without migration."""
        config = BilgeConfig.load(sample_config_yaml_v2)
        assert config.model.name == "meta-llama/Llama-3-8B"
        assert config.llm.provider == "anthropic"
        assert config.llm.model == "claude-sonnet-4-20250514"
        assert config.schema_version == SCHEMA_VERSION
