"""
Test script to verify branch filtering in reports dashboard
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import Branch, CustomUser
from loans.models import Loan
from django.db.models import Count, Sum

print("=" * 80)
print("BRANCH FILTERING TEST")
print("=" * 80)

# Get all branches
branches = Branch.objects.filter(is_active=True)
print(f"\n✓ Total Active Branches: {branches.count()}")
for branch in branches:
    print(f"  - {branch.name} (ID: {branch.id})")

# Get loans per branch
print("\n" + "=" * 80)
print("LOANS PER BRANCH")
print("=" * 80)

for branch in branches:
    loans = Loan.objects.filter(borrower__branch=branch)
    active_loans = loans.filter(status='active')
    total_portfolio = active_loans.aggregate(total=Sum('principal_amount'))['total'] or 0
    
    print(f"\n{branch.name}:")
    print(f"  - Total Loans: {loans.count()}")
    print(f"  - Active Loans: {active_loans.count()}")
    print(f"  - Portfolio Value: KES {total_portfolio:,.2f}")

# Get all loans (no branch filter)
print("\n" + "=" * 80)
print("ALL BRANCHES COMBINED")
print("=" * 80)

all_loans = Loan.objects.all()
all_active_loans = all_loans.filter(status='active')
all_portfolio = all_active_loans.aggregate(total=Sum('principal_amount'))['total'] or 0

print(f"  - Total Loans: {all_loans.count()}")
print(f"  - Active Loans: {all_active_loans.count()}")
print(f"  - Portfolio Value: KES {all_portfolio:,.2f}")

# Test admin users
print("\n" + "=" * 80)
print("ADMIN USERS")
print("=" * 80)

admins = CustomUser.objects.filter(role='admin', is_active=True)
print(f"\n✓ Total Admin Users: {admins.count()}")
for admin in admins:
    print(f"  - {admin.username} (Email: {admin.email})")

print("\n" + "=" * 80)
print("TEST COMPLETE")
print("=" * 80)
