#!/usr/bin/env python
"""
Fix Application/Loan Inconsistency Issue
=========================================

This script fixes applications that are marked as 'approved' but have no associated loan.

Usage on production:
    python fix_application_loan_issue.py [application_id]

Or to fix a specific application:
    python fix_application_loan_issue.py c39d3e10-8c36-4db6-a758-aa5963b1bb40

Or to scan and fix all inconsistent applications:
    python fix_application_loan_issue.py --all
"""

import os
import sys
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import LoanApplication, Loan
from django.db.models import Q

def fix_application(app_id):
    """Fix a single application"""
    try:
        app = LoanApplication.objects.get(pk=app_id)
        
        print(f"\n📋 Checking application: {app.application_number}")
        print(f"   Current Status: {app.status}")
        
        if app.status == 'approved':
            # Check if loan actually exists
            try:
                loan = app.loan
                print(f"   ✅ Loan exists: {loan.loan_number}")
                print(f"   No fix needed - data is consistent")
                return False
            except Loan.DoesNotExist:
                print(f"   ❌ INCONSISTENCY: Status is 'approved' but no loan exists!")
                print(f"   🔧 Resetting status to 'pending'...")
                
                app.status = 'pending'
                app.reviewed_by = None
                app.reviewed_at = None
                app.approval_notes = ''
                app.save()
                
                print(f"   ✅ Fixed! Status reset to 'pending'")
                print(f"   You can now approve this application properly")
                return True
        else:
            print(f"   Status is '{app.status}' - no fix needed")
            return False
            
    except LoanApplication.DoesNotExist:
        print(f"❌ Application {app_id} not found!")
        return False


def find_and_fix_all():
    """Find and fix all inconsistent applications"""
    print("\n🔍 Scanning for inconsistent applications...")
    
    # Find all approved applications
    approved_apps = LoanApplication.objects.filter(status='approved')
    print(f"   Found {approved_apps.count()} approved applications")
    
    fixed_count = 0
    inconsistent_apps = []
    
    for app in approved_apps:
        try:
            # Try to access the loan
            loan = app.loan
        except Loan.DoesNotExist:
            # No loan exists - inconsistency!
            inconsistent_apps.append(app)
    
    if not inconsistent_apps:
        print(f"\n✅ No inconsistent applications found - all good!")
        return 0
    
    print(f"\n❌ Found {len(inconsistent_apps)} inconsistent applications:")
    for app in inconsistent_apps:
        print(f"   - {app.application_number} (ID: {app.pk})")
    
    # Ask for confirmation
    print(f"\n⚠️  About to reset {len(inconsistent_apps)} applications to 'pending' status")
    response = input("Continue? (yes/no): ").strip().lower()
    
    if response != 'yes':
        print("❌ Cancelled - no changes made")
        return 0
    
    print(f"\n🔧 Fixing applications...")
    for app in inconsistent_apps:
        print(f"\n   Fixing {app.application_number}...")
        app.status = 'pending'
        app.reviewed_by = None
        app.reviewed_at = None
        app.approval_notes = ''
        app.save()
        fixed_count += 1
        print(f"   ✅ Fixed!")
    
    print(f"\n✅ Successfully fixed {fixed_count} applications")
    return fixed_count


def main():
    print("="*80)
    print(" FIX APPLICATION/LOAN INCONSISTENCY")
    print("="*80)
    
    if len(sys.argv) < 2:
        print("\n❌ Error: Missing argument")
        print("\nUsage:")
        print("  python fix_application_loan_issue.py [application_id]")
        print("  python fix_application_loan_issue.py --all")
        print("\nExample:")
        print("  python fix_application_loan_issue.py c39d3e10-8c36-4db6-a758-aa5963b1bb40")
        sys.exit(1)
    
    if sys.argv[1] == '--all':
        fixed_count = find_and_fix_all()
        print(f"\n{'='*80}")
        print(f" COMPLETE: Fixed {fixed_count} applications")
        print(f"{'='*80}")
    else:
        app_id = sys.argv[1]
        fixed = fix_application(app_id)
        
        if fixed:
            print(f"\n{'='*80}")
            print(f" COMPLETE: Application fixed")
            print(f"{'='*80}")
            print(f"\nNext steps:")
            print(f"1. Go to: https://grazuri.uzuriapps.xyz/loans/applications/{app_id}/")
            print(f"2. Edit the application to fill in missing data if needed")
            print(f"3. Approve the application again")
        else:
            print(f"\n{'='*80}")
            print(f" NO CHANGES MADE")
            print(f"{'='*80}")


if __name__ == '__main__':
    main()
