#!/usr/bin/env python3
"""
Main migration runner - Execute all migration steps in sequence
"""
import os
import sys
import subprocess
import time
from datetime import datetime

def run_script(script_name):
    """Run a migration script and return success status"""
    print(f"\n{'='*60}")
    print(f"🚀 Running: {script_name}")
    print(f"{'='*60}")

    script_path = f"/home/whgoparts/public_html/whims-dev/migration-dev/scripts/{script_name}"

    try:
        result = subprocess.run(
            [sys.executable, script_path],
            capture_output=True,
            text=True,
            check=False
        )

        if result.returncode == 0:
            print(f"✅ {script_name} completed successfully")
            if result.stdout:
                print(result.stdout)
            return True
        else:
            print(f"❌ {script_name} failed with error:")
            if result.stderr:
                print(result.stderr)
            if result.stdout:
                print(result.stdout)
            return False

    except Exception as e:
        print(f"❌ Error running {script_name}: {str(e)}")
        return False

def main():
    """Main migration runner"""
    print("\n" + "="*60)
    print("   FINALE INVENTORY TO WHIMS MIGRATION")
    print("="*60)
    print(f"\nStarting migration at: {datetime.now()}")

    # Migration scripts in order
    scripts = [
        ("01_backup_database.py", "Database Backup", True),
        ("02_cleanup_database.py", "Database Cleanup", True),
        ("10_import_active_products.py", "Product Import (Active Products with Categories)", True),
        ("04_migrate_purchase_orders.py", "Purchase Order Migration", True),
        ("05_migrate_stock_inventory.py", "Stock Inventory Migration", True),
        ("06_migrate_stock_history.py", "Stock History Migration", True),
        ("07_validate_migration.py", "Migration Validation", False)
    ]

    results = []
    failed_critical = False

    for script_file, description, is_critical in scripts:
        print(f"\n📋 Step: {description}")

        # Check if script exists
        if not os.path.exists(f"/home/whgoparts/public_html/whims-dev/migration-dev/scripts/{script_file}"):
            if script_file == "07_validate_migration.py":
                print(f"   ⚠️ Validation script not found, skipping...")
                continue
            else:
                print(f"   ❌ Script {script_file} not found!")
                if is_critical:
                    failed_critical = True
                    break
                continue

        # Run the script
        success = run_script(script_file)
        results.append((description, success))

        if not success and is_critical:
            print(f"\n❌ Critical step '{description}' failed!")
            print("Migration halted to prevent data corruption.")
            failed_critical = True
            break

        # Small delay between scripts
        if success:
            time.sleep(1)

    # Print summary
    print("\n" + "="*60)
    print("   MIGRATION SUMMARY")
    print("="*60)

    for description, success in results:
        status = "✅ Success" if success else "❌ Failed"
        print(f"{status}: {description}")

    if failed_critical:
        print("\n⚠️  MIGRATION FAILED - Critical step encountered an error")
        print("Please check the logs and fix the issue before re-running.")
        print("\nTo restore from backup, run:")
        print("mysql -u[user] -p[password] whims_dev < backup_whims_dev_[timestamp].sql")
        sys.exit(1)
    else:
        print("\n✅ MIGRATION COMPLETED SUCCESSFULLY!")
        print(f"Finished at: {datetime.now()}")

        print("\n📊 Next Steps:")
        print("1. Review the migration results")
        print("2. Test the application with migrated data")
        print("3. Check for any data inconsistencies")
        print("4. Run validation reports if needed")

if __name__ == "__main__":
    # Check for --yes flag to skip confirmation
    skip_confirm = '--yes' in sys.argv or '-y' in sys.argv

    if not skip_confirm:
        print("\n⚠️  WARNING: This will clear all existing data and import from Finale!")
        print("Make sure you have reviewed the migration plan.")

        response = input("\nDo you want to proceed with the migration? (yes/no): ")
        if response.lower() != 'yes':
            print("Migration cancelled.")
            sys.exit(0)

    main()