#!/usr/bin/env python
"""
Complete fix for all loans migration dependencies
This script fixes the entire loans migration chain by removing and re-adding all migrations in correct order
"""

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 get_current_migrations():
    """Get current migration status"""
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT app, name, applied 
            FROM django_migrations 
            WHERE app = 'loans' 
            ORDER BY app, name
        """)
        return cursor.fetchall()

def reset_all_loans_migrations():
    """Reset all loans migrations to fix the dependency chain"""
    print("=== Resetting All Loans Migrations ===")
    
    with connection.cursor() as cursor:
        # Remove ALL loans migrations
        cursor.execute("DELETE FROM django_migrations WHERE app = 'loans'")
        print("  Removed all loans migrations")
        
        # Re-add migrations in the correct dependency order
        # This is the correct order based on the actual migration files
        loans_migrations = [
            '0001_initial',
            '0002_initial', 
            '0003_loanproduct_available_repayment_methods_and_more',
            '0004_loanapplication_repayment_method',
            '0005_loanproduct_max_rollover_count_and_more',
            '0002_add_boost_plus_product',
            '0006_merge_20250822_2013',
            '0002_add_penalty_charges',
            '0007_merge_20250822_2040',
            '0008_auto_20250823_0823',
            '0009_add_duration_options_and_payment_date',
            '0010_loan_deleted_at_loan_deleted_by_loan_is_deleted',
            '0011_loan_registration_fee_and_more',
            '0012_remove_registration_fee_fields',
            '0014_merge_20250827_0154',
            '0015_alter_loanproduct_late_payment_penalty_and_more',
            '0002_enhance_rollover_request',  # This comes before 0016
            '0016_enhance_mpesa_transaction',  # This depends on 0015
            '0017_merge_20251002_0238',  # This depends on both 0002_enhance_rollover_request and 0016
            '0018_add_rollover_date_field',  # This depends on 0017
        ]
        
        print("  Re-adding loans migrations in correct dependency order:")
        for migration_name in loans_migrations:
            cursor.execute("""
                INSERT INTO django_migrations (app, name, applied) 
                VALUES ('loans', %s, %s)
            """, [migration_name, datetime.now()])
            print(f"    Added loans.{migration_name}")

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("=== Complete Loans Migration Dependency Fix ===")
    print("This script resets all loans migrations to fix the entire dependency chain.\n")
    
    try:
        # Setup Django
        setup_django()
        
        # Show current state
        print("Current loans migrations:")
        current_migrations = get_current_migrations()
        for app, name, applied in current_migrations:
            status = "✓" if applied else "✗"
            print(f"  {status} {app}.{name}")
        
        # Reset all loans migrations
        reset_all_loans_migrations()
        
        # Ensure rollover_date column exists
        ensure_rollover_date_column()
        
        # Test migrations
        if test_migrations():
            print("\n=== Fix Complete ===")
            print("✓ All loans migration dependencies have 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("⚠ Loans migrations have 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✗ Fix failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

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