#!/usr/bin/env python3
"""
Script to add sample recipes for testing
"""
import asyncio
import os
import sys
from datetime import datetime
from decimal import Decimal

# Add the app directory to Python path
sys.path.append(os.path.join(os.path.dirname(__file__), 'app'))

from core.database import get_db_session
from repositories.recipe_repository import RecipeRepository
from schemas.recipes import RecipeCreate, RecipeIngredientCreate

# Sample tenant ID - you should replace this with a real tenant ID from your system
SAMPLE_TENANT_ID = "946206b3-7446-436b-b29d-f265b28d9ff5"

# Sample finished product IDs - you should replace these with real product IDs from your system
SAMPLE_PRODUCT_IDS = [
    "550e8400-e29b-41d4-a716-446655440001",  # Pan Integral
    "550e8400-e29b-41d4-a716-446655440002",  # Croissant
    "550e8400-e29b-41d4-a716-446655440003",  # Tarta de Manzana
    "550e8400-e29b-41d4-a716-446655440004",  # Magdalenas
]

# Sample ingredient IDs - you should replace these with real ingredient IDs from your system
SAMPLE_INGREDIENT_IDS = [
    "660e8400-e29b-41d4-a716-446655440001",  # Harina integral
    "660e8400-e29b-41d4-a716-446655440002",  # Agua
    "660e8400-e29b-41d4-a716-446655440003",  # Levadura
    "660e8400-e29b-41d4-a716-446655440004",  # Sal
    "660e8400-e29b-41d4-a716-446655440005",  # Harina de fuerza
    "660e8400-e29b-41d4-a716-446655440006",  # Mantequilla
    "660e8400-e29b-41d4-a716-446655440007",  # Leche
    "660e8400-e29b-41d4-a716-446655440008",  # Azúcar
    "660e8400-e29b-41d4-a716-446655440009",  # Manzanas
    "660e8400-e29b-41d4-a716-446655440010",  # Huevos
    "660e8400-e29b-41d4-a716-446655440011",  # Limón
    "660e8400-e29b-41d4-a716-446655440012",  # Canela
]

async def add_sample_recipes():
    """Add sample recipes to the database"""
    async with get_db_session() as session:
        recipe_repo = RecipeRepository(session)

        sample_recipes = [
            {
                "name": "Pan de Molde Integral",
                "recipe_code": "PAN001",
                "finished_product_id": SAMPLE_PRODUCT_IDS[0],
                "description": "Pan integral artesanal con semillas, perfecto para desayunos saludables.",
                "category": "bread",
                "difficulty_level": 2,
                "yield_quantity": 1,
                "yield_unit": "units",
                "prep_time_minutes": 120,
                "cook_time_minutes": 35,
                "total_time_minutes": 155,
                "is_signature_item": False,
                "target_margin_percentage": Decimal("40.0"),
                "ingredients": [
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[0], "quantity": 500, "unit": "g", "is_optional": False, "ingredient_order": 1},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[1], "quantity": 300, "unit": "ml", "is_optional": False, "ingredient_order": 2},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[2], "quantity": 10, "unit": "g", "is_optional": False, "ingredient_order": 3},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[3], "quantity": 8, "unit": "g", "is_optional": False, "ingredient_order": 4},
                ]
            },
            {
                "name": "Croissants de Mantequilla",
                "recipe_code": "CRO001",
                "finished_product_id": SAMPLE_PRODUCT_IDS[1],
                "description": "Croissants franceses tradicionales con laminado de mantequilla.",
                "category": "pastry",
                "difficulty_level": 3,
                "yield_quantity": 12,
                "yield_unit": "units",
                "prep_time_minutes": 480,
                "cook_time_minutes": 20,
                "total_time_minutes": 500,
                "is_signature_item": True,
                "target_margin_percentage": Decimal("52.8"),
                "ingredients": [
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[4], "quantity": 500, "unit": "g", "is_optional": False, "ingredient_order": 1},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[5], "quantity": 250, "unit": "g", "is_optional": False, "ingredient_order": 2},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[6], "quantity": 150, "unit": "ml", "is_optional": False, "ingredient_order": 3},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[7], "quantity": 50, "unit": "g", "is_optional": False, "ingredient_order": 4},
                ]
            },
            {
                "name": "Tarta de Manzana",
                "recipe_code": "TAR001",
                "finished_product_id": SAMPLE_PRODUCT_IDS[2],
                "description": "Tarta casera de manzana con canela y masa quebrada.",
                "category": "cake",
                "difficulty_level": 1,
                "yield_quantity": 8,
                "yield_unit": "portions",
                "prep_time_minutes": 45,
                "cook_time_minutes": 40,
                "total_time_minutes": 85,
                "is_signature_item": False,
                "target_margin_percentage": Decimal("65.0"),
                "ingredients": [
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[8], "quantity": 1000, "unit": "g", "is_optional": False, "ingredient_order": 1},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[0], "quantity": 250, "unit": "g", "is_optional": False, "ingredient_order": 2},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[5], "quantity": 125, "unit": "g", "is_optional": False, "ingredient_order": 3},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[7], "quantity": 100, "unit": "g", "is_optional": False, "ingredient_order": 4},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[11], "quantity": 5, "unit": "g", "is_optional": True, "ingredient_order": 5},
                ]
            },
            {
                "name": "Magdalenas de Limón",
                "recipe_code": "MAG001",
                "finished_product_id": SAMPLE_PRODUCT_IDS[3],
                "description": "Magdalenas suaves y esponjosas con ralladura de limón.",
                "category": "pastry",
                "difficulty_level": 1,
                "yield_quantity": 12,
                "yield_unit": "units",
                "prep_time_minutes": 20,
                "cook_time_minutes": 25,
                "total_time_minutes": 45,
                "is_signature_item": False,
                "target_margin_percentage": Decimal("57.8"),
                "ingredients": [
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[0], "quantity": 200, "unit": "g", "is_optional": False, "ingredient_order": 1},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[9], "quantity": 3, "unit": "units", "is_optional": False, "ingredient_order": 2},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[7], "quantity": 150, "unit": "g", "is_optional": False, "ingredient_order": 3},
                    {"ingredient_id": SAMPLE_INGREDIENT_IDS[10], "quantity": 2, "unit": "units", "is_optional": False, "ingredient_order": 4},
                ]
            }
        ]

        for recipe_data in sample_recipes:
            try:
                # Prepare ingredients
                ingredients = [
                    RecipeIngredientCreate(**ing_data)
                    for ing_data in recipe_data.pop("ingredients")
                ]

                # Create recipe
                recipe_create = RecipeCreate(
                    **recipe_data,
                    ingredients=ingredients
                )

                # Check if recipe already exists
                existing_recipes = await recipe_repo.search_recipes(
                    tenant_id=SAMPLE_TENANT_ID,
                    search_term=recipe_data["name"]
                )

                recipe_exists = any(
                    recipe.name == recipe_data["name"]
                    for recipe in existing_recipes
                )

                if not recipe_exists:
                    recipe = await recipe_repo.create_recipe(
                        tenant_id=SAMPLE_TENANT_ID,
                        recipe_data=recipe_create
                    )
                    print(f"✅ Created recipe: {recipe.name}")
                else:
                    print(f"⏭️  Recipe already exists: {recipe_data['name']}")

            except Exception as e:
                print(f"❌ Error creating recipe {recipe_data['name']}: {e}")

        await session.commit()
        print(f"\n🎉 Sample recipes setup completed!")

if __name__ == "__main__":
    print("🧁 Adding sample recipes to database...")
    print(f"📍 Tenant ID: {SAMPLE_TENANT_ID}")
    print("=" * 50)

    asyncio.run(add_sample_recipes())