"""Pattern: semantic memory as structured facts with history.

Free-text memories pile up contradictions ("lives in Berlin", later "moved to
Lisbon"). Storing facts as (subject, key) -> value lets a new value supersede
the old one while keeping history for audit and undo.
"""
from __future__ import annotations

import json
import time
from dataclasses import dataclass, asdict
from pathlib import Path


@dataclass
class Fact:
    subject: str
    key: str
    value: str
    updated_at: float
    source: str | None = None
    confidence: float = 1.0


class FactStore:
    def __init__(self, path: str | Path | None = None, clock=time.time):
        self.path = Path(path) if path else None
        self.clock = clock
        self.current: dict[tuple[str, str], Fact] = {}
        self.history: list[Fact] = []
        if self.path and self.path.exists():
            self._load()

    def set(self, subject: str, key: str, value: str, *, source: str | None = None,
            confidence: float = 1.0, min_confidence_to_override: float = 0.0) -> bool:
        """Set a fact. Returns False if an existing, more confident fact was kept."""
        k = (subject.strip().lower(), key.strip().lower())
        old = self.current.get(k)
        if old and old.value == value:
            return True
        if old and confidence < old.confidence and confidence < min_confidence_to_override:
            return False
        fact = Fact(k[0], k[1], value, self.clock(), source, confidence)
        if old:
            self.history.append(old)
        self.current[k] = fact
        self._save()
        return True

    def get(self, subject: str, key: str) -> str | None:
        fact = self.current.get((subject.strip().lower(), key.strip().lower()))
        return fact.value if fact else None

    def delete(self, subject: str, key: str) -> bool:
        removed = self.current.pop((subject.strip().lower(), key.strip().lower()), None)
        if removed:
            self.history.append(removed)
            self._save()
        return removed is not None

    def previous_values(self, subject: str, key: str) -> list[str]:
        k = (subject.strip().lower(), key.strip().lower())
        return [f.value for f in self.history if (f.subject, f.key) == k]

    def items(self, subject: str) -> list[str]:
        """One subject's facts as 'key: value' strings, sorted by key."""
        s = subject.strip().lower()
        return [f"{f.key}: {f.value}" for (subj, _), f in sorted(self.current.items()) if subj == s]

    def as_prompt(self, subject: str) -> str:
        """Render one subject's facts as a Markdown bullet list for a system prompt."""
        return "\n".join(f"- {line}" for line in self.items(subject))

    def _save(self) -> None:
        if not self.path:
            return
        data = {"current": [asdict(f) for f in self.current.values()], "history": [asdict(f) for f in self.history]}
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
        tmp.replace(self.path)  # atomic on POSIX and Windows

    def _load(self) -> None:
        data = json.loads(self.path.read_text(encoding="utf-8"))
        for d in data.get("current", []):
            f = Fact(**d)
            self.current[(f.subject, f.key)] = f
        self.history = [Fact(**d) for d in data.get("history", [])]
