"""Tests for the settings module."""

from __future__ import annotations

from pathlib import Path

from agent_scout.config.settings import (
    CustomEndpointSettings,
    Settings,
    load_settings,
    save_settings,
)


def test_default_settings():
    s = Settings()
    assert "claude" in s.llm.default_model.lower() or "anthropic" in s.llm.default_model.lower()
    assert s.budget.task_limit == 1.0
    assert s.budget.daily_limit == 10.0
    assert s.autonomy == "full"
    assert "web_search" in s.plugins


def test_save_and_load(tmp_path: Path):
    config_path = tmp_path / "config.toml"

    s = Settings()
    s.llm.default_model = "openai/gpt-4o"
    s.budget.task_limit = 2.5
    s.search.tavily_api_key = "tvly-test-key"
    s.personality = "concise"
    s.custom_endpoints = [
        CustomEndpointSettings(
            name="myapi",
            base_url="https://api.example.com/v1",
            api_key="sk-test",
            model_name="my-model",
        ),
    ]

    save_settings(s, config_path)
    assert config_path.exists()

    loaded = load_settings(config_path)
    assert loaded.llm.default_model == "openai/gpt-4o"
    assert loaded.budget.task_limit == 2.5
    assert loaded.search.tavily_api_key == "tvly-test-key"
    assert loaded.personality == "concise"
    assert len(loaded.custom_endpoints) == 1
    assert loaded.custom_endpoints[0].name == "myapi"


def test_load_nonexistent_returns_defaults():
    s = load_settings(Path("/nonexistent/path/config.toml"))
    assert s.llm.default_model == Settings().llm.default_model


def test_save_creates_directories(tmp_path: Path):
    config_path = tmp_path / "subdir" / "deep" / "config.toml"
    save_settings(Settings(), config_path)
    assert config_path.exists()


def test_settings_plugins_default():
    s = Settings()
    assert isinstance(s.plugins, list)
    assert len(s.plugins) >= 3


def test_budget_settings():
    s = Settings()
    assert s.budget.enforce is True
    assert s.budget.monthly_limit == 50.0


def test_custom_endpoint_round_trip(tmp_path: Path):
    config_path = tmp_path / "config.toml"

    s = Settings()
    s.custom_endpoints = [
        CustomEndpointSettings(name="a", base_url="http://a.com", api_key="k1", model_name="m1"),
        CustomEndpointSettings(name="b", base_url="http://b.com", api_key="k2", model_name="m2"),
    ]

    save_settings(s, config_path)
    loaded = load_settings(config_path)

    assert len(loaded.custom_endpoints) == 2
    assert loaded.custom_endpoints[0].name == "a"
    assert loaded.custom_endpoints[1].name == "b"
    assert loaded.custom_endpoints[1].api_key == "k2"
