from __future__ import annotations

import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

from src import env_settings


class EnvSettingsTests(unittest.TestCase):
    def test_load_env_candidates_project_overrides_home(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            home_env = Path(tmp) / "home.env"
            project_env = Path(tmp) / "project.env"
            home_env.write_text("OPENAI_API_KEY=home-key\n", encoding="utf-8")
            project_env.write_text("OPENAI_API_KEY=project-key\n", encoding="utf-8")

            with patch.object(env_settings, "HOME_ENV_PATH", home_env), patch.object(
                env_settings, "PROJECT_ENV_PATH", project_env
            ):
                env_settings._ENV_BOOTSTRAPPED = False
                with patch.dict(os.environ, {}, clear=False):
                    env_settings.load_env_candidates()
                    self.assertEqual(os.getenv("OPENAI_API_KEY"), "project-key")

    def test_save_env_values_writes_target_file(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            project_env = Path(tmp) / "project.env"
            with patch.object(env_settings, "PROJECT_ENV_PATH", project_env):
                env_settings._ENV_BOOTSTRAPPED = False
                saved = env_settings.save_env_values({"OPENAI_API_KEY": "abc"}, target="project")
                self.assertEqual(saved["target"], "project")
                self.assertIn("OPENAI_API_KEY", saved["updated_keys"])
                self.assertIn("OPENAI_API_KEY=abc", project_env.read_text(encoding="utf-8"))


if __name__ == "__main__":
    unittest.main()
