"""Add feedback_analysis to weekly_run and external fields to recipe

Revision ID: 0011
Revises: 0010
Create Date: 2026-05-23
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "0011"
down_revision = "0010"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add feedback_analysis JSONB to weekly_run
    op.add_column(
        "weekly_run",
        sa.Column("feedback_analysis", postgresql.JSONB, nullable=True),
    )

    # Add external source fields to recipe
    op.add_column(
        "recipe",
        sa.Column("external_source", sa.String(50), nullable=True),
    )
    op.add_column(
        "recipe",
        sa.Column("external_id", sa.String(100), nullable=True),
    )
    op.add_column(
        "recipe",
        sa.Column("discovery_reason", sa.Text, nullable=True),
    )

    # Index for deduplication lookups
    op.create_index(
        "idx_recipe_external",
        "recipe",
        ["external_source", "external_id"],
        unique=True,
        postgresql_where=sa.text("external_source IS NOT NULL AND external_id IS NOT NULL"),
    )


def downgrade() -> None:
    op.drop_index("idx_recipe_external", table_name="recipe")
    op.drop_column("recipe", "discovery_reason")
    op.drop_column("recipe", "external_id")
    op.drop_column("recipe", "external_source")
    op.drop_column("weekly_run", "feedback_analysis")
