"""ImportTask — a single source file to import as part of a batch.

State machine: pending -> queued -> processing -> complete | skipped | failed.
Workers crashing mid-task leave rows in 'processing'; the recovery sweep
(tasks/maintenance.py::recover_interrupted_tasks) re-queues rows that have
been processing longer than the stuck-task threshold.
"""

from datetime import datetime

from sqlalchemy import (
    BigInteger,
    Boolean,
    DateTime,
    ForeignKey,
    Integer,
    String,
    Text,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from .base import Base


class ImportTask(Base):
    __tablename__ = "import_task"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    batch_id: Mapped[int] = mapped_column(
        ForeignKey("import_batch.id", ondelete="CASCADE"), nullable=False, index=True
    )

    source_path: Mapped[str] = mapped_column(Text, nullable=False)
    task_type: Mapped[str] = mapped_column(String(16), nullable=False)  # media|archive
    status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", index=True)

    # Poison-pill circuit breaker (alembic 0026). recovery_count tracks
    # how many times the stuck-task sweep has re-queued this row; after
    # the cap it's failed with a diagnostic instead of looping. refetched
    # bounds the one-shot re-download remediation to a single attempt.
    recovery_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    refetched: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    result_image_id: Mapped[int | None] = mapped_column(
        ForeignKey("image_record.id", ondelete="SET NULL"), nullable=True
    )
    error: Mapped[str | None] = mapped_column(Text, nullable=True)
    size_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False, server_default=func.now()
    )
    started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)

    batch = relationship("ImportBatch", back_populates="tasks")
