"""Tests for reflection.py LLM calls — proper prompt/text split.

Verifies that all LLM calls pass data in the text parameter,
not embedded in the prompt. The prompt should be the instruction only.
"""
import pytest
from neo_cortex.llm import LLMClient


class CaptureLLM(LLMClient):
    """Captures all call arguments for verification."""

    def __init__(self, responses: list[str]):
        super().__init__()
        self._responses = list(responses)
        self.calls: list[dict] = []

    @property
    def name(self) -> str:
        return "mock/capture"

    async def call(self, prompt: str, text: str, max_tokens: int = 250, temperature: float = 0.1) -> str:
        self.calls.append({"prompt": prompt, "text": text, "max_tokens": max_tokens})
        return self._responses.pop(0) if self._responses else ""

    async def close(self) -> None:
        pass


class TestGenerateInsightFormat:
    @pytest.mark.asyncio
    async def test_evidence_passed_as_text(self):
        from neo_cortex.reflection import generate_insight
        llm = CaptureLLM(["INSIGHT: test insight\nEVIDENCE: id1"])
        evidence = [{"id": "id1", "summary": "some evidence about debugging"}]
        await generate_insight(llm, "How does X work?", evidence)
        assert llm.calls[0]["text"] != ""
        assert "some evidence about debugging" in llm.calls[0]["text"]
        assert "How does X work?" in llm.calls[0]["prompt"]


class TestVerifyTruthfulnessFormat:
    @pytest.mark.asyncio
    async def test_evidence_passed_as_text(self):
        from neo_cortex.reflection import verify_truthfulness
        llm = CaptureLLM(["SUPPORTED because reasons"])
        evidence = [{"id": "id1", "summary": "supporting fact"}]
        await verify_truthfulness(llm, "The agent does X", evidence)
        assert llm.calls[0]["text"] != ""
        assert "supporting fact" in llm.calls[0]["text"]
        assert "The agent does X" in llm.calls[0]["prompt"]


class TestIdentityReviewFormat:
    @pytest.mark.asyncio
    async def test_all_calls_have_nonempty_text(self):
        from neo_cortex.reflection import identity_review
        from unittest.mock import MagicMock

        mock_cortex = MagicMock()
        mock_cortex._index.get_metacognitive_memories.return_value = [
            {"id": f"meta_{i}", "summary": f"insight {i}",
             "energy": 0.9, "stability": 1.5, "concepts": "self-reflection"}
            for i in range(5)
        ]

        llm = CaptureLLM([
            "SECTION: §AUTONOMY\nPROPOSAL: test\nREASON: test",
            "COHERENT because test",
        ])

        await identity_review(mock_cortex, llm)

        for i, c in enumerate(llm.calls):
            assert c["text"] != "", f"Call #{i} has empty text. Prompt: {c['prompt'][:60]}..."
