"""Add highlight_candidates table for highlight detection scoring.

Revision ID: 019_add_highlight_candidates
Revises: 018_add_impersonation_log
"""

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


revision = "019_add_highlight_candidates"
down_revision = "018_add_impersonation_log"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Pure SQL — idempotent with IF NOT EXISTS / exception guards
    op.execute("DO $$ BEGIN CREATE TYPE highlight_status AS ENUM ('candidate', 'approved', 'rejected'); EXCEPTION WHEN duplicate_object THEN NULL; END $$")
    op.execute("""
        CREATE TABLE IF NOT EXISTS highlight_candidates (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            key_moment_id UUID NOT NULL UNIQUE REFERENCES key_moments(id) ON DELETE CASCADE,
            source_video_id UUID NOT NULL REFERENCES source_videos(id) ON DELETE CASCADE,
            score FLOAT NOT NULL,
            score_breakdown JSONB,
            duration_secs FLOAT NOT NULL,
            status highlight_status NOT NULL DEFAULT 'candidate',
            created_at TIMESTAMP NOT NULL DEFAULT now(),
            updated_at TIMESTAMP NOT NULL DEFAULT now()
        )
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_highlight_candidates_source_video_id ON highlight_candidates (source_video_id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_highlight_candidates_score_desc ON highlight_candidates (score DESC)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_highlight_candidates_status ON highlight_candidates (status)")


def downgrade() -> None:
    op.drop_index("ix_highlight_candidates_status")
    op.drop_index("ix_highlight_candidates_score_desc")
    op.drop_index("ix_highlight_candidates_source_video_id")
    op.drop_table("highlight_candidates")
    sa.Enum(name="highlight_status").drop(op.get_bind(), checkfirst=True)
