#!/usr/bin/env python
"""
Fix client performance ranking to work without portfolio managers
"""

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()

# Read the current file
file_path = 'users/portfolio_views.py'

print("="*60)
print("FIXING CLIENT PERFORMANCE VIEW")
print("="*60)

# The fix: Change the query to include clients without portfolio managers
old_code = """                # Get clients directly from database
                clients = CustomUser.objects.filter(
                    portfolio_manager=manager,
                    role='borrower',
                    status='active'
                ).select_related('portfolio_manager')"""

new_code = """                # Get clients directly from database
                # Include clients assigned to this manager OR clients without any manager (for admin)
                if manager.role == 'admin':
                    clients = CustomUser.objects.filter(
                        role='borrower',
                        status='active'
                    ).select_related('portfolio_manager')
                else:
                    clients = CustomUser.objects.filter(
                        portfolio_manager=manager,
                        role='borrower',
                        status='active'
                    ).select_related('portfolio_manager')"""

print("\nReading portfolio_views.py...")
with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()

if old_code in content:
    print("✓ Found the code to fix")
    content = content.replace(old_code, new_code)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("✓ Fixed client performance view")
    print("\nChanges made:")
    print("- Admin users now see ALL clients (even without portfolio managers)")
    print("- Other users see only their assigned clients")
    print("\n" + "="*60)
    print("✅ FIX APPLIED SUCCESSFULLY")
    print("="*60)
    print("\nNext steps:")
    print("1. Restart your Django server")
    print("2. Refresh the client performance page")
    print("3. You should now see client data")
else:
    print("⚠️  Could not find the exact code to replace")
    print("The file may have been modified already")
    print("\nManual fix needed:")
    print("Edit users/portfolio_views.py around line 1740")
    print("Make admin users see all clients, not just assigned ones")

