#!/usr/bin/env python
"""
Fix loans that are missing product associations
This will help display actual product names instead of "Standard Loan"
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan, LoanProduct, LoanApplication
from django.db import transaction

def fix_missing_loan_products():
    """Associate loans with proper loan products"""
    
    print("=" * 60)
    print("Fixing Missing Loan Product Associations")
    print("=" * 60)
    
    # Get all active loans
    all_loans = Loan.objects.filter(is_deleted=False)
    
    # Find loans without applications or products
    loans_without_app = []
    loans_without_product = []
    
    for loan in all_loans:
        if not loan.application:
            loans_without_app.append(loan)
        elif not loan.application.loan_product:
            loans_without_product.append(loan)
    
    print(f"\n📊 Analysis:")
    print(f"   Total active loans: {all_loans.count()}")
    print(f"   Loans without application: {len(loans_without_app)}")
    print(f"   Loans without product: {len(loans_without_product)}")
    
    # Get available loan products
    products = LoanProduct.objects.filter(is_active=True)
    print(f"\n📦 Available Loan Products:")
    for product in products:
        print(f"   - {product.name} ({product.product_type})")
    
    if not products.exists():
        print("\n❌ No loan products found! Create loan products first.")
        return
    
    # Use the first product as default (or you can choose based on loan amount)
    default_product = products.first()
    
    print(f"\n🔧 Fixing loans...")
    print(f"   Using default product: {default_product.name}")
    
    fixed_count = 0
    
    with transaction.atomic():
        # Fix loans without applications
        for loan in loans_without_app[:10]:  # Limit to 10 for safety
            print(f"\n   Creating application for loan {loan.loan_number}...")
            
            # Create a loan application
            app = LoanApplication.objects.create(
                borrower=loan.borrower,
                loan_product=default_product,
                requested_amount=loan.principal_amount,
                purpose="Retroactively created",
                status='approved',
                approved_by=None,
                approved_at=loan.created_at
            )
            
            # Link loan to application
            loan.application = app
            loan.save()
            
            fixed_count += 1
            print(f"   ✅ Fixed: {loan.loan_number}")
        
        # Fix loans with applications but no products
        for loan in loans_without_product[:10]:  # Limit to 10 for safety
            print(f"\n   Adding product to application for loan {loan.loan_number}...")
            
            loan.application.loan_product = default_product
            loan.application.save()
            
            fixed_count += 1
            print(f"   ✅ Fixed: {loan.loan_number}")
    
    print(f"\n{'=' * 60}")
    print(f"✅ Fixed {fixed_count} loans")
    print("=" * 60)
    
    if len(loans_without_app) > 10 or len(loans_without_product) > 10:
        print(f"\n⚠️  Note: Only fixed first 10 loans for safety.")
        print(f"   Run this script again to fix more, or remove the [:10] limit.")

if __name__ == '__main__':
    fix_missing_loan_products()
