"""Coordination workflow model."""

from datetime import datetime
from typing import Optional

from sqlalchemy import CHAR, CheckConstraint, Index, String, Text, DateTime
from sqlalchemy.orm import Mapped, mapped_column

from .base import Base, TimestampMixin, UUIDMixin


class CoordWorkflow(Base, UUIDMixin, TimestampMixin):
    """A named unit of work spanning one or more sessions."""

    __tablename__ = "coord_workflows"

    project_key: Mapped[str] = mapped_column(
        String(200),
        nullable=False,
        doc="Project namespace slug, e.g. 'gururmm', 'client/acme-corp'"
    )

    name: Mapped[str] = mapped_column(
        String(200),
        nullable=False,
        doc="Short identifier, e.g. 'discovery-feature'"
    )

    description: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="Freeform description, markdown ok"
    )

    status: Mapped[str] = mapped_column(
        String(20),
        nullable=False,
        default="planning",
        doc="Status: planning, active, blocked, completed, cancelled"
    )

    created_by: Mapped[str] = mapped_column(
        String(200),
        nullable=False,
        doc="Session that created this workflow, e.g. 'DESKTOP-0O8A1RL/Claude'"
    )

    completed_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime,
        doc="When the workflow reached a terminal state"
    )

    __table_args__ = (
        CheckConstraint(
            "status IN ('planning', 'active', 'blocked', 'completed', 'cancelled')",
            name="ck_coord_workflows_status"
        ),
        Index("idx_coord_workflows_project_status", "project_key", "status"),
    )

    def __repr__(self) -> str:
        return f"<CoordWorkflow(project_key='{self.project_key}', name='{self.name}', status='{self.status}')>"
