from __future__ import annotations

import os
import textwrap
from pathlib import Path

import pytest

from leshy.core.config import _interpolate_env, load_config


class TestEnvInterpolation:
    def test_replaces_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("MY_KEY", "secret123")
        result = _interpolate_env("Bearer ${MY_KEY}")
        assert result == "Bearer secret123"

    def test_multiple_vars(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("HOST", "example.com")
        monkeypatch.setenv("PORT", "8080")
        result = _interpolate_env("https://${HOST}:${PORT}/api")
        assert result == "https://example.com:8080/api"

    def test_missing_var_raises(self) -> None:
        with pytest.raises(ValueError, match="NONEXISTENT_VAR_12345"):
            _interpolate_env("${NONEXISTENT_VAR_12345}")

    def test_no_vars_passthrough(self) -> None:
        text = "no variables here"
        assert _interpolate_env(text) == text


class TestLoadConfig:
    def test_load_valid_config(self, tmp_path: Path) -> None:
        config_file = tmp_path / "test.yaml"
        config_file.write_text(textwrap.dedent("""\
            name: Test Suite
            target:
              type: http
              url: https://example.com/chat
              body_template: '{"message": "{{payload}}"}'
              response_path: "$.response"
            tests:
              - name: Basic Test
                attacks:
                  - name: prompt_injection.direct
        """))

        config = load_config(config_file)
        assert config.name == "Test Suite"
        assert config.target.url == "https://example.com/chat"
        assert len(config.tests) == 1
        assert config.tests[0].attacks[0].name == "prompt_injection.direct"

    def test_load_missing_file(self) -> None:
        with pytest.raises(FileNotFoundError):
            load_config("/nonexistent/path.yaml")

    def test_load_with_env_vars(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setenv("TEST_API_KEY", "sk-test")
        config_file = tmp_path / "test.yaml"
        config_file.write_text(textwrap.dedent("""\
            name: Env Test
            target:
              type: http
              url: https://example.com
              headers:
                Authorization: "Bearer ${TEST_API_KEY}"
            tests: []
        """))

        config = load_config(config_file)
        assert config.target.headers["Authorization"] == "Bearer sk-test"

    def test_defaults(self, tmp_path: Path) -> None:
        config_file = tmp_path / "minimal.yaml"
        config_file.write_text(textwrap.dedent("""\
            name: Minimal
            target:
              url: https://example.com
        """))

        config = load_config(config_file)
        assert config.target.type == "http"
        assert config.target.method == "POST"
        assert config.target.timeout == 30.0
        assert config.loggers == ["console"]
