"""
Create portfolio managers (loan officers) for client assignment
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser, Branch
from django.db import transaction

print("=" * 80)
print("CREATING PORTFOLIO MANAGERS")
print("=" * 80)

# Get branches
branches = list(Branch.objects.filter(is_active=True).order_by('name'))
print(f"\n✓ Found {len(branches)} active branches")

portfolio_managers = []

with transaction.atomic():
    # Create loan officers for each branch
    for i, branch in enumerate(branches, 1):
        username = f"loan_officer_{branch.code.lower()}"
        email = f"{username}@example.com"
        
        user, created = CustomUser.objects.get_or_create(
            username=username,
            defaults={
                'email': email,
                'first_name': f'Loan Officer',
                'last_name': branch.name,
                'phone_number': f'0711000{i:03d}',
                'role': 'loan_officer',
                'branch': branch,
                'status': 'active',
                'is_staff': True,
                'is_active': True
            }
        )
        
        if created:
            user.set_password('password123')
            user.save()
            print(f"\n✓ Created: {user.username}")
            print(f"  - Name: {user.get_full_name()}")
            print(f"  - Branch: {branch.name}")
            print(f"  - Role: {user.role}")
            print(f"  - Password: password123")
        else:
            # Update to ensure they're loan officers
            if user.role != 'loan_officer':
                user.role = 'loan_officer'
                user.branch = branch
                user.status = 'active'
                user.is_active = True
                user.save()
                print(f"\n✓ Updated: {user.username} to loan_officer")
            else:
                print(f"\n✓ Exists: {user.username}")
            print(f"  - Branch: {branch.name}")
        
        portfolio_managers.append(user)
    
    # Create a team leader
    main_branch = Branch.objects.filter(is_main_branch=True).first() or branches[0]
    
    team_leader, created = CustomUser.objects.get_or_create(
        username='team_leader',
        defaults={
            'email': 'team_leader@example.com',
            'first_name': 'Team',
            'last_name': 'Leader',
            'phone_number': '0722000001',
            'role': 'team_leader',
            'branch': main_branch,
            'status': 'active',
            'is_staff': True,
            'is_active': True
        }
    )
    
    if created:
        team_leader.set_password('password123')
        team_leader.save()
        print(f"\n✓ Created: {team_leader.username}")
        print(f"  - Name: {team_leader.get_full_name()}")
        print(f"  - Branch: {main_branch.name}")
        print(f"  - Role: {team_leader.role}")
        print(f"  - Password: password123")
    else:
        if team_leader.role != 'team_leader':
            team_leader.role = 'team_leader'
            team_leader.branch = main_branch
            team_leader.status = 'active'
            team_leader.is_active = True
            team_leader.save()
            print(f"\n✓ Updated: {team_leader.username} to team_leader")
        else:
            print(f"\n✓ Exists: {team_leader.username}")
        print(f"  - Branch: {main_branch.name}")
    
    portfolio_managers.append(team_leader)

print("\n" + "=" * 80)
print("SUMMARY")
print("=" * 80)

# Show all portfolio managers
all_pms = CustomUser.objects.filter(
    role__in=['loan_officer', 'team_leader'],
    status='active',
    is_active=True
).order_by('branch__name', 'role')

print(f"\n✓ Total Portfolio Managers: {all_pms.count()}")
for pm in all_pms:
    print(f"\n{pm.username}")
    print(f"  - Name: {pm.get_full_name()}")
    print(f"  - Role: {pm.role}")
    print(f"  - Branch: {pm.branch.name if pm.branch else 'No Branch'}")
    print(f"  - Email: {pm.email}")

print("\n" + "=" * 80)
print("✓ PORTFOLIO MANAGERS CREATED")
print("=" * 80)
print("\nYou can now assign clients to these portfolio managers!")
print("\nDefault password for all: password123")
