"""coord_agent_coordination

Revision ID: 20260512_120000
Revises: 20260309_074038
Create Date: 2026-05-12 12:00:00

Creates the agent coordination tables:
- coord_workflows: Named units of work spanning one or more sessions
- coord_work_items: Discrete tasks within a workflow
- coord_session_locks: Exclusive resource locks claimed by sessions
- coord_component_states: Current state of named components per project (composite PK)
- coord_messages: Inter-session messages and broadcasts
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    """Create all coordination tables."""

    op.create_table(
        "coord_workflows",
        sa.Column("id", sa.CHAR(36), primary_key=True),
        sa.Column("project_key", sa.String(200), nullable=False),
        sa.Column("name", sa.String(200), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="planning"),
        sa.Column("created_by", sa.String(200), nullable=False),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        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 ('planning', 'active', 'blocked', 'completed', 'cancelled')",
            name="ck_coord_workflows_status",
        ),
    )
    op.create_index("idx_coord_workflows_project_status", "coord_workflows", ["project_key", "status"])

    op.create_table(
        "coord_work_items",
        sa.Column("id", sa.CHAR(36), primary_key=True),
        sa.Column("workflow_id", sa.CHAR(36), sa.ForeignKey("coord_workflows.id", ondelete="CASCADE"), nullable=False),
        sa.Column("project_key", sa.String(200), nullable=False),
        sa.Column("title", sa.String(500), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="pending"),
        sa.Column("priority", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("assigned_session", sa.String(200), nullable=True),
        sa.Column("depends_on_id", sa.CHAR(36), sa.ForeignKey("coord_work_items.id", ondelete="SET NULL"), nullable=True),
        sa.Column("started_at", sa.DateTime(), nullable=True),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        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', 'in_progress', 'blocked', 'completed', 'cancelled')",
            name="ck_coord_work_items_status",
        ),
    )
    op.create_index("idx_coord_work_items_workflow", "coord_work_items", ["workflow_id"])
    op.create_index("idx_coord_work_items_project_status", "coord_work_items", ["project_key", "status"])
    op.create_index("idx_coord_work_items_assigned", "coord_work_items", ["assigned_session"])

    op.create_table(
        "coord_session_locks",
        sa.Column("id", sa.CHAR(36), primary_key=True),
        sa.Column("project_key", sa.String(200), nullable=False),
        sa.Column("session_id", sa.String(200), nullable=False),
        sa.Column("resource", sa.String(500), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("acquired_at", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
        sa.Column("expires_at", sa.DateTime(), nullable=True),
        sa.Column("released_at", sa.DateTime(), nullable=True),
        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")),
    )
    op.create_index("idx_coord_locks_project_resource", "coord_session_locks", ["project_key", "resource"])
    op.create_index("idx_coord_locks_session", "coord_session_locks", ["session_id"])

    op.create_table(
        "coord_component_states",
        sa.Column("project_key", sa.String(200), nullable=False),
        sa.Column("component", sa.String(200), nullable=False),
        sa.Column("state", sa.String(50), nullable=False),
        sa.Column("version", sa.String(100), nullable=True),
        sa.Column("notes", sa.Text(), nullable=True),
        sa.Column("updated_by", sa.String(200), 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.PrimaryKeyConstraint("project_key", "component", name="pk_coord_component_states"),
    )

    op.create_table(
        "coord_messages",
        sa.Column("id", sa.CHAR(36), primary_key=True),
        sa.Column("from_session", sa.String(200), nullable=False),
        sa.Column("to_session", sa.String(200), nullable=True),
        sa.Column("project_key", sa.String(200), nullable=True),
        sa.Column("subject", sa.String(500), nullable=False),
        sa.Column("body", sa.Text(), nullable=False),
        sa.Column("read_at", sa.DateTime(), nullable=True),
        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")),
    )
    op.create_index("idx_coord_messages_to_read", "coord_messages", ["to_session", "read_at"])
    op.create_index("idx_coord_messages_from", "coord_messages", ["from_session"])


def downgrade() -> None:
    """Drop all coordination tables in reverse dependency order."""
    op.drop_table("coord_messages")
    op.drop_table("coord_component_states")
    op.drop_table("coord_session_locks")
    op.drop_table("coord_work_items")
    op.drop_table("coord_workflows")
