"""add_diarization_jobs_table

Revision ID: d8e5f6a7b2c3
Revises: c7d4e9f3a2b1
Create Date: 2025-12-19 10:00:00.000000

"""

from collections.abc import Sequence

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

# revision identifiers, used by Alembic.
revision: str = "d8e5f6a7b2c3"
down_revision: str | Sequence[str] | None = "c7d4e9f3a2b1"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create diarization_jobs table for tracking background jobs."""
    op.create_table(
        "diarization_jobs",
        sa.Column("id", sa.String(36), primary_key=True),
        sa.Column(
            "meeting_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.meetings.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("status", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("segments_updated", sa.Integer(), nullable=False, server_default="0"),
        sa.Column(
            "speaker_ids",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=False,
            server_default="[]",
        ),
        sa.Column("error_message", sa.Text(), nullable=False, server_default=""),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        schema="noteflow",
    )

    # Create index for meeting_id lookups
    op.create_index(
        "ix_diarization_jobs_meeting_id",
        "diarization_jobs",
        ["meeting_id"],
        schema="noteflow",
    )

    # Create index for status queries (e.g., finding running jobs)
    op.create_index(
        "ix_diarization_jobs_status",
        "diarization_jobs",
        ["status"],
        schema="noteflow",
    )


def downgrade() -> None:
    """Drop diarization_jobs table."""
    op.drop_index("ix_diarization_jobs_status", table_name="diarization_jobs", schema="noteflow")
    op.drop_index(
        "ix_diarization_jobs_meeting_id", table_name="diarization_jobs", schema="noteflow"
    )
    op.drop_table("diarization_jobs", schema="noteflow")
