from __future__ import annotations

from datetime import datetime

from sqlalchemy import BigInteger, Numeric, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column

from supply_infra.db.base import Base


class SchedulerJobExecution(Base):
    """定时任务执行记录（开始/结束各记一条，同一 run_id 关联）。"""

    __tablename__ = "scheduler_job_execution"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    run_id: Mapped[str] = mapped_column(
        String(36),
        nullable=False,
        index=True,
        comment="同一次执行的唯一标识",
    )
    job_name: Mapped[str] = mapped_column(String(128), nullable=False, comment="定时任务名称")
    job_id: Mapped[str | None] = mapped_column(String(64), nullable=True, comment="调度器 job id")
    status: Mapped[str] = mapped_column(
        String(32),
        nullable=False,
        comment="状态: started/finished/failed/skipped",
    )
    event_time: Mapped[datetime] = mapped_column(nullable=False, comment="事件发生时间")
    biz_dt: Mapped[str | None] = mapped_column(String(8), nullable=True, comment="业务日 YYYYMMDD")
    started_at: Mapped[datetime | None] = mapped_column(nullable=True, comment="任务开始时间")
    finished_at: Mapped[datetime | None] = mapped_column(nullable=True, comment="任务结束时间")
    duration_seconds: Mapped[float | None] = mapped_column(
        Numeric(10, 2),
        nullable=True,
        comment="执行耗时（秒）",
    )
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True, comment="失败原因")
    detail: Mapped[str | None] = mapped_column(Text, nullable=True, comment="执行结果摘要 JSON")
    create_time: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        comment="创建时间",
    )
    update_time: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间",
    )
