from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from memnixa.config import AppConfig
from memnixa.context import CORE_SAFETY_RULES, ContextBuilder
from memnixa.gateway.messages import InboundMessageContext


class ContextBuilderTests(unittest.TestCase):
    def _make_builder(
        self,
        workspace: Path,
        *,
        system_prompt: str | None = None,
    ) -> ContextBuilder:
        config = AppConfig(
            workspace=workspace,
            database_path=workspace / ".memnixa/memnixa.db",
            system_prompt=system_prompt,
        )
        return ContextBuilder(config)

    def test_default_system_prompt_starts_with_core_safety_rules(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            workspace = Path(temp_dir)
            builder = self._make_builder(workspace)
            prompt = builder._build_system_prompt(
                inbound=InboundMessageContext(
                    session_id="main",
                    raw_body="hello",
                    body_for_agent="hello",
                ),
                tool_summaries=["list_dir: List files in a directory."],
                provider_summary="1 / Demo / demo-model",
            )

        self.assertTrue(prompt.startswith(CORE_SAFETY_RULES))
        self.assertIn("You are Memnixa, a practical coding agent.", prompt)
        self.assertIn("## Runtime Environment", prompt)

    def test_custom_system_prompt_is_kept_after_core_safety_rules(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            workspace = Path(temp_dir)
            builder = self._make_builder(
                workspace,
                system_prompt="Follow the owner's repository conventions exactly.",
            )
            prompt = builder._build_system_prompt(
                inbound=InboundMessageContext(
                    session_id="main",
                    raw_body="hello",
                    body_for_agent="hello",
                ),
                tool_summaries=[],
                provider_summary="1 / Demo / demo-model",
            )

        self.assertTrue(prompt.startswith(CORE_SAFETY_RULES))
        self.assertIn(
            "Follow the owner's repository conventions exactly.",
            prompt,
        )


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