"""Workflow model — a defined automation graph (build plan Sections 5, 8)."""

from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, String, Uuid
from sqlalchemy.orm import Mapped, mapped_column

from legate.db.base import Base, TimestampMixin, UUIDPrimaryKeyMixin


class Workflow(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "workflows"

    workspace_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("workspaces.id", ondelete="CASCADE"), index=True, nullable=False
    )
    created_by: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
    )
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str] = mapped_column(String(1024), nullable=False, default="")
    # The graph: {"nodes": [...], "edges": [...]}.
    definition_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
    # manual | schedule | webhook | event
    trigger_type: Mapped[str] = mapped_column(String(20), nullable=False, default="manual")
    trigger_config: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
    # Webhook trigger: a unique inbound token + HMAC signing secret.
    webhook_token: Mapped[str | None] = mapped_column(
        String(64), unique=True, index=True, nullable=True
    )
    webhook_secret: Mapped[str | None] = mapped_column(String(128), nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    # Bookkeeping for the cron scheduler.
    last_triggered_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )

    def __repr__(self) -> str:  # pragma: no cover - debug helper
        return f"<Workflow {self.name} ws={self.workspace_id}>"
