#!/usr/bin/env python
"""
Fix loans migration dependency issue
Specifically fixes loans.0018_add_rollover_date_field dependency on loans.0017_merge_20251002_0238
"""

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 analyze_loans_migrations():
    """Analyze loans app migrations"""
    print("=== Analyzing Loans Migrations ===")
    
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT name, applied 
            FROM django_migrations 
            WHERE app = 'loans' 
            ORDER BY id
        """)
        loans_migrations = cursor.fetchall()
        
        print("Current loans migrations:")
        for name, applied in loans_migrations:
            status = "✓" if applied else "✗"
            print(f"  {status} {name}")
        
        # Check for the problematic migrations
        cursor.execute("""
            SELECT COUNT(*) 
            FROM django_migrations 
            WHERE app = 'loans' AND name = '0017_merge_20251002_0238'
        """)
        has_0017 = cursor.fetchone()[0] > 0
        
        cursor.execute("""
            SELECT COUNT(*) 
            FROM django_migrations 
            WHERE app = 'loans' AND name = '0018_add_rollover_date_field'
        """)
        has_0018 = cursor.fetchone()[0] > 0
        
        print(f"\nMigration status:")
        print(f"  0017_merge_20251002_0238: {'✓' if has_0017 else '✗'}")
        print(f"  0018_add_rollover_date_field: {'✓' if has_0018 else '✗'}")
        
        return has_0017, has_0018

def fix_loans_migration_dependency():
    """Fix the loans migration dependency issue"""
    print("\n=== Fixing Loans Migration Dependency ===")
    
    with connection.cursor() as cursor:
        # Remove the problematic migration
        cursor.execute("""
            DELETE FROM django_migrations 
            WHERE app = 'loans' AND name = '0018_add_rollover_date_field'
        """)
        print("  Removed loans.0018_add_rollover_date_field")
        
        # Check if 0017 exists, if not add it
        cursor.execute("""
            SELECT COUNT(*) 
            FROM django_migrations 
            WHERE app = 'loans' AND name = '0017_merge_20251002_0238'
        """)
        has_0017 = cursor.fetchone()[0] > 0
        
        if not has_0017:
            cursor.execute("""
                INSERT INTO django_migrations (app, name, applied) 
                VALUES ('loans', '0017_merge_20251002_0238', %s)
            """, [datetime.now()])
            print("  Added loans.0017_merge_20251002_0238")
        else:
            print("  loans.0017_merge_20251002_0238 already exists")
        
        # Re-add 0018 after 0017
        cursor.execute("""
            INSERT INTO django_migrations (app, name, applied) 
            VALUES ('loans', '0018_add_rollover_date_field', %s)
        """, [datetime.now()])
        print("  Re-added loans.0018_add_rollover_date_field")

def ensure_rollover_date_column():
    """Ensure rollover_date column exists"""
    print("\n=== Ensuring 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
        
        # Check if column exists
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.columns 
            WHERE table_schema = DATABASE() 
            AND table_name = 'rollover_requests' 
            AND column_name = 'rollover_date'
        """)
        column_exists = cursor.fetchone()[0] > 0
        
        if not column_exists:
            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
        else:
            print("  ✓ rollover_date column already exists")
        
        return True

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("=== Loans Migration Dependency Fix ===")
    print("This script fixes the loans.0018 dependency on loans.0017 issue.\n")
    
    try:
        # Setup Django
        setup_django()
        
        # Analyze current state
        has_0017, has_0018 = analyze_loans_migrations()
        
        # Fix the dependency issue
        fix_loans_migration_dependency()
        
        # Ensure rollover_date column exists
        ensure_rollover_date_column()
        
        # Test migrations
        if test_migrations():
            print("\n=== Fix Complete ===")
            print("✓ Loans migration dependency issue has been resolved!")
            print("✓ Django migrations are now working correctly")
            print("✓ rollover_date column is available")
            print("✓ Enhanced rollover functionality is ready")
            return True
        else:
            print("\n=== Fix Partially Complete ===")
            print("⚠ Migration dependency has been fixed")
            print("⚠ Some migration issues may remain")
            print("⚠ The rollover_date column should still be available")
            return False
        
    except Exception as e:
        print(f"\n✗ Fix failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

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