"""
Update Mwamba product to 10% monthly interest and create a sample loan for 3 months.

This script demonstrates that interest is calculated as:
- Month 1: 10% of principal
- Month 2: 10% of principal  
- Month 3: 10% of principal
Total Interest = 30% of principal (10% × 3 months)
"""

import os
import django
import sys
from decimal import Decimal

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

from django.contrib.auth import get_user_model
from loans.models import LoanProduct, LoanApplication, Loan
from django.utils import timezone
from datetime import timedelta

User = get_user_model()

def update_mwamba_and_create_loan():
    """Update Mwamba product to 10% interest and create a sample loan"""
    
    print("=" * 80)
    print("UPDATING MWAMBA PRODUCT AND CREATING SAMPLE LOAN")
    print("=" * 80)
    
    # Step 1: Update Mwamba loan product to 10% interest
    print("\n1. Updating Mwamba loan product to 10% monthly interest...")
    try:
        mwamba_product = LoanProduct.objects.get(product_type='mwamba')
        print(f"   Found Mwamba product: {mwamba_product.name}")
        print(f"   Current interest rate: {mwamba_product.interest_rate}%")
        
        # Update to 10%
        mwamba_product.interest_rate = Decimal('10.00')
        mwamba_product.save()
        
        print(f"   ✓ Updated interest rate to: {mwamba_product.interest_rate}%")
    except LoanProduct.DoesNotExist:
        print("   Creating Mwamba product with 10% interest...")
        mwamba_product = LoanProduct.objects.create(
            name="Mwamba Loan",
            product_type='mwamba',
            description="Medium-term loan product with 10% monthly interest",
            min_amount=Decimal('50000.00'),
            max_amount=Decimal('500000.00'),
            interest_rate=Decimal('10.00'),  # 10% monthly
            processing_fee=Decimal('5.00'),  # 5% processing fee
            late_payment_penalty=Decimal('5.00'),
            duration_months=3,
            min_duration=30,
            max_duration=365,
            available_repayment_methods=['monthly'],
            requires_guarantor=True,
            requires_collateral=False,
            is_active=True
        )
        print(f"   ✓ Created Mwamba product: {mwamba_product.name}")
    
    # Display product details
    print(f"\n   Product Details:")
    print(f"   - Interest Rate: {mwamba_product.interest_rate}% per month")
    print(f"   - Processing Fee: {mwamba_product.processing_fee}%")
    print(f"   - Duration: {mwamba_product.duration_months} months")
    
    # Step 2: Get or create a borrower
    print("\n2. Getting borrower...")
    borrower = User.objects.filter(role='borrower', is_active=True).first()
    
    if not borrower:
        print("   No borrower found. Creating sample borrower...")
        borrower = User.objects.create_user(
            username='mwamba_borrower',
            email='mwamba@example.com',
            password='password123',
            first_name='John',
            last_name='Mwamba',
            phone_number='+254712345678',
            role='borrower',
            is_active=True,
            status='active',
            monthly_income=Decimal('80000.00')
        )
        print(f"   ✓ Created borrower: {borrower.get_full_name()}")
    else:
        print(f"   ✓ Using borrower: {borrower.get_full_name()}")
    
    # Step 3: Define loan parameters
    principal = Decimal('100000.00')  # KES 100,000
    duration_days = 90  # 3 months (90 days)
    months = Decimal('3')  # 3 months
    
    print(f"\n3. Loan Parameters:")
    print(f"   - Principal Amount: KES {principal:,.2f}")
    print(f"   - Duration: {duration_days} days ({months} months)")
    print(f"   - Interest Rate: {mwamba_product.interest_rate}% per month")
    
    # Step 4: Calculate loan amounts
    print(f"\n4. Calculating Loan Amounts:")
    
    # Interest calculation: 10% per month × 3 months
    interest_rate_decimal = mwamba_product.interest_rate / Decimal('100')
    interest_per_month = principal * interest_rate_decimal
    total_interest = interest_per_month * months
    
    print(f"\n   Interest Calculation:")
    print(f"   - Month 1: {mwamba_product.interest_rate}% of KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"   - Month 2: {mwamba_product.interest_rate}% of KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"   - Month 3: {mwamba_product.interest_rate}% of KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"   - Total Interest: KES {total_interest:,.2f}")
    
    # Processing fee calculation (one-time for Mwamba)
    processing_fee_rate = mwamba_product.processing_fee / Decimal('100')
    processing_fee = principal * processing_fee_rate
    
    print(f"\n   Processing Fee Calculation:")
    print(f"   - {mwamba_product.processing_fee}% of KES {principal:,.2f} = KES {processing_fee:,.2f}")
    
    # Total amount
    total_amount = principal + total_interest + processing_fee
    
    print(f"\n   Total Loan Amount:")
    print(f"   - Principal:        KES {principal:,.2f}")
    print(f"   - Interest (3 mo):  KES {total_interest:,.2f}")
    print(f"   - Processing Fee:   KES {processing_fee:,.2f}")
    print(f"   - TOTAL:            KES {total_amount:,.2f}")
    
    # Step 5: Create loan application
    print(f"\n5. Creating Loan Application...")
    
    application = LoanApplication.objects.create(
        borrower=borrower,
        loan_product=mwamba_product,
        requested_amount=principal,
        requested_duration=duration_days,
        purpose="Business expansion - sample Mwamba loan with 10% monthly interest",
        repayment_method='monthly',
        interest_amount=total_interest,
        processing_fee_amount=processing_fee,
        total_amount=total_amount,
        status='pending'
    )
    
    print(f"   ✓ Application created: {application.application_number}")
    
    # Step 6: Approve and create loan
    print(f"\n6. Approving Application and Creating Loan...")
    
    # Get an admin user to approve
    admin = User.objects.filter(role='admin').first()
    if not admin:
        admin = User.objects.filter(is_superuser=True).first()
    
    if not admin:
        print("   Creating admin user for approval...")
        admin = User.objects.create_superuser(
            username='admin',
            email='admin@example.com',
            password='admin123',
            first_name='Admin',
            last_name='User'
        )
    
    # Approve the application
    loan = application.approve(
        approved_by=admin,
        notes="Sample Mwamba loan for testing 10% monthly interest calculation",
        disbursement_date=timezone.now()
    )
    
    print(f"   ✓ Loan created: {loan.loan_number}")
    print(f"   ✓ Status: {loan.status}")
    
    # Step 7: Display final loan details
    print(f"\n" + "=" * 80)
    print("LOAN CREATED SUCCESSFULLY")
    print("=" * 80)
    
    print(f"\nLoan Number: {loan.loan_number}")
    print(f"Borrower: {loan.borrower.get_full_name()}")
    print(f"Product: {mwamba_product.name}")
    print(f"\nLoan Details:")
    print(f"  Principal Amount:     KES {loan.principal_amount:,.2f}")
    print(f"  Interest Amount:      KES {loan.interest_amount:,.2f}")
    print(f"  Processing Fee:       KES {loan.processing_fee:,.2f}")
    print(f"  Total Amount:         KES {loan.total_amount:,.2f}")
    print(f"\nDates:")
    print(f"  Disbursement Date:    {loan.disbursement_date.strftime('%Y-%m-%d')}")
    print(f"  Due Date:             {loan.due_date.strftime('%Y-%m-%d')}")
    print(f"  Duration:             {loan.duration_days} days")
    
    print(f"\nInterest Breakdown (10% per month):")
    print(f"  Month 1: 10% × KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"  Month 2: 10% × KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"  Month 3: 10% × KES {principal:,.2f} = KES {interest_per_month:,.2f}")
    print(f"  Total:   30% × KES {principal:,.2f} = KES {total_interest:,.2f}")
    
    print(f"\nPayment Status:")
    print(f"  Amount Paid:          KES {loan.amount_paid:,.2f}")
    print(f"  Outstanding:          KES {loan.outstanding_amount:,.2f}")
    print(f"  Status:               {loan.status}")
    
    print(f"\n" + "=" * 80)
    print("VERIFICATION")
    print("=" * 80)
    
    # Verify the calculation
    expected_interest = principal * Decimal('0.10') * Decimal('3')
    actual_interest = loan.interest_amount
    
    print(f"\nInterest Calculation Verification:")
    print(f"  Expected: KES {expected_interest:,.2f} (10% × 3 months)")
    print(f"  Actual:   KES {actual_interest:,.2f}")
    print(f"  Match:    {'✓ YES' if expected_interest == actual_interest else '✗ NO'}")
    
    if expected_interest == actual_interest:
        print(f"\n✓ SUCCESS: Interest is correctly calculated as 10% per month for 3 months!")
        print(f"✓ This means:")
        print(f"  - Each month charges 10% of the principal")
        print(f"  - Total interest = 10% + 10% + 10% = 30% of principal")
        print(f"  - NOT compound interest (which would be 33.1%)")
    else:
        print(f"\n✗ WARNING: Interest calculation mismatch!")
        print(f"  Expected: {expected_interest}")
        print(f"  Got: {actual_interest}")
    
    return loan

if __name__ == '__main__':
    try:
        loan = update_mwamba_and_create_loan()
        print(f"\n✓ Script completed successfully!")
        print(f"✓ Loan ID: {loan.id}")
        print(f"✓ Loan Number: {loan.loan_number}")
    except Exception as e:
        print(f"\n✗ Error: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
