"""Tests for MemoryStructureMiddleware."""

from __future__ import annotations

import asyncio
from pathlib import Path
from unittest.mock import MagicMock

from icarus.runtime.memory_context import MemoryStructureMiddleware
from langchain_core.messages import SystemMessage


class TestMemoryStructureMiddleware:
    def _make_request(self):
        request = MagicMock()
        request.system_message = SystemMessage(content="Base prompt.")
        captured = {}
        request.override = lambda **kw: captured.update(kw) or MagicMock()
        return request, captured

    def test_appends_memory_instructions_to_system_prompt(self):
        mw = MemoryStructureMiddleware(memory_dir=Path("/home/testuser/.icarus/memory"))
        request, captured = self._make_request()
        mw.wrap_model_call(request, MagicMock(return_value=MagicMock()))

        result = captured["system_message"]
        assert isinstance(result, SystemMessage)
        text = str(result.text)
        assert text.startswith("Base prompt.")
        assert "Persistent Memory" in text

    def test_interpolates_memory_dir_path(self):
        mw = MemoryStructureMiddleware(memory_dir=Path("/home/testuser/.icarus/memory"))
        assert "/home/testuser/.icarus/memory" in mw._section
        assert "{memory_dir}" not in mw._section

    def test_async_variant(self):
        mw = MemoryStructureMiddleware(memory_dir=Path("/home/testuser/.icarus/memory"))
        request, captured = self._make_request()

        async def handler(req):
            return MagicMock()

        asyncio.run(mw.awrap_model_call(request, handler))

        result = captured["system_message"]
        assert isinstance(result, SystemMessage)
        assert "Persistent Memory" in str(result.text)
