"""Coordination work item model."""

from datetime import datetime
from typing import Optional

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

from .base import Base, TimestampMixin, UUIDMixin


class CoordWorkItem(Base, UUIDMixin, TimestampMixin):
    """A discrete task within a coordination workflow."""

    __tablename__ = "coord_work_items"

    workflow_id: Mapped[str] = mapped_column(
        CHAR(36),
        ForeignKey("coord_workflows.id", ondelete="CASCADE"),
        nullable=False,
        doc="Parent workflow"
    )

    project_key: Mapped[str] = mapped_column(
        String(200),
        nullable=False,
        doc="Denormalized project key for filtering without join"
    )

    title: Mapped[str] = mapped_column(
        String(500),
        nullable=False,
        doc="Short title"
    )

    description: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="Full description, markdown ok — store design specs, schemas, etc."
    )

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

    priority: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        default=0,
        doc="Higher value = more urgent"
    )

    assigned_session: Mapped[Optional[str]] = mapped_column(
        String(200),
        doc="Session currently working this item"
    )

    depends_on_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("coord_work_items.id", ondelete="SET NULL"),
        doc="Blocking predecessor item"
    )

    started_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime,
        doc="When work began"
    )

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

    __table_args__ = (
        CheckConstraint(
            "status IN ('pending', 'in_progress', 'blocked', 'completed', 'cancelled')",
            name="ck_coord_work_items_status"
        ),
        Index("idx_coord_work_items_workflow", "workflow_id"),
        Index("idx_coord_work_items_project_status", "project_key", "status"),
        Index("idx_coord_work_items_assigned", "assigned_session"),
    )

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