"""Schemas for the download job endpoints (§A5 download manager)."""

import datetime as dt
import uuid

from pydantic import BaseModel, Field

from app.domain.entities.download import DownloadJob


class DownloadCreate(BaseModel):
    """Request to download an item discovered on a fetch source."""

    source: str
    source_id: str = Field(min_length=1)
    # Optional free-text the result came from — stored for display only.
    query: str | None = None


class DownloadJobOut(BaseModel):
    id: uuid.UUID
    source: str
    source_id: str | None
    query: str | None
    status: str
    progress: float
    error_message: str | None
    retry_count: int
    track_id: uuid.UUID | None
    created_at: dt.datetime
    updated_at: dt.datetime

    @classmethod
    def from_entity(cls, job: DownloadJob) -> DownloadJobOut:
        return cls(
            id=job.id,
            source=job.source,
            source_id=job.source_id,
            query=job.query,
            status=job.status,
            progress=job.progress,
            error_message=job.error_message,
            retry_count=job.retry_count,
            track_id=job.track_id,
            created_at=job.created_at,
            updated_at=job.updated_at,
        )


class DownloadCreateResponse(BaseModel):
    """Result of requesting a download.

    ``already_in_library`` → the item was already imported (``track_id`` set, no
    job). Otherwise ``job`` describes the queued (or already in-flight) download.
    """

    already_in_library: bool
    track_id: uuid.UUID | None
    job: DownloadJobOut | None
