"""coord_todos

Revision ID: 20260526_120000
Revises: 20260512_120000
Create Date: 2026-05-26 12:00:00

Creates the coord_todos table for personal and project-scoped to-do items,
supporting sub-tasks via a self-referencing parent_id FK.
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "20260526_120000"
down_revision: Union[str, None] = "20260512_120000"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Create coord_todos table."""
    op.create_table(
        "coord_todos",
        sa.Column("id", sa.CHAR(36), primary_key=True),
        sa.Column("text", sa.Text(), nullable=False),
        sa.Column("project_key", sa.String(100), nullable=True),
        sa.Column("parent_id", sa.CHAR(36), sa.ForeignKey("coord_todos.id", ondelete="CASCADE"), nullable=True),
        sa.Column("assigned_to_user", sa.String(50), nullable=True),
        sa.Column("assigned_to_machine", sa.String(100), nullable=True),
        sa.Column("auto_created", sa.Boolean(), nullable=False, server_default=sa.text("0")),
        sa.Column("source_context", sa.Text(), nullable=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="pending"),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        sa.Column("completed_by", sa.String(100), nullable=True),
        sa.Column("created_by_user", sa.String(50), nullable=False),
        sa.Column("created_by_machine", sa.String(100), nullable=False),
        sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
        sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")),
        sa.CheckConstraint(
            "status IN ('pending', 'done', 'cancelled')",
            name="ck_coord_todos_status",
        ),
    )
    op.create_index("idx_coord_todos_project_status", "coord_todos", ["project_key", "status"])
    op.create_index("idx_coord_todos_assigned", "coord_todos", ["assigned_to_user", "assigned_to_machine", "status"])
    op.create_index("idx_coord_todos_parent", "coord_todos", ["parent_id"])


def downgrade() -> None:
    """Drop coord_todos table."""
    op.drop_table("coord_todos")
