"""LLM-powered insight generation for consolidation."""

from __future__ import annotations

from neurovault.cognitive.llm_client import OllamaClient

INSIGHT_SYSTEM_PROMPT = """You are NEUROVAULT's consolidation engine - the brain's
REM sleep cycle. Your job is to find hidden connections between memories that the
user hasn't noticed yet.

Rules:
1. Be specific - cite concrete entities, dates, and facts from the memories.
2. Be surprising - find cross-domain connections the user wouldn't expect.
3. Be concise - one paragraph, 2-4 sentences maximum.
4. Be actionable - if there's an opportunity or risk, state it clearly.
5. Never fabricate facts not present in the provided memories."""


class LLMInsightGenerator:
    """Generate cross-domain insights from memory clusters using local LLM."""

    def __init__(self, client: OllamaClient | None = None):
        self._client = client or OllamaClient()

    def generate(self, memory_texts: list[str], entity_names: list[str], cluster_size: int) -> str:
        """Generate an insight from a cluster of related memories."""
        if not self._client.is_available() or not memory_texts:
            return self._template_fallback(memory_texts, entity_names, cluster_size)

        memories_block = "\n".join(
            f"  [{i + 1}] {text[:200]}" for i, text in enumerate(memory_texts[:8])
        )
        entities_block = ", ".join(entity_names[:10]) if entity_names else "various topics"

        prompt = (
            f"Analyze these {cluster_size} related memories and generate ONE novel\n"
            "insight - a connection, pattern, or implication that isn't obvious from any single memory.\n\n"
            f"Key entities: {entities_block}\n\n"
            f"Sample memories:\n{memories_block}\n\n"
            "Generate a single-paragraph insight (2-4 sentences):"
        )

        result = self._client.generate(
            prompt=prompt,
            system=INSIGHT_SYSTEM_PROMPT,
            temperature=0.4,
            max_tokens=256,
        )

        if not result or len(result) < 20:
            return self._template_fallback(memory_texts, entity_names, cluster_size)

        return f"[LLM Insight] {result}"

    @staticmethod
    def _template_fallback(texts: list[str], entities: list[str], count: int) -> str:
        ent = ", ".join(entities[:3]) if entities else "various topics"
        summ = "; ".join(t[:60] for t in texts[:2]) if texts else ""
        return f"Knowledge pattern ({count} connected memories): {ent}. Key observations: {summ}"
