#!/usr/bin/env python
"""
Remove problematic migration file
Deletes the reports.0002_initial.py migration file that's causing 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_problematic_migration_file():
    """Remove the problematic migration file"""
    print("=== REMOVING PROBLEMATIC MIGRATION FILE ===")
    
    # Path to the problematic migration file
    migration_file_path = 'reports/migrations/0002_initial.py'
    
    if os.path.exists(migration_file_path):
        try:
            # Backup the file first
            backup_path = f'{migration_file_path}.backup'
            with open(migration_file_path, 'r') as original:
                with open(backup_path, 'w') as backup:
                    backup.write(original.read())
            print(f"✓ Backed up {migration_file_path} to {backup_path}")
            
            # Remove the problematic file
            os.remove(migration_file_path)
            print(f"✓ Removed problematic migration file: {migration_file_path}")
            
        except Exception as e:
            print(f"⚠ Could not remove migration file: {e}")
    else:
        print(f"⚠ Migration file not found: {migration_file_path}")
    
    # Also check for other problematic migration files
    problematic_files = [
        'reports/migrations/0007_merge_20250827_0157.py',
        'reports/migrations/0008_alter_notification_related_application_and_more.py'
    ]
    
    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}")

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 PROBLEMATIC MIGRATION FILE ===")
    print("Deleting the reports.0002_initial.py migration file that's causing issues.\n")
    
    try:
        setup_django()
        
        # Remove problematic migration file
        remove_problematic_migration_file()
        
        # Test migrations
        if test_migrations():
            print("\n=== FIX COMPLETE ===")
            print("✓ Problematic migration file has 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("⚠ Problematic migration file has 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)
