"""Data migration to convert serving_size to float

Revision ID: 13939361fc35
Revises: a11a3921f528
Create Date: 2025-10-01 23:44:34.144506

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '13939361fc35'
down_revision: Union[str, None] = 'a11a3921f528'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """
    Data migration to convert existing string-based 'serving_size' values to floats.
    This version uses a session to iterate through the data, providing more robust error handling.
    """
    bind = op.get_bind()
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind=bind)
    session = Session()

    # Define a simple table structure for our purpose
    food_table = sa.Table('foods', sa.MetaData(),
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('name', sa.String),
        sa.Column('serving_size', sa.String)  # Treat it as String to be safe
    )

    try:
        foods_to_update = session.query(food_table).all()
        updated_count = 0
        
        for food in foods_to_update:
            # Check if serving_size is a string and needs conversion
            if isinstance(food.serving_size, str):
                try:
                    new_size = float(food.serving_size)
                    # Use session.execute for the update
                    session.execute(
                        food_table.update().
                        where(food_table.c.id == food.id).
                        values(serving_size=new_size)
                    )
                    updated_count += 1
                except (ValueError, TypeError):
                    print(f"Could not convert serving_size for Food ID {food.id} (Name: {food.name}). Value: '{food.serving_size}'")

        if updated_count > 0:
            session.commit()
            print(f"Successfully converted {updated_count} food items.")
        else:
            print("No food items required an update.")

    except Exception as e:
        print(f"An error occurred during the data migration: {e}")
        session.rollback()
    finally:
        session.close()


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # A downgrade for this data migration is not practical as it would require
    # converting floats back to strings, which could lead to loss of precision.
    # It is better to back up the database before upgrading.
    pass
    # ### end Alembic commands ###
