"""Tests for configuration loader."""

from pathlib import Path
from unittest.mock import patch

import pytest

from ai_org.utils.config_loader import create_example_user_config, load_config_value


@pytest.mark.unit
class TestLoadConfigValue:
    def test_env_takes_precedence(self, monkeypatch):
        monkeypatch.setenv("TEST_KEY", "from_env")
        assert load_config_value("TEST_KEY") == "from_env"

    def test_returns_default(self, monkeypatch):
        monkeypatch.delenv("MISSING_KEY", raising=False)
        assert load_config_value("MISSING_KEY", "fallback") == "fallback"

    def test_returns_none_when_nothing_set(self, monkeypatch):
        monkeypatch.delenv("MISSING_KEY", raising=False)
        assert load_config_value("MISSING_KEY") is None

    def test_reads_user_config_file(self, monkeypatch, tmp_path):
        monkeypatch.delenv("MY_VAR", raising=False)
        config_dir = tmp_path / ".augint"
        config_dir.mkdir()
        config_file = config_dir / ".env.augint-org"
        config_file.write_text("MY_VAR=from_file\n")

        with patch.object(Path, "home", return_value=tmp_path):
            result = load_config_value("MY_VAR")

        assert result == "from_file"

    def test_env_overrides_user_config(self, monkeypatch, tmp_path):
        monkeypatch.setenv("MY_VAR", "from_env")
        config_dir = tmp_path / ".augint"
        config_dir.mkdir()
        config_file = config_dir / ".env.augint-org"
        config_file.write_text("MY_VAR=from_file\n")

        result = load_config_value("MY_VAR")
        assert result == "from_env"


@pytest.mark.unit
class TestCreateExampleUserConfig:
    def test_creates_example_file(self, tmp_path):
        with patch.object(Path, "home", return_value=tmp_path):
            create_example_user_config()

        example_file = tmp_path / ".augint" / ".env.augint-org.example"
        assert example_file.exists()
        content = example_file.read_text()
        assert "GH_ACCOUNT" in content

    def test_does_not_overwrite_existing(self, tmp_path):
        config_dir = tmp_path / ".augint"
        config_dir.mkdir()
        example_file = config_dir / ".env.augint-org.example"
        example_file.write_text("ORIGINAL")

        with patch.object(Path, "home", return_value=tmp_path):
            create_example_user_config()

        assert example_file.read_text() == "ORIGINAL"
