"""Session management — tracks user interaction state across the network."""

from __future__ import annotations

import uuid
from datetime import UTC, datetime

from pydantic import BaseModel, Field


class SessionMessage(BaseModel):
    """A single message in a session."""

    role: str  # "user" or agent_id
    content: str
    timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
    metadata: dict = Field(default_factory=dict)


class Session(BaseModel):
    """A user interaction session with the Vastian Network."""

    id: str = Field(default_factory=lambda: uuid.uuid4().hex[:12])
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    messages: list[SessionMessage] = Field(default_factory=list)
    active_agent: str | None = None
    context: dict = Field(default_factory=dict)

    def add_message(self, role: str, content: str, **metadata: object) -> None:
        """Add a message to the session history."""
        self.messages.append(
            SessionMessage(
                role=role,
                content=content,
                metadata=metadata,
            )
        )

    def get_history(self, limit: int = 20) -> list[dict[str, str]]:
        """Get recent conversation history in LLM-compatible format."""
        recent = self.messages[-limit:]
        return [
            {
                "role": "user" if m.role == "user" else "assistant",
                "content": f"[{m.role}] {m.content}" if m.role != "user" else m.content,
            }
            for m in recent
        ]

    @property
    def message_count(self) -> int:
        return len(self.messages)


class SessionManager:
    """Manages active and historical sessions."""

    def __init__(self) -> None:
        self._sessions: dict[str, Session] = {}
        self._current_session_id: str | None = None

    def create_session(self) -> Session:
        """Create a new session."""
        session = Session()
        self._sessions[session.id] = session
        self._current_session_id = session.id
        return session

    def get_current(self) -> Session:
        """Get or create the current session."""
        if self._current_session_id and self._current_session_id in self._sessions:
            return self._sessions[self._current_session_id]
        return self.create_session()

    def get_session(self, session_id: str) -> Session | None:
        """Get a specific session by ID."""
        return self._sessions.get(session_id)

    def list_sessions(self) -> list[dict]:
        """List all sessions with basic info."""
        return [
            {
                "id": s.id,
                "created_at": s.created_at.isoformat(),
                "message_count": s.message_count,
                "active_agent": s.active_agent,
            }
            for s in self._sessions.values()
        ]
