"""Create pipeline_events table.

Revision ID: 004_pipeline_events
Revises: 003_content_reports
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB

revision = "004_pipeline_events"
down_revision = "003_content_reports"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "pipeline_events",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.func.gen_random_uuid()),
        sa.Column("video_id", UUID(as_uuid=True), nullable=False, index=True),
        sa.Column("stage", sa.String(50), nullable=False),
        sa.Column("event_type", sa.String(30), nullable=False),
        sa.Column("prompt_tokens", sa.Integer(), nullable=True),
        sa.Column("completion_tokens", sa.Integer(), nullable=True),
        sa.Column("total_tokens", sa.Integer(), nullable=True),
        sa.Column("model", sa.String(100), nullable=True),
        sa.Column("duration_ms", sa.Integer(), nullable=True),
        sa.Column("payload", JSONB(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    # Composite index for event log queries (video + newest first)
    op.create_index("ix_pipeline_events_video_created", "pipeline_events", ["video_id", "created_at"])


def downgrade() -> None:
    op.drop_index("ix_pipeline_events_video_created")
    op.drop_table("pipeline_events")
