"""Govdoc 审查运行模型 —— govdoc_runs 表。"""

from __future__ import annotations

from datetime import datetime

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

from fastapi_common.fastapi_common_web.models import BaseModel


class GovdocRun(BaseModel):
    """公文审查运行主表。"""

    __tablename__ = "govdoc_runs"

    Id: Mapped[int] = mapped_column("id", BigInteger, primary_key=True, autoincrement=True)
    documentId: Mapped[int] = mapped_column("document_id", BigInteger, comment="关联 leaudit_documents.id")
    documentFileId: Mapped[int | None] = mapped_column("document_file_id", BigInteger, comment="输入文件 ID，关联 leaudit_document_files.id")
    runNo: Mapped[int] = mapped_column("run_no", Integer, default=1, comment="同一文档第几次执行")
    triggerSource: Mapped[str] = mapped_column("trigger_source", String(64), default="upload", comment="触发来源：upload/manual/retry/migration")
    triggerUserId: Mapped[int | None] = mapped_column("trigger_user_id", BigInteger, comment="触发人 user_id")
    taskId: Mapped[str | None] = mapped_column("task_id", String(128), comment="Celery 任务 ID")

    # 运行状态
    status: Mapped[str] = mapped_column("status", String(64), default="pending", comment="pending/processing/completed/failed/cancelled")
    phase: Mapped[str | None] = mapped_column("phase", String(32), comment="当前阶段：parsing/executing/reporting")

    # 引擎快照
    engineVersion: Mapped[str | None] = mapped_column("engine_version", String(64), comment="引擎版本号")
    llmProvider: Mapped[str | None] = mapped_column("llm_provider", String(64), comment="LLM 提供商")
    llmModel: Mapped[str | None] = mapped_column("llm_model", String(128), comment="LLM 模型名")
    rulesPath: Mapped[str | None] = mapped_column("rules_path", String(1024), comment="本次运行使用的规则文件路径")

    # 结果汇总
    totalScore: Mapped[float | None] = mapped_column("total_score", Numeric(10, 2), comment="总分")
    passedCount: Mapped[int | None] = mapped_column("passed_count", Integer, comment="通过规则数")
    failedCount: Mapped[int | None] = mapped_column("failed_count", Integer, comment="未通过规则数")
    skippedCount: Mapped[int | None] = mapped_column("skipped_count", Integer, comment="跳过规则数")
    resultStatus: Mapped[str | None] = mapped_column("result_status", String(32), comment="综合结果：pass/fail/partial/error")
    resultSummaryJson: Mapped[str | None] = mapped_column("result_summary_json", Text, comment="结构化结果摘要 JSON")
    errorMessage: Mapped[str | None] = mapped_column("error_message", Text, comment="运行失败时错误描述")

    # 时间
    startedAt: Mapped[datetime | None] = mapped_column("started_at", DateTime(timezone=True), comment="开始执行时间")
    finishedAt: Mapped[datetime | None] = mapped_column("finished_at", DateTime(timezone=True), comment="结束执行时间")
