#!/usr/bin/env python
"""
Test the client performance view logic
"""

import os
import sys
import django
from pathlib import Path

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

# Setup Django
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser
from loans.models import Loan

print("="*60)
print("TESTING CLIENT PERFORMANCE VIEW LOGIC")
print("="*60)

# Get admin user
print("\n[1/5] Finding admin user...")
admin_user = CustomUser.objects.filter(role='admin').first()
if admin_user:
    print(f"✓ Found admin: {admin_user.get_full_name()}")
    print(f"  Role: {admin_user.role}")
else:
    print("✗ No admin user found!")
    sys.exit(1)

# Get portfolio managers
print("\n[2/5] Finding portfolio managers...")
portfolio_managers = CustomUser.objects.filter(
    role__in=['loan_officer', 'team_leader'],
    status='active'
)
print(f"✓ Found {portfolio_managers.count()} portfolio managers")
for pm in portfolio_managers:
    print(f"  - {pm.get_full_name()} ({pm.role})")

# Test the logic for admin
print("\n[3/5] Testing admin logic...")
if admin_user.role == 'admin':
    clients = CustomUser.objects.filter(
        role='borrower',
        status='active'
    )
    print(f"✓ Admin should see {clients.count()} clients")
else:
    print("✗ User is not admin")

# Get sample client data
print("\n[4/5] Testing client data retrieval...")
sample_client = clients.first()
if sample_client:
    print(f"✓ Sample client: {sample_client.get_full_name()}")
    
    # Get loans
    client_loans = Loan.objects.filter(borrower=sample_client)
    print(f"  Loans: {client_loans.count()}")
    
    if client_loans.exists():
        loan = client_loans.first()
        print(f"  Sample loan ID: {loan.id}")
        print(f"  Total amount: {loan.total_amount}")
        print(f"  Amount paid cache: {getattr(loan, '_amount_paid_cache', 'N/A')}")
        print(f"  Status: {loan.status}")
        
        # Calculate metrics
        total_borrowed = sum(loan.total_amount for loan in client_loans)
        total_repaid = sum(getattr(loan, '_amount_paid_cache', 0) or 0 for loan in client_loans)
        outstanding = sum(
            loan.total_amount - (getattr(loan, '_amount_paid_cache', 0) or 0) 
            for loan in client_loans.filter(status='active')
        )
        
        print(f"\n  Calculated metrics:")
        print(f"    Total borrowed: KES {total_borrowed:,.2f}")
        print(f"    Total repaid: KES {total_repaid:,.2f}")
        print(f"    Outstanding: KES {outstanding:,.2f}")
else:
    print("✗ No clients found!")

# Test the full loop
print("\n[5/5] Testing full data collection...")
client_performance_data = []

for manager in portfolio_managers:
    # For admin, show ALL clients
    if admin_user.role == 'admin':
        clients = CustomUser.objects.filter(
            role='borrower',
            status='active'
        )
    else:
        clients = CustomUser.objects.filter(
            portfolio_manager=manager,
            role='borrower',
            status='active'
        )
    
    print(f"\n  Manager: {manager.get_full_name()}")
    print(f"  Clients: {clients.count()}")
    
    for client in clients[:2]:  # Just first 2 for testing
        client_loans = Loan.objects.filter(borrower=client)
        total_loans = client_loans.count()
        
        if total_loans > 0:
            total_borrowed = sum(loan.total_amount for loan in client_loans)
            total_repaid = sum(getattr(loan, '_amount_paid_cache', 0) or 0 for loan in client_loans)
            
            client_performance_data.append({
                'client_name': client.get_full_name(),
                'total_loans': total_loans,
                'total_borrowed': total_borrowed,
                'total_repaid': total_repaid,
            })
            
            print(f"    - {client.get_full_name()}: {total_loans} loans, KES {total_borrowed:,.2f}")

print("\n" + "="*60)
print(f"COLLECTED DATA FOR {len(client_performance_data)} CLIENTS")
print("="*60)

if len(client_performance_data) > 0:
    print("\n✅ Data collection works!")
    print("\nSample data:")
    for data in client_performance_data[:3]:
        print(f"  - {data['client_name']}: {data['total_loans']} loans")
else:
    print("\n❌ NO DATA COLLECTED - Something is wrong!")
    print("\nPossible issues:")
    print("1. Portfolio managers loop is not iterating correctly")
    print("2. Client query is not returning results")
    print("3. View logic has a bug")
