from __future__ import annotations

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

from src.bootstrap_config import apply_initial_env_from_config


class BootstrapConfigTests(unittest.TestCase):
    def test_apply_initial_env_from_config_sets_missing_env_keys(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            cfg_path = Path(tmp) / "Config.yaml"
            cfg_path.write_text(
                """
auth:
  allow_signup: false
agent:
  tool:
    preset: readonly-safe
settings:
  defaults:
    mode: evaluation
""".strip(),
                encoding="utf-8",
            )
            with patch.dict(
                os.environ,
                {
                    "AGENT_CONFIG_YAML_PATH": str(cfg_path),
                    "AGENT_AUTH_ALLOW_SIGNUP": "",
                    "AGENT_LANGFUSE_TOOL_PRESET": "",
                    "AGENT_DEFAULT_MODE": "",
                },
                clear=False,
            ):
                result = apply_initial_env_from_config(force=True)
                self.assertTrue(result["loaded"])
                self.assertEqual(os.getenv("AGENT_AUTH_ALLOW_SIGNUP"), "false")
                self.assertEqual(os.getenv("AGENT_LANGFUSE_TOOL_PRESET"), "readonly-safe")
                self.assertEqual(os.getenv("AGENT_DEFAULT_MODE"), "evaluation")

    def test_env_value_has_priority_over_config(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            cfg_path = Path(tmp) / "Config.yaml"
            cfg_path.write_text(
                """
settings:
  defaults:
    mode: overview
""".strip(),
                encoding="utf-8",
            )
            with patch.dict(
                os.environ,
                {
                    "AGENT_CONFIG_YAML_PATH": str(cfg_path),
                    "AGENT_DEFAULT_MODE": "prompt",
                },
                clear=False,
            ):
                _ = apply_initial_env_from_config(force=True, override_existing=False)
                self.assertEqual(os.getenv("AGENT_DEFAULT_MODE"), "prompt")


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