from __future__ import annotations

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

from arr_mcp.launch import (
    KEYCHAIN_SERVICES,
    _private_route_values,
    load_runtime_environment,
)


class McpLaunchTests(unittest.TestCase):
    def test_route_loader_reads_only_allowlisted_values_from_0600_file(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            path = Path(temporary) / "runtime.env"
            path.write_text(
                "\n".join(
                    [
                        "ARR_OSS_REGION=cn-guangzhou",
                        "ARR_OSS_BUCKET=synthetic-bucket",
                        "ARR_OSS_ENDPOINT=https://oss.example.test",
                        "DEERFLOW_API_KEY=must-not-be-loaded",
                    ]
                ),
                encoding="utf-8",
            )
            path.chmod(0o600)
            values = _private_route_values(path)
        self.assertEqual(
            set(values),
            {"ARR_OSS_REGION", "ARR_OSS_BUCKET", "ARR_OSS_ENDPOINT"},
        )
        self.assertNotIn("DEERFLOW_API_KEY", values)

    def test_environment_loader_maps_keychain_items_without_logging_values(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            path = Path(temporary) / "runtime.env"
            path.write_text(
                "ARR_OSS_REGION=cn-guangzhou\nARR_OSS_BUCKET=synthetic-bucket\n",
                encoding="utf-8",
            )
            path.chmod(0o600)
            with patch("arr_mcp.launch._keychain_secret", return_value="S" * 48):
                with patch.dict(os.environ, {}, clear=True):
                    load_runtime_environment(path)
                    self.assertEqual(os.environ["ARR_OSS_REGION"], "cn-guangzhou")
                    for environment_name in KEYCHAIN_SERVICES:
                        self.assertEqual(os.environ[environment_name], "S" * 48)


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