#!/usr/bin/env python
"""
Diagnose why client performance ranking shows zeros
"""

import os
import sys
import django
from pathlib import Path

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

def diagnose():
    print("="*60)
    print("CLIENT PERFORMANCE DIAGNOSTIC")
    print("="*60)
    
    # Check total clients
    total_clients = CustomUser.objects.filter(role='borrower').count()
    print(f"\n1. Total Borrowers: {total_clients}")
    
    # Check active clients
    active_clients = CustomUser.objects.filter(role='borrower', status='active').count()
    print(f"2. Active Borrowers: {active_clients}")
    
    # Check clients with portfolio managers
    clients_with_pm = CustomUser.objects.filter(
        role='borrower', 
        portfolio_manager__isnull=False
    ).count()
    print(f"3. Borrowers with Portfolio Manager: {clients_with_pm}")
    
    # Check clients without portfolio managers
    clients_without_pm = CustomUser.objects.filter(
        role='borrower', 
        portfolio_manager__isnull=True
    ).count()
    print(f"4. Borrowers WITHOUT Portfolio Manager: {clients_without_pm}")
    
    # Check total loans
    total_loans = Loan.objects.count()
    print(f"\n5. Total Loans: {total_loans}")
    
    # Check active loans
    active_loans = Loan.objects.filter(status='active').count()
    print(f"6. Active Loans: {active_loans}")
    
    # Check portfolio managers
    portfolio_managers = CustomUser.objects.filter(
        role__in=['loan_officer', 'team_leader'],
        status='active'
    ).count()
    print(f"\n7. Active Portfolio Managers: {portfolio_managers}")
    
    # Sample clients without portfolio managers
    print("\n" + "="*60)
    print("ISSUE IDENTIFIED:")
    print("="*60)
    
    if clients_without_pm > 0:
        print(f"\n⚠️  {clients_without_pm} clients don't have portfolio managers assigned!")
        print("\nSample clients without portfolio managers:")
        
        sample_clients = CustomUser.objects.filter(
            role='borrower',
            portfolio_manager__isnull=True
        )[:5]
        
        for client in sample_clients:
            print(f"  - {client.get_full_name()} (ID: {client.id})")
        
        print("\n" + "="*60)
        print("SOLUTION:")
        print("="*60)
        print("\nRun this command to assign portfolio managers:")
        print("  python assign_portfolio_managers.py")
        print("\nOr manually assign in Django admin")
    else:
        print("\n✓ All clients have portfolio managers assigned")
        print("\nThe issue might be with permissions or data filtering.")
        print("Check if the logged-in user has proper role and permissions.")

if __name__ == "__main__":
    diagnose()
