"""Pydantic schemas for the AI Script Builder."""
from datetime import datetime
from typing import Literal, Optional
from uuid import UUID

from pydantic import BaseModel, Field


class ScriptBuilderCreateRequest(BaseModel):
    """Request to start (or get-or-create, for inline origin) a builder session.

    When `origin='pilot_inline'`, `ai_session_id` is REQUIRED and must
    reference a pilot session owned by the current user. The endpoint's
    get-or-create semantics kick in: if a pilot_inline session already
    exists for (user_id, ai_session_id), that row is returned instead of
    creating a duplicate.
    """
    language: str = Field(
        default="powershell",
        pattern=r"^(powershell|bash|python)$",
        description="Script language",
    )
    origin: Literal["standalone", "pilot_inline"] = "standalone"
    ai_session_id: UUID | None = None


class ScriptBuilderMessageRequest(BaseModel):
    """User message in a builder session."""
    content: str = Field(min_length=1, max_length=5000)


class ScriptBuilderMessageSchema(BaseModel):
    """A single message in a builder session."""
    id: UUID
    role: str
    content: str
    script: str | None = None
    script_filename: str | None = None
    line_count: int | None = None
    input_tokens: int | None = None
    output_tokens: int | None = None
    created_at: datetime

    model_config = {"from_attributes": True}


class ScriptBuilderMessageResponse(BaseModel):
    """AI response to a builder message."""
    role: str = "assistant"
    content: str
    script: str | None = None
    script_filename: str | None = None
    line_count: int | None = None
    timestamp: datetime

    model_config = {"from_attributes": True}


class ScriptBuilderSessionSummary(BaseModel):
    """Lightweight session for list views (no messages)."""
    id: UUID
    language: str
    title: str | None = None
    message_count: int = 0
    latest_script_filename: str | None = None
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class ScriptBuilderSessionDetail(BaseModel):
    """Full session with message history."""
    id: UUID
    language: str
    title: str | None = None
    messages: list[ScriptBuilderMessageSchema] = []
    latest_script: str | None = None
    latest_script_filename: str | None = None
    message_count: int = 0
    ai_session_id: UUID | None = None
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class SaveToLibraryRequest(BaseModel):
    """Request to save a generated script to the Script Library."""
    name: str = Field(min_length=1, max_length=200)
    description: str | None = None
    category_id: UUID | None = None
    share_with_team: bool = False
    script_body: str | None = None
    parameters_schema: dict | None = None
