"""工作流：SOP 的可执行形态。"""
from __future__ import annotations

from typing import Any, Dict, Optional

from sqlalchemy import Boolean, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from ..enums import DangerLevel
from .base import Base, TimestampMixin, pk


class Workflow(Base, TimestampMixin):
    """工作流定义。

    spec 存原文，spec_hash 存规范化后的哈希。spec_hash 变了而 version 没变 →
    拒绝发布（见 workflow-spec.md）。理由：A/B 对比的结论必须能追溯到
    具体哪一版流程，否则"上周跑的和这周跑的是不是同一个流程"说不清。
    """

    __tablename__ = "workflows"
    __table_args__ = (UniqueConstraint("key", "version", name="uq_workflow_key_version"),)

    id: Mapped[str] = pk("wf")
    key: Mapped[str] = mapped_column(String(64), nullable=False)
    name: Mapped[str] = mapped_column(String(128), nullable=False)
    version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)

    spec: Mapped[Dict[str, Any]] = mapped_column(JSON, nullable=False)
    spec_hash: Mapped[str] = mapped_column(String(64), nullable=False)

    danger_level: Mapped[str] = mapped_column(String(16), default=DangerLevel.NONE.value)
    source_sop: Mapped[Optional[str]] = mapped_column(String(255))
    published: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    approved_by: Mapped[Optional[str]] = mapped_column(String(64))
