"""
Pending task model for tracking open items across clients and projects.

Tracks tasks that need to be completed, their priority, status, and
assignment information.
"""

from datetime import date, datetime
from typing import TYPE_CHECKING, Optional

from sqlalchemy import CHAR, CheckConstraint, DATE, ForeignKey, Index, String, Text, TIMESTAMP
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func

from .base import Base, TimestampMixin, UUIDMixin

if TYPE_CHECKING:
    from .client import Client
    from .project import Project
    from .work_item import WorkItem


class PendingTask(Base, UUIDMixin, TimestampMixin):
    """
    Pending task model for open items across all clients and projects.

    Tracks tasks that need to be completed with priority, blocking information,
    assignment, and due dates. These represent work items that are planned or
    in progress but not yet completed.

    Attributes:
        client_id: Foreign key to clients table
        project_id: Foreign key to projects table
        work_item_id: Foreign key to work_items table (if task linked to work item)
        title: Brief title of the task
        description: Detailed description of the task
        priority: Task priority (critical, high, medium, low)
        blocked_by: Description of what is blocking this task
        assigned_to: Name of person assigned to the task
        due_date: Due date for the task
        status: Task status (pending, in_progress, blocked, completed, cancelled)
        completed_at: When the task was completed
        client: Relationship to Client model
        project: Relationship to Project model
        work_item: Relationship to WorkItem model
    """

    __tablename__ = "pending_tasks"

    # Foreign keys
    client_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("clients.id", ondelete="CASCADE"),
        doc="Foreign key to clients table"
    )

    project_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("projects.id", ondelete="CASCADE"),
        doc="Foreign key to projects table"
    )

    work_item_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("work_items.id", ondelete="SET NULL"),
        doc="Foreign key to work_items table (if task linked to work item)"
    )

    # Task details
    title: Mapped[str] = mapped_column(
        String(500),
        nullable=False,
        doc="Brief title of the task"
    )

    description: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="Detailed description of the task"
    )

    # Priority and blocking
    priority: Mapped[Optional[str]] = mapped_column(
        String(20),
        doc="Task priority: critical, high, medium, low"
    )

    blocked_by: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="Description of what is blocking this task"
    )

    # Assignment
    assigned_to: Mapped[Optional[str]] = mapped_column(
        String(255),
        doc="Name of person assigned to the task"
    )

    # Scheduling
    due_date: Mapped[Optional[date]] = mapped_column(
        DATE,
        doc="Due date for the task"
    )

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

    # Completion tracking
    completed_at: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMP,
        doc="When the task was completed"
    )

    # Relationships
    client: Mapped[Optional["Client"]] = relationship(
        "Client",
        back_populates="pending_tasks",
        doc="Relationship to Client model"
    )

    project: Mapped[Optional["Project"]] = relationship(
        "Project",
        back_populates="pending_tasks",
        doc="Relationship to Project model"
    )

    work_item: Mapped[Optional["WorkItem"]] = relationship(
        "WorkItem",
        doc="Relationship to WorkItem model"
    )

    # Constraints and indexes
    __table_args__ = (
        CheckConstraint(
            "priority IN ('critical', 'high', 'medium', 'low')",
            name="ck_pending_tasks_priority"
        ),
        CheckConstraint(
            "status IN ('pending', 'in_progress', 'blocked', 'completed', 'cancelled')",
            name="ck_pending_tasks_status"
        ),
        Index("idx_pending_tasks_client", "client_id"),
        Index("idx_pending_tasks_status", "status"),
        Index("idx_pending_tasks_priority", "priority"),
    )

    def __repr__(self) -> str:
        """String representation of the pending task."""
        return f"<PendingTask(title='{self.title}', status='{self.status}', priority='{self.priority}')>"
