"""Thread state types for agent conversations."""

from datetime import UTC, datetime

from pydantic import BaseModel, Field

from core.common import JSONValue
from core.types.messages import ConversationMessage

# Keep JsonValue as an alias for backwards compatibility
JsonValue = JSONValue


class ThreadState(BaseModel):
    """Conversation state for an agent thread.

    This is runtime state - changes on every turn.
    """

    agent_id: str
    thread_id: str
    messages: list[ConversationMessage] = Field(default_factory=list)
    working_memory: dict[str, JSONValue] = Field(default_factory=dict)

    # Extensible metadata (for skills activation, etc.)
    metadata: dict[str, JSONValue] = Field(default_factory=dict)

    # Counters
    last_active: str | None = None
    turn_count: int = 0
    total_tokens_used: int = 0

    # Schema version
    schema_version: int = 1

    def add_message(self, role: str, content: str) -> None:
        """Add a message to the conversation."""
        self.messages.append(ConversationMessage(role=role, content=content))
        self.last_active = datetime.now(UTC).isoformat()


__all__ = [
    "JSONValue",
    "JsonValue",
    "ThreadState",
]
