from pathlib import Path
from datetime import datetime

try:
    import orjson as json
except Exception:  # fallback leve
    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.events_file = log_dir / "events.jsonl"

    def remember(self, kind: str, data: dict) -> None:
        rec = {
            "ts": datetime.utcnow().isoformat() + "Z",
            "kind": kind,
            "data": data,
        }
        try:
            if "orjson" in json.__name__:
                blob = json.dumps(rec)
            else:
                blob = json.dumps(rec)  # type: ignore
            with self.events_file.open("ab") as f:
                f.write(blob if isinstance(blob, bytes) else blob.encode("utf-8"))
                f.write(b"\n")
        except Exception:
            # evitar crash por IO em early boot
            pass
