"""Conceptual CPLOM memory index. Synthetic data; not production CPLOM.

Python 3.10+, standard library only. Run: python memory_index.py
The in-memory tree models a persisted index; it is not a storage engine.
"""
from dataclasses import dataclass, field


@dataclass(frozen=True)
class Memory:
    id: str
    path: tuple[str, ...]
    tags: tuple[str, ...]
    summary: str
    body: str
    source: str
    observed_at: str
    confidence: float  # Illustrative source annotation, NOT a probability.
    contradicts: tuple[str, ...] = ()


@dataclass
class Node:
    name: str
    children: dict[str, "Node"] = field(default_factory=dict)
    objects: list[Memory] = field(default_factory=list)
    tags: set[str] = field(default_factory=set)

    def walk(self):
        """Iterative traversal avoids a recursion limit on index depth."""
        pending = [self]
        while pending:
            node = pending.pop()
            yield from node.objects
            pending.extend(reversed(list(node.children.values())))


def build_index(memories):
    root = Node("context-storage")
    seen = set()
    for item in memories:
        if item.id in seen:
            raise ValueError(f"Duplicate memory id: {item.id}")
        if not 0 <= item.confidence <= 1:
            raise ValueError("Confidence annotation must be in [0, 1]")
        seen.add(item.id)
        node = root
        node.tags.update(item.tags)
        for part in item.path:
            node = node.children.setdefault(part, Node(part))
            node.tags.update(item.tags)
        node.objects.append(item)
    return root


def sample_memories():
    return [
        Memory("launch-plan", ("projects", "atlas", "planning"),
               ("atlas", "launch", "schedule"), "Atlas launch plan",
               "Atlas launch is planned for September 30, conditional on security approval.",
               "synthetic:planning-note", "2026-09-01", 0.7),
        Memory("capacity-check", ("projects", "atlas", "operations"),
               ("atlas", "launch", "capacity"), "Atlas launch capacity check",
               "Capacity is available for the planned launch; this does not authorize release.",
               "synthetic:capacity-check", "2026-09-05", 0.8),
        Memory("security-review", ("assurance", "security"),
               ("security", "approval", "exception"), "Unresolved security approval",
               "Atlas security approval remains blocked by an unresolved access-control defect.",
               "synthetic:security-review", "2026-09-18", 0.9, ("launch-plan",)),
        Memory("release-rule", ("policies", "releases"),
               ("approval", "security", "policy"), "Release approval policy",
               "A planned date is not authorization. Unresolved security review blocks release.",
               "synthetic:release-policy", "2026-08-01", 0.95),
        Memory("unrelated", ("facilities",), ("office", "paint"),
               "Office paint schedule", "The office will be painted in October.",
               "synthetic:facilities-note", "2026-09-01", 0.8),
    ]


if __name__ == "__main__":
    for memory in build_index(sample_memories()).walk():
        print("/".join(memory.path), memory.id, memory.tags)
