#!/usr/bin/env python
"""
Fix processing fees report to show actual data
This script updates the enhanced_processing_fees_report view to properly filter by date
"""
import os
import sys
import django

# Setup Django
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from django.db.models import Sum, Count
from django.utils import timezone
from datetime import timedelta
from decimal import Decimal

print("=" * 80)
print("PROCESSING FEES REPORT DIAGNOSTIC")
print("=" * 80)

# Check all loans
all_loans = Loan.objects.filter(is_deleted=False)
print(f"\n1. Total loans (not deleted): {all_loans.count()}")

# Check active loans
active_loans = all_loans.filter(status='active')
print(f"2. Active loans: {active_loans.count()}")

# Check loans with processing fees
loans_with_fees = all_loans.exclude(processing_fee__isnull=True).exclude(processing_fee=0)
print(f"3. Loans with processing fees > 0: {loans_with_fees.count()}")

# Calculate total fees
total_fees = all_loans.aggregate(total=Sum('processing_fee'))['total'] or Decimal('0.00')
print(f"4. Total processing fees (all loans): KSh {total_fees:,.2f}")

# Check by status
print("\n" + "=" * 80)
print("BREAKDOWN BY STATUS")
print("=" * 80)
status_breakdown = all_loans.values('status').annotate(
    count=Count('id'),
    total_fees=Sum('processing_fee')
).order_by('-count')

for item in status_breakdown:
    print(f"  {item['status']}: {item['count']} loans, KSh {item['total_fees'] or 0:,.2f} in fees")

# Check recent loans
print("\n" + "=" * 80)
print("RECENT LOANS (Last 30 days)")
print("=" * 80)
thirty_days_ago = timezone.now() - timedelta(days=30)
recent_loans = all_loans.filter(created_at__gte=thirty_days_ago)
recent_fees = recent_loans.aggregate(total=Sum('processing_fee'))['total'] or Decimal('0.00')
print(f"  Count: {recent_loans.count()}")
print(f"  Total Processing Fees: KSh {recent_fees:,.2f}")

# Show sample loans
print("\n" + "=" * 80)
print("SAMPLE LOANS (First 5)")
print("=" * 80)
for loan in all_loans[:5]:
    print(f"\n  Loan: {loan.loan_number or loan.id}")
    print(f"    Borrower: {loan.borrower.first_name} {loan.borrower.last_name}")
    print(f"    Principal: KSh {loan.principal_amount:,.2f}")
    print(f"    Processing Fee: KSh {loan.processing_fee or 0:,.2f}")
    print(f"    Status: {loan.status}")
    print(f"    Created: {loan.created_at}")

print("\n" + "=" * 80)
print("RECOMMENDATIONS")
print("=" * 80)

if all_loans.count() == 0:
    print("  ⚠️  No loans found in database")
    print("  → Create test loans with processing fees")
elif loans_with_fees.count() == 0:
    print("  ⚠️  No loans have processing fees set")
    print("  → Update existing loans to include processing fees")
elif active_loans.count() == 0:
    print("  ⚠️  No active loans found")
    print("  → The report only shows active loans")
    print("  → Consider showing all loans or filtering by date instead")
else:
    print("  ✅ Data looks good!")
    print(f"  → {active_loans.count()} active loans with KSh {active_loans.aggregate(total=Sum('processing_fee'))['total'] or 0:,.2f} in fees")

print("\n" + "=" * 80)
