import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser

# Get all loan officers
loan_officers = CustomUser.objects.filter(role='loan_officer')
print(f"Found {loan_officers.count()} loan officers")

# Get all borrowers without portfolio managers
borrowers = CustomUser.objects.filter(role='borrower', portfolio_manager__isnull=True)
print(f"Found {borrowers.count()} borrowers without portfolio managers")

if loan_officers.count() == 0:
    print("No loan officers found!")
    exit(1)

# Assign borrowers to loan officers in round-robin fashion
officer_index = 0
assigned_count = 0

for borrower in borrowers:
    officer = list(loan_officers)[officer_index % loan_officers.count()]
    borrower.portfolio_manager = officer
    borrower.save()
    print(f"✓ Assigned {borrower.get_full_name()} to {officer.get_full_name()}")
    assigned_count += 1
    officer_index += 1

print(f"\n✓ Assigned {assigned_count} borrowers to {loan_officers.count()} loan officers")

# Show summary
print("\nPortfolio Summary:")
for officer in loan_officers:
    count = CustomUser.objects.filter(portfolio_manager=officer).count()
    print(f"  {officer.get_full_name()}: {count} clients")
