"""
Quick script to seed test loan data for local development.
Run: python seed_test_loans.py
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from decimal import Decimal
from datetime import date, timedelta
from django.utils import timezone
from users.models import CustomUser, Branch
from loans.models import LoanProduct, LoanApplication, Loan, Repayment

print("Seeding test loans...")

# Get some borrowers
borrowers = list(CustomUser.objects.filter(role='borrower', status='active')[:20])
if not borrowers:
    print("No borrowers found. Create some clients first.")
    exit()

# Get or create a loan product
product = LoanProduct.objects.filter(is_active=True).first()
if not product:
    print("No active loan products found. Create one first.")
    exit()

print(f"Using product: {product.name}")
print(f"Found {len(borrowers)} borrowers")

created = 0
for i, borrower in enumerate(borrowers):
    # Skip if borrower already has a loan
    if LoanApplication.objects.filter(borrower=borrower).exists():
        continue

    principal = Decimal('50000') + (i * Decimal('10000'))
    interest = principal * Decimal('0.15')
    processing_fee = principal * Decimal('0.02')
    total = principal + interest + processing_fee

    # Create application
    app = LoanApplication.objects.create(
        borrower=borrower,
        loan_product=product,
        requested_amount=principal,
        interest_amount=interest,
        processing_fee_amount=processing_fee,
        total_amount=total,
        repayment_method='monthly',
        requested_duration=12,
        status='approved',
    )

    # Determine status - mix of active, paid, defaulted
    if i % 5 == 4:
        status = 'defaulted'
    elif i % 4 == 3:
        status = 'paid'
    else:
        status = 'active'

    disbursement_date = timezone.now() - timedelta(days=30 * (i % 6 + 1))
    due_date = disbursement_date + timedelta(days=365)

    loan = Loan.objects.create(
        application=app,
        borrower=borrower,
        loan_number=f'LN{2024000 + i + 1:06d}',
        principal_amount=principal,
        interest_amount=interest,
        processing_fee=processing_fee,
        total_amount=total,
        disbursement_date=disbursement_date,
        due_date=due_date.date() if hasattr(due_date, 'date') else due_date,
        duration_days=365,
        status=status,
        is_deleted=False,
        is_rolled_over=False,
    )

    # Add some repayments for active/paid loans
    if status in ('active', 'paid'):
        months_paid = 6 if status == 'active' else 12
        monthly_payment = total / 12
        for m in range(months_paid):
            pay_date = disbursement_date + timedelta(days=30 * (m + 1))
            Repayment.objects.create(
                loan=loan,
                amount=monthly_payment,
                payment_date=pay_date,
                payment_method='mpesa',
            )
        # Update cached amount_paid
        from django.db.models import Sum
        paid = Repayment.objects.filter(loan=loan).aggregate(t=Sum('amount'))['t'] or Decimal('0')
        Loan.objects.filter(id=loan.id).update(_amount_paid_cache=paid)

    created += 1
    print(f"  Created loan {loan.loan_number} for {borrower.first_name} {borrower.last_name} [{status}]")

print(f"\nDone. Created {created} loans.")
print("Refresh the reports dashboard to see data.")
