#!/usr/bin/env python3
"""
Complete migration script for soft deletion functionality.
Runs all individual migration scripts in the correct order and verifies the results.
"""

import subprocess
import sys
from pathlib import Path

def run_migration_script(script_name):
    """Run a migration script and return success status."""
    
    script_path = Path(__file__).parent / script_name
    
    if not script_path.exists():
        print(f"ERROR: Migration script {script_name} not found")
        return False
    
    try:
        print(f"\n{'='*50}")
        print(f"Running {script_name}")
        print(f"{'='*50}")
        
        result = subprocess.run([sys.executable, str(script_path)], 
                              capture_output=True, text=True, cwd=Path(__file__).parent)
        
        print(result.stdout)
        
        if result.stderr:
            print("STDERR:", result.stderr)
        
        if result.returncode == 0:
            print(f"SUCCESS: {script_name} completed successfully")
            return True
        else:
            print(f"ERROR: {script_name} failed with exit code {result.returncode}")
            return False
            
    except Exception as e:
        print(f"ERROR: Error running {script_name}: {e}")
        return False

def main():
    """Run all soft deletion migration scripts."""
    
    print("=== Complete Soft Deletion Migration ===")
    print("This will add soft deletion columns to all relevant tables")
    
    # Migration scripts in order
    migration_scripts = [
        "migrate_soft_deletion_shots.py",
        "migrate_soft_deletion_assets.py", 
        "migrate_soft_deletion_tasks.py",
        "migrate_soft_deletion_related_tables.py"
    ]
    
    all_successful = True
    
    for script in migration_scripts:
        success = run_migration_script(script)
        if not success:
            all_successful = False
            print(f"\nERROR: Migration failed at {script}")
            break
    
    if all_successful:
        print(f"\n{'='*50}")
        print("SUCCESS: ALL MIGRATIONS COMPLETED SUCCESSFULLY!")
        print("SUCCESS: Soft deletion columns added to all tables:")
        print("  - shots (deleted_at, deleted_by)")
        print("  - assets (deleted_at, deleted_by)")
        print("  - tasks (deleted_at, deleted_by)")
        print("  - submissions (deleted_at, deleted_by)")
        print("  - task_attachments (deleted_at, deleted_by)")
        print("  - production_notes (deleted_at, deleted_by)")
        print("  - reviews (deleted_at, deleted_by)")
        print("SUCCESS: Partial indexes created for efficient querying")
        print(f"{'='*50}")
        return True
    else:
        print(f"\n{'='*50}")
        print("ERROR: MIGRATION FAILED!")
        print("Please check the error messages above and fix any issues.")
        print(f"{'='*50}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)