#!/usr/bin/env python
"""
Remove all problematic reports migrations
Removes all reports migrations that have dependency issues
"""

import os
import sys
import django
from django.core.management import execute_from_command_line
from django.db import connection
from datetime import datetime

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def remove_all_problematic_reports_migrations():
    """Remove all problematic reports migration files"""
    print("=== REMOVING ALL PROBLEMATIC REPORTS MIGRATIONS ===")
    
    # List of all problematic migration files to remove
    problematic_files = [
        'reports/migrations/0002_initial.py',
        'reports/migrations/0007_merge_20250827_0157.py',
        'reports/migrations/0008_alter_notification_related_application_and_more.py',
        'reports/migrations/0009_merge_20250930_0151.py',  # This one depends on 0008
        'reports/migrations/0010_add_database_indexes.py',  # Might also have issues
    ]
    
    for file_path in problematic_files:
        if os.path.exists(file_path):
            try:
                # Backup the file first
                backup_path = f'{file_path}.backup'
                with open(file_path, 'r') as original:
                    with open(backup_path, 'w') as backup:
                        backup.write(original.read())
                print(f"✓ Backed up {file_path} to {backup_path}")
                
                # Remove the problematic file
                os.remove(file_path)
                print(f"✓ Removed problematic migration file: {file_path}")
                
            except Exception as e:
                print(f"⚠ Could not remove migration file {file_path}: {e}")
        else:
            print(f"✓ Migration file not found (good): {file_path}")
    
    # Also remove these migrations from the database
    with connection.cursor() as cursor:
        problematic_migration_names = [
            '0002_initial',
            '0007_merge_20250827_0157',
            '0008_alter_notification_related_application_and_more',
            '0009_merge_20250930_0151',
            '0010_add_database_indexes',
        ]
        
        for migration_name in problematic_migration_names:
            cursor.execute("DELETE FROM django_migrations WHERE app = 'reports' AND name = %s", [migration_name])
            print(f"✓ Removed reports.{migration_name} from database")

def test_migrations():
    """Test that migrations work"""
    print("\n=== TESTING MIGRATIONS ===")
    
    try:
        # Test makemigrations
        print("  Testing makemigrations...")
        execute_from_command_line(['manage.py', 'makemigrations', '--dry-run'])
        print("    ✓ makemigrations works")
        
        # Test migrate
        print("  Testing migrate...")
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("    ✓ migrate works")
        
        return True
        
    except Exception as e:
        print(f"    ✗ Migration test failed: {e}")
        return False

def main():
    """Main fix function"""
    print("=== REMOVE ALL PROBLEMATIC REPORTS MIGRATIONS ===")
    print("Removing all reports migrations that have dependency issues.\n")
    
    try:
        setup_django()
        
        # Remove all problematic reports migrations
        remove_all_problematic_reports_migrations()
        
        # Test migrations
        if test_migrations():
            print("\n=== FIX COMPLETE ===")
            print("✓ All problematic reports migrations have been removed!")
            print("✓ Django migrations are working correctly")
            print("✓ All migration issues are now fixed")
            print("\n🎉 Your application should now work perfectly!")
            print("\n📋 Next steps:")
            print("1. Test your application: python manage.py runserver")
            print("2. Check the portfolio assignment page")
            print("3. Test the enhanced rollover functionality")
            return True
        else:
            print("\n=== FIX PARTIALLY COMPLETE ===")
            print("⚠ All problematic reports migrations have been removed")
            print("⚠ Some issues may remain")
            return False
        
    except Exception as e:
        print(f"\n❌ Fix failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
