"""Pydantic models for unified session and message representation."""

from datetime import datetime
from typing import Any

from pydantic import BaseModel, ConfigDict, Field


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

    model_config = ConfigDict(frozen=False)

    tool: str
    session_id: str
    node_id: str
    parent_node_id: str | None
    message_id: str
    role: str
    content: str
    created_at: datetime
    metadata: dict[str, Any] = Field(default_factory=dict)


class SessionExport(BaseModel):
    """A full session export containing all messages."""

    model_config = ConfigDict(frozen=False)

    tool: str
    session_id: str
    title: str
    working_directory: str
    created_at: datetime | None = None
    last_activity_at: datetime | None = None
    model: str | None = None
    messages: list[SessionMessage]
    metadata: dict[str, Any] = Field(default_factory=dict)

    @property
    def assistant_texts(self) -> list[SessionMessage]:
        """Return deduplicated assistant messages with >50 chars of content.

        Filters messages where role == "assistant", deduplicates by content,
        and excludes messages with len(content) <= 50.
        """
        seen: set[str] = set()
        result: list[SessionMessage] = []
        for msg in self.messages:
            if msg.role != "assistant":
                continue
            if len(msg.content) <= 50:
                continue
            if msg.content in seen:
                continue
            seen.add(msg.content)
            result.append(msg)
        return result


class SessionInfo(BaseModel):
    """Lightweight metadata for listing sessions without loading full content."""

    model_config = ConfigDict(frozen=False)

    tool: str
    session_id: str
    title: str
    message_count: int
    last_activity: datetime
    working_directory: str
