"""Tests for configuration loading."""

import os
import tempfile

import pytest

from backend.config import load_config


class TestConfig:
    def test_load_missing_file(self):
        config = load_config("/nonexistent/config.yaml")
        assert config.server.port == 8000
        assert config.routing.default_strategy == "auto"

    def test_load_valid_config(self, tmp_path):
        cfg = tmp_path / "config.yaml"
        cfg.write_text("""
server:
  port: 9000
routing:
  default_strategy: best
  cost_weight: 0.5
providers:
  - id: test
    type: openai
    base_url: http://localhost:8080
    models:
      - id: test-model
        input_cost_per_mtok: 1.0
        output_cost_per_mtok: 2.0
        max_context: 4096
""")
        config = load_config(str(cfg))
        assert config.server.port == 9000
        assert config.routing.default_strategy == "best"
        assert config.routing.cost_weight == 0.5
        assert len(config.providers) == 1
        assert config.providers[0].models[0].id == "test-model"

    def test_env_interpolation(self, tmp_path):
        os.environ["TEST_ECATE_KEY"] = "sk-secret"
        cfg = tmp_path / "config.yaml"
        cfg.write_text("""
providers:
  - id: test
    type: openai
    base_url: http://localhost
    api_key: ${TEST_ECATE_KEY}
    models: []
""")
        config = load_config(str(cfg))
        assert config.providers[0].api_key == "sk-secret"
        del os.environ["TEST_ECATE_KEY"]

    def test_get_model(self, tmp_path):
        cfg = tmp_path / "config.yaml"
        cfg.write_text("""
providers:
  - id: openai
    type: openai
    base_url: http://localhost
    models:
      - id: gpt-4o
        input_cost_per_mtok: 2.5
        output_cost_per_mtok: 10.0
""")
        config = load_config(str(cfg))

        # By provider/model
        result = config.get_model("openai/gpt-4o")
        assert result is not None
        assert result[1].id == "gpt-4o"

        # By model name only
        result = config.get_model("gpt-4o")
        assert result is not None

        # Unknown
        assert config.get_model("nonexistent") is None

    def test_all_models(self, tmp_path):
        cfg = tmp_path / "config.yaml"
        cfg.write_text("""
providers:
  - id: a
    type: openai
    base_url: http://localhost
    models:
      - id: m1
      - id: m2
  - id: b
    type: openai
    base_url: http://localhost
    models:
      - id: m3
""")
        config = load_config(str(cfg))
        assert len(config.all_models()) == 3
