"""Add agent_messages table for inter-agent coordination

Revision ID: f3a4b5c6d7e8
Revises: e2f3a4b5c6d7
Create Date: 2026-03-16 00:00:00.000000
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import UUID

revision: str = "f3a4b5c6d7e8"
down_revision: Union[str, None] = "e2f3a4b5c6d7"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "agent_messages",
        sa.Column("id", UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text("gen_random_uuid()")),
        sa.Column("from_agent", sa.String(100), nullable=False),
        sa.Column("to_agent", sa.String(100), nullable=False),
        sa.Column("subject", sa.String(500), nullable=False),
        sa.Column("body", sa.Text, nullable=False),
        sa.Column("thread_id", UUID(as_uuid=True),
                  sa.ForeignKey("agent_messages.id", ondelete="SET NULL"),
                  nullable=True),
        sa.Column("read_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("archived_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
    )
    op.create_index("ix_agent_messages_to_agent_read_at",
                    "agent_messages", ["to_agent", "read_at"])
    op.create_index("ix_agent_messages_thread_id",
                    "agent_messages", ["thread_id"])
    op.create_index("ix_agent_messages_created_at",
                    "agent_messages", ["created_at"])


def downgrade() -> None:
    op.drop_index("ix_agent_messages_created_at", "agent_messages")
    op.drop_index("ix_agent_messages_thread_id", "agent_messages")
    op.drop_index("ix_agent_messages_to_agent_read_at", "agent_messages")
    op.drop_table("agent_messages")
