"""Type definitions for pipeline SDK results."""

from decimal import Decimal
from typing import Any
from uuid import UUID

from pydantic import BaseModel, Field


class TokenUsage(BaseModel):
    """Token usage information from generation."""

    input_tokens: int
    output_tokens: int
    cache_creation_tokens: int | None = None
    cache_read_tokens: int | None = None


class CostBreakdown(BaseModel):
    """Cost breakdown for execution."""

    input_cost_usd: Decimal
    output_cost_usd: Decimal
    cache_cost_usd: Decimal | None = None
    total_cost_usd: Decimal


class GenerateTextResult(BaseModel):
    """Result from ctx.generate_text() primitive.

    Contains the output text, structured output (if schema provided),
    execution metadata, and cost information.
    """

    execution_id: UUID
    """Unique identifier for this execution."""

    chat_session_id: UUID | None = None
    """Chat session used for this execution."""

    output_text: str
    """Raw text output from the model."""

    structured_output: dict[str, Any] | None = None
    """Parsed structured output if output_schema was provided."""

    usage: TokenUsage
    """Token usage statistics."""

    cost: CostBreakdown
    """Cost breakdown for this execution."""

    provider_key: str
    """Provider that handled the request (e.g., 'openai', 'anthropic')."""

    provider_model_name: str
    """Model used for generation."""

    finish_reason: str
    """Why generation stopped (e.g., 'stop', 'length')."""

    metadata: dict[str, Any] = Field(default_factory=dict)
    """Additional metadata from the execution."""


class GenerateTextTurnResult(BaseModel):
    step_id: str
    """Generated step identifier used for this conversational turn."""

    result: GenerateTextResult
    """Underlying generation result returned by ctx.generate_text()."""


class ApprovalResult(BaseModel):
    """Result from ctx.wait_for_approval() primitive.

    Contains the approval decision and any data provided by the approver.
    """

    approved: bool
    """Whether the approval was granted."""

    approved_by_user_id: UUID | None = None
    """User who made the approval decision."""

    decision_data: dict[str, Any] = Field(default_factory=dict)
    """Additional data provided with the decision (selections, feedback, etc.)."""

    decided_at: str | None = None
    """ISO timestamp when the decision was made."""


class ApprovalCheckpoint(BaseModel):
    """Server-side approval checkpoint data returned by the approval API."""

    id: UUID
    pipeline_execution_id: UUID
    approval_key: str
    status: str
    approved: bool | None = None
    decided_by_user_id: UUID | None = None
    decision_data: dict[str, Any] | None = None
    decided_at: str | None = None
    created_at: str
