"""Initial recipe management tables

Revision ID: 001_initial_recipe_tables
Revises: 
Create Date: 2024-01-15 10:00:00.000000

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

# revision identifiers, used by Alembic.
revision = '001_initial_recipe_tables'
down_revision = None
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Create enum types
    op.execute("CREATE TYPE recipestatus AS ENUM ('draft', 'active', 'testing', 'archived', 'discontinued')")
    op.execute("CREATE TYPE productionstatus AS ENUM ('planned', 'in_progress', 'completed', 'failed', 'cancelled')")
    op.execute("CREATE TYPE measurementunit AS ENUM ('g', 'kg', 'ml', 'l', 'cups', 'tbsp', 'tsp', 'units', 'pieces', '%')")
    op.execute("CREATE TYPE productionpriority AS ENUM ('low', 'normal', 'high', 'urgent')")
    
    # Create recipes table
    op.create_table(
        'recipes',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('name', sa.String(255), nullable=False, index=True),
        sa.Column('recipe_code', sa.String(100), nullable=True, index=True),
        sa.Column('version', sa.String(20), nullable=False, default='1.0'),
        sa.Column('finished_product_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('description', sa.Text, nullable=True),
        sa.Column('category', sa.String(100), nullable=True, index=True),
        sa.Column('cuisine_type', sa.String(100), nullable=True),
        sa.Column('difficulty_level', sa.Integer, nullable=False, default=1),
        sa.Column('yield_quantity', sa.Float, nullable=False),
        sa.Column('yield_unit', sa.Enum('g', 'kg', 'ml', 'l', 'cups', 'tbsp', 'tsp', 'units', 'pieces', '%', name='measurementunit'), nullable=False),
        sa.Column('prep_time_minutes', sa.Integer, nullable=True),
        sa.Column('cook_time_minutes', sa.Integer, nullable=True),
        sa.Column('total_time_minutes', sa.Integer, nullable=True),
        sa.Column('rest_time_minutes', sa.Integer, nullable=True),
        sa.Column('estimated_cost_per_unit', sa.Numeric(10, 2), nullable=True),
        sa.Column('last_calculated_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('cost_calculation_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('target_margin_percentage', sa.Float, nullable=True),
        sa.Column('suggested_selling_price', sa.Numeric(10, 2), nullable=True),
        sa.Column('instructions', postgresql.JSONB, nullable=True),
        sa.Column('preparation_notes', sa.Text, nullable=True),
        sa.Column('storage_instructions', sa.Text, nullable=True),
        sa.Column('quality_standards', sa.Text, nullable=True),
        sa.Column('serves_count', sa.Integer, nullable=True),
        sa.Column('nutritional_info', postgresql.JSONB, nullable=True),
        sa.Column('allergen_info', postgresql.JSONB, nullable=True),
        sa.Column('dietary_tags', postgresql.JSONB, nullable=True),
        sa.Column('batch_size_multiplier', sa.Float, nullable=False, default=1.0),
        sa.Column('minimum_batch_size', sa.Float, nullable=True),
        sa.Column('maximum_batch_size', sa.Float, nullable=True),
        sa.Column('optimal_production_temperature', sa.Float, nullable=True),
        sa.Column('optimal_humidity', sa.Float, nullable=True),
        sa.Column('quality_check_points', postgresql.JSONB, nullable=True),
        sa.Column('common_issues', postgresql.JSONB, nullable=True),
        sa.Column('status', sa.Enum('draft', 'active', 'testing', 'archived', 'discontinued', name='recipestatus'), nullable=False, default='draft', index=True),
        sa.Column('is_seasonal', sa.Boolean, default=False),
        sa.Column('season_start_month', sa.Integer, nullable=True),
        sa.Column('season_end_month', sa.Integer, nullable=True),
        sa.Column('is_signature_item', sa.Boolean, default=False),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now()),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=True),
    )
    
    # Create recipe ingredients table
    op.create_table(
        'recipe_ingredients',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('recipe_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('recipes.id', ondelete='CASCADE'), nullable=False, index=True),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('quantity', sa.Float, nullable=False),
        sa.Column('unit', sa.Enum('g', 'kg', 'ml', 'l', 'cups', 'tbsp', 'tsp', 'units', 'pieces', '%', name='measurementunit'), nullable=False),
        sa.Column('quantity_in_base_unit', sa.Float, nullable=True),
        sa.Column('alternative_quantity', sa.Float, nullable=True),
        sa.Column('alternative_unit', sa.Enum('g', 'kg', 'ml', 'l', 'cups', 'tbsp', 'tsp', 'units', 'pieces', '%', name='measurementunit'), nullable=True),
        sa.Column('preparation_method', sa.String(255), nullable=True),
        sa.Column('ingredient_notes', sa.Text, nullable=True),
        sa.Column('is_optional', sa.Boolean, default=False),
        sa.Column('ingredient_order', sa.Integer, nullable=False, default=1),
        sa.Column('ingredient_group', sa.String(100), nullable=True),
        sa.Column('substitution_options', postgresql.JSONB, nullable=True),
        sa.Column('substitution_ratio', sa.Float, nullable=True),
        sa.Column('unit_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('total_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('cost_updated_at', sa.DateTime(timezone=True), nullable=True),
    )
    
    # Create production batches table
    op.create_table(
        'production_batches',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('recipe_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('recipes.id'), nullable=False, index=True),
        sa.Column('batch_number', sa.String(100), nullable=False, index=True),
        sa.Column('production_date', sa.DateTime(timezone=True), nullable=False, index=True),
        sa.Column('planned_start_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('actual_start_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('planned_end_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('actual_end_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('planned_quantity', sa.Float, nullable=False),
        sa.Column('actual_quantity', sa.Float, nullable=True),
        sa.Column('yield_percentage', sa.Float, nullable=True),
        sa.Column('batch_size_multiplier', sa.Float, nullable=False, default=1.0),
        sa.Column('status', sa.Enum('planned', 'in_progress', 'completed', 'failed', 'cancelled', name='productionstatus'), nullable=False, default='planned', index=True),
        sa.Column('priority', sa.Enum('low', 'normal', 'high', 'urgent', name='productionpriority'), nullable=False, default='normal'),
        sa.Column('assigned_staff', postgresql.JSONB, nullable=True),
        sa.Column('production_notes', sa.Text, nullable=True),
        sa.Column('quality_score', sa.Float, nullable=True),
        sa.Column('quality_notes', sa.Text, nullable=True),
        sa.Column('defect_rate', sa.Float, nullable=True),
        sa.Column('rework_required', sa.Boolean, default=False),
        sa.Column('planned_material_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('actual_material_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('labor_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('overhead_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('total_production_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('cost_per_unit', sa.Numeric(10, 2), nullable=True),
        sa.Column('production_temperature', sa.Float, nullable=True),
        sa.Column('production_humidity', sa.Float, nullable=True),
        sa.Column('oven_temperature', sa.Float, nullable=True),
        sa.Column('baking_time_minutes', sa.Integer, nullable=True),
        sa.Column('waste_quantity', sa.Float, nullable=False, default=0.0),
        sa.Column('waste_reason', sa.String(255), nullable=True),
        sa.Column('efficiency_percentage', sa.Float, nullable=True),
        sa.Column('customer_order_reference', sa.String(100), nullable=True),
        sa.Column('pre_order_quantity', sa.Float, nullable=True),
        sa.Column('shelf_quantity', sa.Float, nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now()),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('completed_by', postgresql.UUID(as_uuid=True), nullable=True),
    )
    
    # Create production ingredient consumption table
    op.create_table(
        'production_ingredient_consumption',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('production_batch_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('production_batches.id', ondelete='CASCADE'), nullable=False, index=True),
        sa.Column('recipe_ingredient_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('recipe_ingredients.id'), nullable=False, index=True),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('stock_id', postgresql.UUID(as_uuid=True), nullable=True, index=True),
        sa.Column('planned_quantity', sa.Float, nullable=False),
        sa.Column('actual_quantity', sa.Float, nullable=False),
        sa.Column('unit', sa.Enum('g', 'kg', 'ml', 'l', 'cups', 'tbsp', 'tsp', 'units', 'pieces', '%', name='measurementunit'), nullable=False),
        sa.Column('variance_quantity', sa.Float, nullable=True),
        sa.Column('variance_percentage', sa.Float, nullable=True),
        sa.Column('unit_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('total_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('consumption_time', sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column('consumption_notes', sa.Text, nullable=True),
        sa.Column('staff_member', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('ingredient_condition', sa.String(50), nullable=True),
        sa.Column('quality_impact', sa.String(255), nullable=True),
        sa.Column('substitution_used', sa.Boolean, default=False),
        sa.Column('substitution_details', sa.Text, nullable=True),
    )
    
    # Create production schedules table
    op.create_table(
        'production_schedules',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('schedule_date', sa.DateTime(timezone=True), nullable=False, index=True),
        sa.Column('schedule_name', sa.String(255), nullable=True),
        sa.Column('total_planned_batches', sa.Integer, nullable=False, default=0),
        sa.Column('total_planned_items', sa.Float, nullable=False, default=0.0),
        sa.Column('estimated_production_hours', sa.Float, nullable=True),
        sa.Column('estimated_material_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('is_published', sa.Boolean, default=False),
        sa.Column('is_completed', sa.Boolean, default=False),
        sa.Column('completion_percentage', sa.Float, nullable=True),
        sa.Column('available_staff_hours', sa.Float, nullable=True),
        sa.Column('oven_capacity_hours', sa.Float, nullable=True),
        sa.Column('production_capacity_limit', sa.Float, nullable=True),
        sa.Column('schedule_notes', sa.Text, nullable=True),
        sa.Column('preparation_instructions', sa.Text, nullable=True),
        sa.Column('special_requirements', postgresql.JSONB, nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now()),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('published_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('published_at', sa.DateTime(timezone=True), nullable=True),
    )
    
    # Create indexes
    op.create_index('idx_recipes_tenant_name', 'recipes', ['tenant_id', 'name'])
    op.create_index('idx_recipes_tenant_product', 'recipes', ['tenant_id', 'finished_product_id'])
    op.create_index('idx_recipes_status', 'recipes', ['tenant_id', 'status'])
    op.create_index('idx_recipes_category', 'recipes', ['tenant_id', 'category', 'status'])
    op.create_index('idx_recipes_seasonal', 'recipes', ['tenant_id', 'is_seasonal', 'season_start_month', 'season_end_month'])
    op.create_index('idx_recipes_signature', 'recipes', ['tenant_id', 'is_signature_item', 'status'])
    
    op.create_index('idx_recipe_ingredients_recipe', 'recipe_ingredients', ['recipe_id', 'ingredient_order'])
    op.create_index('idx_recipe_ingredients_ingredient', 'recipe_ingredients', ['ingredient_id'])
    op.create_index('idx_recipe_ingredients_tenant', 'recipe_ingredients', ['tenant_id', 'recipe_id'])
    op.create_index('idx_recipe_ingredients_group', 'recipe_ingredients', ['recipe_id', 'ingredient_group', 'ingredient_order'])
    
    op.create_index('idx_production_batches_tenant_date', 'production_batches', ['tenant_id', 'production_date'])
    op.create_index('idx_production_batches_recipe', 'production_batches', ['recipe_id', 'production_date'])
    op.create_index('idx_production_batches_status', 'production_batches', ['tenant_id', 'status', 'production_date'])
    op.create_index('idx_production_batches_batch_number', 'production_batches', ['tenant_id', 'batch_number'])
    op.create_index('idx_production_batches_priority', 'production_batches', ['tenant_id', 'priority', 'planned_start_time'])
    
    op.create_index('idx_consumption_batch', 'production_ingredient_consumption', ['production_batch_id'])
    op.create_index('idx_consumption_ingredient', 'production_ingredient_consumption', ['ingredient_id', 'consumption_time'])
    op.create_index('idx_consumption_tenant', 'production_ingredient_consumption', ['tenant_id', 'consumption_time'])
    op.create_index('idx_consumption_recipe_ingredient', 'production_ingredient_consumption', ['recipe_ingredient_id'])
    op.create_index('idx_consumption_stock', 'production_ingredient_consumption', ['stock_id'])
    
    op.create_index('idx_production_schedules_tenant_date', 'production_schedules', ['tenant_id', 'schedule_date'])
    op.create_index('idx_production_schedules_published', 'production_schedules', ['tenant_id', 'is_published', 'schedule_date'])
    op.create_index('idx_production_schedules_completed', 'production_schedules', ['tenant_id', 'is_completed', 'schedule_date'])


def downgrade() -> None:
    # Drop all tables
    op.drop_table('production_schedules')
    op.drop_table('production_ingredient_consumption')
    op.drop_table('production_batches')
    op.drop_table('recipe_ingredients')
    op.drop_table('recipes')
    
    # Drop enum types
    op.execute("DROP TYPE IF EXISTS productionpriority")
    op.execute("DROP TYPE IF EXISTS measurementunit")
    op.execute("DROP TYPE IF EXISTS productionstatus")
    op.execute("DROP TYPE IF EXISTS recipestatus")