"""add_named_entities_table

Revision ID: h2c3d4e5f6g7
Revises: g1b2c3d4e5f6
Create Date: 2025-12-25 12: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 = "h2c3d4e5f6g7"
down_revision: str | Sequence[str] | None = "g1b2c3d4e5f6"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create named_entities table for NER storage."""
    op.execute(
        """
        CREATE OR REPLACE FUNCTION noteflow.set_updated_at()
        RETURNS trigger AS $$
        BEGIN
            NEW.updated_at = now();
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;
        """
    )

    op.create_table(
        "named_entities",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column(
            "meeting_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.meetings.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("text", sa.Text(), nullable=False),
        sa.Column("normalized_text", sa.Text(), nullable=False),
        sa.Column("category", sa.String(50), nullable=False),
        sa.Column(
            "segment_ids",
            postgresql.ARRAY(sa.Integer()),
            nullable=False,
            server_default="{}",
        ),
        sa.Column("confidence", sa.Float(), nullable=False, server_default="0.0"),
        sa.Column("is_pinned", sa.Boolean(), nullable=False, server_default="false"),
        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()"),
        ),
        sa.UniqueConstraint(
            "meeting_id", "normalized_text", name="uq_named_entities_meeting_text"
        ),
        schema="noteflow",
    )

    op.create_index(
        "idx_named_entities_meeting_id",
        "named_entities",
        ["meeting_id"],
        schema="noteflow",
    )

    op.create_index(
        "idx_named_entities_category",
        "named_entities",
        ["category"],
        schema="noteflow",
    )

    # Create updated_at trigger
    op.execute(
        """
        CREATE TRIGGER trg_named_entities_updated_at
        BEFORE UPDATE ON noteflow.named_entities
        FOR EACH ROW EXECUTE FUNCTION noteflow.set_updated_at();
        """
    )


def downgrade() -> None:
    """Drop named_entities table."""
    # Drop trigger first
    op.execute(
        "DROP TRIGGER IF EXISTS trg_named_entities_updated_at ON noteflow.named_entities;"
    )

    op.drop_index(
        "idx_named_entities_category",
        table_name="named_entities",
        schema="noteflow",
    )
    op.drop_index(
        "idx_named_entities_meeting_id",
        table_name="named_entities",
        schema="noteflow",
    )
    op.drop_table("named_entities", schema="noteflow")

    op.execute("DROP FUNCTION IF EXISTS noteflow.set_updated_at();")
