from __future__ import annotations

from typing import List, Optional

from pydantic import Field
from typing_extensions import Literal

from .._models import BaseModel


class GenerationError(BaseModel):
    code: str
    message: str


class GenerationOutput(BaseModel):
    url: Optional[str] = None
    duration_sec: Optional[float] = Field(default=None, alias="durationSec")


class GenerationUsage(BaseModel):
    credits: int = 0


class Generation(BaseModel):
    request_id: str = Field(alias="requestId")
    type: Optional[str] = None
    status: Literal["queued", "running", "succeeded", "failed"]
    outputs: List[GenerationOutput] = []
    usage: Optional[GenerationUsage] = None
    error: Optional[GenerationError] = None
    created_at: Optional[str] = Field(default=None, alias="createdAt")
    finished_at: Optional[str] = Field(default=None, alias="finishedAt")

    @property
    def url(self) -> str | None:
        """Shortcut for the first output URL. Returns None if no outputs."""
        return self.outputs[0].url if self.outputs else None

    @property
    def urls(self) -> list[str]:
        """All output URLs, filtering out None values."""
        return [o.url for o in self.outputs if o.url]

    @property
    def credits(self) -> int:
        """Credits consumed. Returns 0 if usage info is not available."""
        return self.usage.credits if self.usage else 0
