"""MBConsolidator — extracts recurring patterns from cortex, appends to Memory Bank files."""

import os
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from neo_cortex.classifier import GroqClassifier
    from neo_cortex.memory_index import MemoryIndex


class MBConsolidator:
    """Finds recurring high-energy patterns in cortex and consolidates them to Memory Bank."""

    def __init__(
        self,
        index: 'MemoryIndex',
        classifier: 'GroqClassifier',
        mb_path: str,
    ):
        self._index = index
        self._classifier = classifier
        self._mb_path = mb_path

    def find_recurring_patterns(
        self, min_count: int = 3, min_energy: float = 0.5
    ) -> list[dict]:
        """Find concepts appearing in min_count+ memories with avg energy >= min_energy."""
        all_concepts = self._index.get_all_concepts()
        patterns = []
        for concept, count in all_concepts.items():
            if count < min_count:
                continue
            memories = self._index.search_by_concept(concept, n=count)
            if not memories:
                continue
            avg_energy = sum(m.energy for m in memories) / len(memories)
            if avg_energy < min_energy:
                continue
            patterns.append({
                "concept": concept,
                "count": count,
                "avg_energy": avg_energy,
                "memory_ids": [m.id for m in memories],
            })
        return patterns

    async def generate_mb_entry(self, pattern: dict) -> str:
        """Use classifier to synthesize a pattern into an MB entry."""
        # Collect summaries from source memories
        records = self._index.get_by_ids(pattern["memory_ids"][:5])
        summaries = []
        for r in records:
            sf = self._index.get_structured(r.id)
            if sf and sf.summary:
                summaries.append(sf.summary)

        context = f"Concept: {pattern['concept']}\nAppears in {pattern['count']} memories.\n"
        context += "Summaries:\n" + "\n".join(f"- {s}" for s in summaries)

        return await self._classifier.summarize_pattern(context)

    async def classify_mb_target(self, pattern: dict) -> str:
        """Classify which MB file a pattern should go to."""
        return await self._classifier.classify_mb_target(pattern["concept"])

    def append_to_mb(self, file_path: str, content: str) -> None:
        """Append content to a MB file. Idempotent — won't add duplicate content."""
        path = Path(file_path)
        path.parent.mkdir(parents=True, exist_ok=True)

        existing = ""
        if path.exists():
            existing = path.read_text(encoding="utf-8")

        # Idempotency: check if content already present
        if content.strip() in existing:
            return

        with open(path, "a", encoding="utf-8") as f:
            if existing and not existing.endswith("\n"):
                f.write("\n")
            f.write("\n" + content + "\n")
