#!/usr/bin/env python
"""
Nuclear option: Reset migration history completely
Use this if the comprehensive fix doesn't work
"""

import os
import sys
import django
from django.core.management import execute_from_command_line
from django.db import connection, transaction
from datetime import datetime

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def backup_migration_history():
    """Backup current migration history"""
    print("=== Backing Up Migration History ===")
    
    with connection.cursor() as cursor:
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS django_migrations_backup AS 
            SELECT * FROM django_migrations
        """)
        print("✓ Migration history backed up to django_migrations_backup")

def reset_migration_history():
    """Reset migration history completely"""
    print("\n=== Resetting Migration History ===")
    
    with connection.cursor() as cursor:
        # Clear all migration records
        cursor.execute("DELETE FROM django_migrations")
        print("✓ Cleared all migration records")
        
        # Add core Django migrations
        core_migrations = [
            ('contenttypes', '0001_initial'),
            ('auth', '0001_initial'),
            ('admin', '0001_initial'),
            ('admin', '0002_logentry_remove_auto_add'),
            ('admin', '0003_logentry_add_action_flag_choices'),
            ('sessions', '0001_initial'),
        ]
        
        for app, name in core_migrations:
            cursor.execute("""
                INSERT INTO django_migrations (app, name, applied) 
                VALUES (%s, %s, %s)
            """, [app, name, datetime.now()])
        
        print("✓ Added core Django migrations")
        
        # Add users migrations in correct order
        users_migrations = [
            '0001_initial',
            '0002_auto_20240101_0001',
            '0003_auto_20240101_0002',
            '0004_auto_20240101_0003',
            '0005_auto_20240101_0004',
            '0006_auto_20240101_0005',
            '0007_auto_20240101_0006',
            '0008_auto_20240101_0007',
            '0009_auto_20240101_0008',
            '0010_add_enhanced_permissions',
            '0011_manual_add_is_default',
            '0012_branch',
        ]
        
        for migration_name in users_migrations:
            cursor.execute("""
                INSERT INTO django_migrations (app, name, applied) 
                VALUES ('users', %s, %s)
            """, [migration_name, datetime.now()])
        
        print("✓ Added users migrations in correct order")
        
        # Add loans migrations
        loans_migrations = [
            '0001_initial',
            '0002_auto_20240101_0001',
            '0003_auto_20240101_0002',
            '0004_auto_20240101_0003',
            '0005_auto_20240101_0004',
            '0006_auto_20240101_0005',
            '0007_auto_20240101_0006',
            '0008_auto_20240101_0007',
            '0009_auto_20240101_0008',
            '0010_auto_20240101_0009',
            '0011_auto_20240101_0010',
            '0012_auto_20240101_0011',
            '0013_auto_20240101_0012',
            '0014_auto_20240101_0013',
            '0015_auto_20240101_0014',
            '0016_auto_20240101_0015',
            '0017_auto_20240101_0016',
            '0018_add_rollover_date_field',
        ]
        
        for migration_name in loans_migrations:
            cursor.execute("""
                INSERT INTO django_migrations (app, name, applied) 
                VALUES ('loans', %s, %s)
            """, [migration_name, datetime.now()])
        
        print("✓ Added loans migrations in correct order")

def add_rollover_date_column():
    """Add rollover_date column"""
    print("\n=== Adding rollover_date Column ===")
    
    with connection.cursor() as cursor:
        # Check if table exists
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.tables 
            WHERE table_schema = DATABASE() 
            AND table_name = 'rollover_requests'
        """)
        table_exists = cursor.fetchone()[0] > 0
        
        if not table_exists:
            print("  rollover_requests table does not exist - skipping")
            return True
        
        # Add column
        try:
            cursor.execute("""
                ALTER TABLE rollover_requests 
                ADD COLUMN rollover_date DATE NULL 
                COMMENT 'Preferred rollover date'
            """)
            print("  ✓ Added rollover_date column")
        except Exception as e:
            if "Duplicate column name" in str(e):
                print("  ✓ rollover_date column already exists")
            else:
                print(f"  ✗ Error adding column: {e}")
                return False
        
        return True

def test_migrations():
    """Test that migrations work"""
    print("\n=== Testing Migrations ===")
    
    try:
        # Test makemigrations
        execute_from_command_line(['manage.py', 'makemigrations', '--dry-run'])
        print("✓ makemigrations works")
        
        # Test 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 reset function"""
    print("=== Nuclear Migration Reset ===")
    print("WARNING: This will completely reset your migration history!")
    print("This is a last resort if other fixes don't work.\n")
    
    try:
        # Setup Django
        setup_django()
        
        # Backup current state
        backup_migration_history()
        
        # Reset migration history
        reset_migration_history()
        
        # Add rollover_date column
        add_rollover_date_column()
        
        # Test migrations
        if test_migrations():
            print("\n=== Reset Complete ===")
            print("✓ Migration history has been reset")
            print("✓ All migrations are now working")
            print("✓ rollover_date column has been added")
            print("✓ Enhanced rollover functionality is ready")
            return True
        else:
            print("\n=== Reset Partially Complete ===")
            print("⚠ Migration history has been reset")
            print("⚠ Some migration issues may remain")
            print("⚠ The rollover_date column should still be available")
            return False
        
    except Exception as e:
        print(f"\n✗ Reset failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

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