#!/usr/bin/env python
"""
Complete fix for all loans migration dependencies
Fixes the entire loans migration chain
"""

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 get_loans_migrations():
    """Get all loans migrations from database"""
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT name, applied 
            FROM django_migrations 
            WHERE app = 'loans' 
            ORDER BY id
        """)
        return cursor.fetchall()

def analyze_loans_migrations():
    """Analyze all loans migrations and identify issues"""
    print("=== Analyzing All Loans Migrations ===")
    
    migrations = get_loans_migrations()
    
    print("Current loans migrations:")
    for name, applied in migrations:
        status = "✓" if applied else "✗"
        print(f"  {status} {name}")
    
    # Check for problematic migrations
    problematic_migrations = [
        '0002_enhance_rollover_request',
        '0017_merge_20251002_0238',
        '0018_add_rollover_date_field'
    ]
    
    print(f"\nChecking problematic migrations:")
    for migration_name in problematic_migrations:
        exists = any(name == migration_name for name, applied in migrations)
        print(f"  {migration_name}: {'✓' if exists else '✗'}")
    
    return migrations

def reset_loans_migrations():
    """Reset all loans migrations to fix dependencies"""
    print("\n=== Resetting 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 correct order
        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 should come before 0017
            '0017_merge_20251002_0238',
            '0018_add_rollover_date_field',
        ]
        
        print("  Re-adding loans migrations in correct 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 Fix ===")
    print("This script resets all loans migrations to fix dependency issues.\n")
    
    try:
        # Setup Django
        setup_django()
        
        # Analyze current state
        analyze_loans_migrations()
        
        # Reset loans migrations
        reset_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)
