"""Tests for config interpolation/validation and workspace reliability."""

from __future__ import annotations

import os
import tempfile
import unittest

from kiessclaw.core.config import resolve_env_vars, validate_runtime_requirements
from kiessclaw.core.memory import MemoryEngine


class ConfigAndWorkspaceTest(unittest.TestCase):
    """Verify runtime config and workspace file guarantees."""

    def test_nested_env_interpolation(self) -> None:
        """Nested config values should interpolate `${VAR}` recursively."""
        os.environ["KIESS_TEST_SMTP"] = "smtp.mail.local"
        os.environ["KIESS_TEST_API"] = "secret-key"

        raw = {
            "email": {"smtp": {"host": "${KIESS_TEST_SMTP}"}},
            "llm": {"api_key": "${KIESS_TEST_API}"},
            "crm": {"hubspot": {"api_key": "${MISSING_OPTIONAL}"}, "provider": "none"},
        }
        resolved = resolve_env_vars(raw).config
        self.assertEqual("smtp.mail.local", resolved["email"]["smtp"]["host"])
        self.assertEqual("secret-key", resolved["llm"]["api_key"])

    def test_validation_fails_when_required_values_missing(self) -> None:
        """Config validator should fail loudly when active providers are misconfigured."""
        with self.assertRaises(RuntimeError):
            validate_runtime_requirements(
                {
                    "llm": {"provider": "openai", "api_key": ""},
                    "email": {"provider": "smtp", "smtp": {"host": ""}},
                    "crm": {"provider": "none"},
                },
                set(),
            )

    def test_workspace_missing_collections_auto_created(self) -> None:
        """Memory engine should create required collections when absent."""
        with tempfile.TemporaryDirectory() as tempdir:
            memory = MemoryEngine(tempdir)
            # Delete a required collection and ensure it is recreated lazily.
            enrollments_path = memory.data_dir / "enrollments.json"
            if enrollments_path.exists():
                enrollments_path.unlink()

            data = memory.load_data("enrollments")
            self.assertEqual([], data)
            self.assertTrue(enrollments_path.exists())


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