#!/bin/bash
#
# Master Demo Data Seeding Script
# Seeds all demo data for base template tenants
#
# This script executes all individual seed scripts in the correct order
# to populate the base demo template tenants with complete, realistic data
#
# Usage:
#   ./scripts/seed_all_demo_data.sh [--skip-existing]
#
# Options:
#   --skip-existing  Skip seeding if data already exists (idempotent)
#
# Environment Variables Required:
#   - DATABASE_URL or service-specific database URLs
#   - DEMO_MODE=production (recommended for consistent seeding)
#   - LOG_LEVEL=INFO (default)
#

set -e  # Exit on error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
SKIP_EXISTING=false
if [[ "$1" == "--skip-existing" ]]; then
    SKIP_EXISTING=true
fi

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Demo Data Seeding - Bakery IA${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "${YELLOW}⚠️ This script will seed demo data for:${NC}"
echo -e "   - Panadería San Pablo (Individual Bakery)"
echo -e "   - Panadería La Espiga (Central Workshop)"
echo ""
echo -e "${YELLOW}Execution Order:${NC}"
echo -e "   1. Auth: Users (enhanced with staff roles)"
echo -e "   2. Tenant: Tenant members (link staff to tenants)"
echo -e "   3. Inventory: Stock batches with expiration dates"
echo -e "   4. Orders: Customers"
echo -e "   5. Orders: Customer orders"
echo -e "   6. Suppliers: Supplier data"
echo -e "   7. Procurement: Procurement plans"
echo -e "   8. Procurement: Purchase orders"
echo -e "   9. Production: Equipment"
echo -e "   10. Production: Production schedules"
echo -e "   11. Production: Quality check templates"
echo -e "   12. Forecasting: Demand forecasts"
echo ""

# Prompt for confirmation
read -p "Continue? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}Aborted.${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}Starting demo data seeding...${NC}"
echo ""

# Function to run a seed script
run_seed() {
    local service=$1
    local script=$2
    local description=$3

    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}▶ ${description}${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━${NC}"

    local script_path="$PROJECT_ROOT/services/$service/scripts/demo/$script"

    if [[ ! -f "$script_path" ]]; then
        echo -e "${YELLOW}⚠  Script not found: $script_path${NC}"
        echo -e "${YELLOW}   Skipping...${NC}"
        echo ""
        return 0
    fi

    # Export PYTHONPATH
    export PYTHONPATH="$PROJECT_ROOT:$PROJECT_ROOT/services/$service:$PYTHONPATH"

    # Run the script
    if python3 "$script_path"; then
        echo -e "${GREEN}✅ ${description} - Completed${NC}"
    else
        echo -e "${RED}❌ ${description} - Failed${NC}"
        echo -e "${RED}   Check logs above for errors${NC}"
        exit 1
    fi

    echo ""
}

# ============================================================================
# Phase 1: Users (Enhanced with Staff Roles)
# ============================================================================
run_seed "auth" "seed_demo_users.py" "Seeding demo users with staff roles"

# ============================================================================
# Phase 2: Tenant Members (Link Staff to Tenants)
# ============================================================================
run_seed "tenant" "seed_demo_tenant_members.py" "Linking staff users to tenants"

# ============================================================================
# Phase 3: Inventory Stock
# ============================================================================
run_seed "inventory" "seed_demo_stock.py" "Seeding inventory stock batches"

# ============================================================================
# Phase 4: Customers & Orders
# ============================================================================
run_seed "orders" "seed_demo_customers.py" "Seeding customer data"
run_seed "orders" "seed_demo_orders.py" "Seeding customer orders"

# ============================================================================
# Phase 5: Procurement (New Architecture)
# ============================================================================
run_seed "procurement" "seed_demo_suppliers.py" "Seeding supplier data"
run_seed "procurement" "seed_demo_procurement_plans.py" "Seeding procurement plans"
run_seed "procurement" "seed_demo_purchase_orders.py" "Seeding purchase orders"

# ============================================================================
# Phase 6: Production Equipment & Schedules
# ============================================================================
run_seed "production" "seed_demo_equipment.py" "Seeding production equipment"
run_seed "production" "seed_demo_production_schedules.py" "Seeding production schedules"

# ============================================================================
# Phase 7: Quality Templates
# ============================================================================
run_seed "production" "seed_demo_quality_templates.py" "Seeding quality check templates"

# ============================================================================
# Phase 8: Forecasting
# ============================================================================
run_seed "forecasting" "seed_demo_forecasts.py" "Seeding demand forecasts"

# ============================================================================
# Summary
# ============================================================================
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}✅ Demo Data Seeding Completed${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "  1. Verify data in base template tenants:"
echo "     - San Pablo: a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6"
echo "     - La Espiga: b2c3d4e5-f6a7-48b9-c0d1-e2f3a4b5c6d7"
echo ""
echo "  2. Test demo session creation:"
echo "     curl -X POST http://localhost:8000/demo/sessions \\"
echo "       -H 'Content-Type: application/json' \\"
echo "       -d '{\"account_type\": \"individual_bakery\"}'"
echo ""
echo "  3. Verify alert generation works"
echo "  4. Check date offset calculations"
echo ""
echo -e "${GREEN}🎉 Demo environment ready for cloning!${NC}"
echo ""
