"""thin phase 4: ingredient.aliases, recipe.calories_per_serving, ingredient_grocery_match

Revision ID: 0006_recipe_engine_thin
Revises: 0005_grocery_item_external_id
Create Date: 2026-05-05
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql import UUID, ARRAY


revision = "0006"
down_revision = "0005"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column(
        "ingredient",
        sa.Column(
            "aliases",
            ARRAY(sa.Text()),
            nullable=False,
            server_default="{}",
        ),
    )

    op.add_column(
        "recipe",
        sa.Column("calories_per_serving", sa.Integer(), nullable=True),
    )

    op.execute(
        "CREATE TYPE ingredient_match_source_enum AS ENUM ('auto', 'manual')"
    )

    op.create_table(
        "ingredient_grocery_match",
        sa.Column(
            "id",
            UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column(
            "ingredient_id",
            UUID(as_uuid=True),
            sa.ForeignKey("ingredient.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column(
            "grocery_item_id",
            UUID(as_uuid=True),
            sa.ForeignKey("grocery_item.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("confidence", sa.Numeric(4, 3), nullable=False),
        sa.Column(
            "source",
            postgresql.ENUM(
                name="ingredient_match_source_enum",
                create_type=False,
            ),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.UniqueConstraint(
            "ingredient_id",
            "grocery_item_id",
            name="uq_ingredient_grocery_match_pair",
        ),
    )

    op.create_index(
        "ix_ingredient_grocery_match_ingredient_confidence",
        "ingredient_grocery_match",
        ["ingredient_id", sa.text("confidence DESC")],
    )


def downgrade() -> None:
    op.drop_index(
        "ix_ingredient_grocery_match_ingredient_confidence",
        table_name="ingredient_grocery_match",
    )
    op.drop_table("ingredient_grocery_match")
    op.execute("DROP TYPE IF EXISTS ingredient_match_source_enum")
    op.drop_column("recipe", "calories_per_serving")
    op.drop_column("ingredient", "aliases")
