from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone

from app.core.api.domain.models.agent_session_message import AgentSessionMessage


@dataclass(slots=True)
class AgentSession:
    session_id: str
    active_rag_session_id: str | None
    created_at: datetime
    updated_at: datetime
    messages: list[AgentSessionMessage] = field(default_factory=list)

    @classmethod
    def create(cls, session_id: str, rag_session_id: str | None = None) -> "AgentSession":
        now = datetime.now(timezone.utc)
        return cls(
            session_id=session_id,
            active_rag_session_id=rag_session_id,
            created_at=now,
            updated_at=now,
        )

    def append_turn(self, user_message: str, assistant_message: str, route_result=None) -> None:
        self._append_message("user", user_message)
        self._append_message("assistant", assistant_message)
        self.updated_at = datetime.now(timezone.utc)

    def _append_message(self, role: str, text: str) -> None:
        value = text.strip()
        if value:
            self.messages.append(AgentSessionMessage.create(role, value))
