"""Pydantic models for TUI screen data types.

This module contains view models used by screens to represent
data in a structured, type-safe manner.
"""

from datetime import datetime
from typing import Any, Literal, cast

from pydantic import BaseModel, Field


def _tag_list_factory() -> list["TagView"]:
    return []


class TagView(BaseModel):
    """View model for a tag."""

    tag_path: str


class ExecutionMetadataView(BaseModel):
    """View model for execution metadata."""

    external_id: str | None = None
    provider_key: str = ""
    provider_model_name: str = ""


class ContentPartView(BaseModel):
    """View model for content parts in the Content browser.

    This provides a flattened, UI-friendly representation of
    ContentPartItemResponse for use in the ContentScreen.
    """

    id: str = Field(description="Content part UUID as string")
    message_role: Literal["user", "assistant"] = Field(
        description="Parent message role for the content part"
    )
    content_type_id: str = Field(description="Content type (text, code, json, etc.)")
    content_text: str | None = Field(
        default=None, description="Plain text content (null for structured/media types)"
    )
    content_structured: dict[str, Any] | None = Field(
        default=None, description="Structured JSON content (null for text types)"
    )
    tags: list[TagView] = Field(
        default_factory=_tag_list_factory,
        description="Associated tags",
    )
    execution_metadata: ExecutionMetadataView | None = Field(
        default=None, description="Execution metadata"
    )
    created_at: datetime | None = Field(default=None, description="Creation timestamp")
    updated_at: datetime | None = Field(
        default=None, description="Last update timestamp"
    )

    @property
    def external_id(self) -> str | None:
        """Get the external_id from execution metadata if available."""
        if self.execution_metadata:
            return self.execution_metadata.external_id
        return None

    @classmethod
    def from_response(cls, part: Any) -> "ContentPartView":
        """Create a ContentPartView from a ContentPartItemResponse.

        Args:
            part: A ContentPartItemResponse from the server client

        Returns:
            A ContentPartView instance
        """
        raw_tags = cast(list[Any], part.tags or [])
        tags: list[TagView] = []
        for tag in raw_tags:
            tags.append(TagView(tag_path=cast(str, tag.tag_path)))
        exec_meta = None
        if part.execution_metadata:
            exec_meta = ExecutionMetadataView(
                external_id=part.execution_metadata.external_id,
                provider_key=part.execution_metadata.provider_key,
                provider_model_name=part.execution_metadata.provider_model_name,
            )

        return cls(
            id=str(part.id),
            message_role=part.message_role,
            content_type_id=part.content_type_id,
            content_text=part.content_text,
            content_structured=part.content_structured,
            tags=tags,
            execution_metadata=exec_meta,
            created_at=part.created_at,
            updated_at=part.updated_at,
        )
