"""Pattern: consolidation (merge near-duplicates).

Agents that write memories freely produce many near-identical entries. A
periodic consolidation pass keeps the store small and retrieval sharp. This is
the deterministic part; an LLM pass can then rewrite each cluster into one
clean statement (see CONSOLIDATE_PROMPT).
"""
from __future__ import annotations

import re

CONSOLIDATE_PROMPT = """These memory entries may overlap or contradict each other:
{entries}

Rewrite them as the smallest set of accurate, self-contained statements.
If two entries contradict, keep the newer one and note the change only if it matters.
Return one statement per line."""

_WORD = re.compile(r"\w+")


def _tokens(text: str) -> set[str]:
    return set(_WORD.findall(text.lower()))


def jaccard(a: str, b: str) -> float:
    ta, tb = _tokens(a), _tokens(b)
    if not ta and not tb:
        return 1.0
    return len(ta & tb) / len(ta | tb)


def dedupe(items: list[str], threshold: float = 0.8) -> list[str]:
    """Keep the first of each group of items whose word-set Jaccard >= threshold.

    Later items win when they are longer (usually more specific). O(n^2), which is
    fine for a few thousand items; use MinHash or embeddings beyond that.
    """
    kept: list[str] = []
    for item in items:
        for i, existing in enumerate(kept):
            if jaccard(item, existing) >= threshold:
                if len(item) > len(existing):
                    kept[i] = item
                break
        else:
            kept.append(item)
    return kept
