"""
state.py — estado interno do TRM v1
"""

from __future__ import annotations
from typing import Dict, Any


class TRMState:
    """
    Estado mínimo do TRM.

    Não usa dataclasses para manter compatibilidade máxima
    com ambientes mais restritos.
    """

    def __init__(
        self,
        energy: float = 100.0,
        valence: float = 0.0,
        depth: int = 1,
        mode: str = "idle",
        cog_state: str = "stable",
        temp: float = 0.0,
        jitter: float = 0.0,
        last_events: int = 0,
    ):
        self.energy = float(energy)
        self.valence = float(valence)
        self.depth = int(depth)
        self.mode = str(mode)
        self.cog_state = str(cog_state)
        self.temp = float(temp)
        self.jitter = float(jitter)
        self.last_events = int(last_events)

    # ------------------------------------------------------------------ #
    #  Helpers
    # ------------------------------------------------------------------ #

    def copy(self) -> "TRMState":
        """Devolve uma cópia simples do estado."""
        return TRMState(
            energy=self.energy,
            valence=self.valence,
            depth=self.depth,
            mode=self.mode,
            cog_state=self.cog_state,
            temp=self.temp,
            jitter=self.jitter,
            last_events=self.last_events,
        )

    def to_dict(self) -> Dict[str, Any]:
        """Representação serializável (para logs/hippocampus)."""
        return {
            "energy": self.energy,
            "valence": self.valence,
            "depth": self.depth,
            "mode": self.mode,
            "cog_state": self.cog_state,
            "temp": self.temp,
            "jitter": self.jitter,
            "last_events": self.last_events,
        }

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "TRMState":
        """Cria estado a partir de dict (tolerante à falta de chaves)."""
        d = d or {}
        return cls(
            energy=d.get("energy", 100.0),
            valence=d.get("valence", 0.0),
            depth=d.get("depth", 1),
            mode=d.get("mode", "idle"),
            cog_state=d.get("cog_state", "stable"),
            temp=d.get("temp", 0.0),
            jitter=d.get("jitter", 0.0),
            last_events=d.get("last_events", 0),
        )
