from pathlib import Path
from datetime import datetime

try:
    import orjson as json
except Exception:
    import json  # type: ignore

class Hippocampus:
    """
    Memória contextual simples (JSON Lines): append-only.
    Guarda perceções, decisões e ações para replays futuros.
    """

    def __init__(self, log_dir: Path):
        self.log_dir = log_dir
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.events_file = self.log_dir / "events.jsonl"

    def remember(self, kind: str, data: dict) -> None:
        rec = {
            "ts": datetime.utcnow().isoformat() + "Z",
            "kind": kind,
            "data": data,
        }

        try:
            # Compatível com orjson e stdlib json
            blob = json.dumps(rec)
            if isinstance(blob, str):
                blob = blob.encode("utf-8")

            with self.events_file.open("ab") as f:
                f.write(blob)
                f.write(b"\n")
        except Exception:
            # Evitar crash em early boot ou IO quebrado
            pass

