"""
Memory Buffer — store last N frames of key events for LLM context
Prevents context overflow; used in Observe -> Think -> Act loop
"""
from __future__ import annotations

from collections import deque
from dataclasses import dataclass
from typing import Any


@dataclass
class FrameEvent:
    t: float | int
    kind: str  # e.g. "world_state", "damage", "chat", "move"
    payload: dict[str, Any]


class MemoryBuffer:
    """Fixed-size deque of recent frame events for short-term memory."""

    def __init__(self, max_frames: int = 32):
        self._max_frames = max_frames
        self._events: deque[FrameEvent] = deque(maxlen=max_frames)

    def push(self, t: float | int, kind: str, payload: dict[str, Any]) -> None:
        self._events.append(FrameEvent(t=t, kind=kind, payload=payload))

    def recent_events(self, n: int | None = None) -> list[FrameEvent]:
        if n is None:
            return list(self._events)
        return list(self._events)[-n:]

    def summary_for_llm(self, last_n: int = 10) -> str:
        """Condensed text summary of last N events for prompt injection."""
        lines = []
        for ev in self.recent_events(last_n):
            lines.append(f"[t={ev.t}] {ev.kind}: {ev.payload}")
        return "\n".join(lines) if lines else "(no recent events)"

    def clear(self) -> None:
        self._events.clear()
