"""TaskInstance database model."""
from __future__ import annotations

from datetime import datetime

from sqlalchemy import DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from crondag.models.base import Base


class TaskInstanceModel(Base):
    __tablename__ = "task_instance"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    task_id: Mapped[str] = mapped_column(String(250), index=True)
    dag_id: Mapped[str] = mapped_column(String(250), ForeignKey("dag.dag_id"), index=True)
    run_id: Mapped[str] = mapped_column(String(250), index=True)
    state: Mapped[str] = mapped_column(String(50), default="pending")
    try_number: Mapped[int] = mapped_column(Integer, default=1)
    max_retries: Mapped[int] = mapped_column(Integer, default=0)
    start_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    end_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    duration: Mapped[float | None] = mapped_column(Float, nullable=True)
    return_value: Mapped[str | None] = mapped_column(Text, nullable=True)  # JSON
    error: Mapped[str | None] = mapped_column(Text, nullable=True)

    def __repr__(self) -> str:
        return f"<TaskInstanceModel task_id={self.task_id!r} state={self.state!r}>"
