#!/usr/bin/env python
"""
Create test users with different access levels for Haven Grazuri Investment Limited
"""
import os
import django
import sys

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser, Branch
from django.db import transaction
from datetime import date

def create_test_users():
    """Create test users with different roles and access levels"""
    
    print("=" * 80)
    print("Creating Test Users for Haven Grazuri Investment Limited")
    print("=" * 80)
    
    # Get or create main branch
    main_branch, created = Branch.objects.get_or_create(
        code='MAIN',
        defaults={
            'name': 'Main Branch - Thika',
            'address': '2nd Floor, Old Jogoo Kimakia Building, Stadium Road, Thika',
            'phone_number': '+254112941830',
            'email': 'havenin2023@gmail.com',
            'is_main_branch': True,
            'is_active': True,
        }
    )
    
    if created:
        print(f"✓ Created main branch: {main_branch.name}")
    else:
        print(f"✓ Main branch already exists: {main_branch.name}")
    
    # Create additional branch for testing
    nairobi_branch, created = Branch.objects.get_or_create(
        code='NRB',
        defaults={
            'name': 'Nairobi Branch',
            'address': 'Nairobi CBD',
            'phone_number': '+254114457516',
            'email': 'nairobi@havengrazuri.co.ke',
            'is_main_branch': False,
            'is_active': True,
        }
    )
    
    if created:
        print(f"✓ Created Nairobi branch: {nairobi_branch.name}")
    else:
        print(f"✓ Nairobi branch already exists: {nairobi_branch.name}")
    
    print("\n" + "=" * 80)
    print("Creating Users")
    print("=" * 80 + "\n")
    
    users_data = [
        {
            'username': 'admin',
            'email': 'admin@havengrazuri.co.ke',
            'password': 'Admin@2025',
            'first_name': 'System',
            'last_name': 'Administrator',
            'role': 'admin',
            'phone_number': '+254112941830',
            'id_number': '12345678',
            'branch': main_branch,
            'is_staff': True,
            'is_superuser': True,
            'status': 'active',
            'date_of_birth': date(1985, 1, 15),
            'gender': 'M',
            'description': 'Full system access - can manage all users, branches, and settings'
        },
        {
            'username': 'teamleader',
            'email': 'teamleader@havengrazuri.co.ke',
            'password': 'TeamLeader@2025',
            'first_name': 'John',
            'last_name': 'Kamau',
            'role': 'team_leader',
            'phone_number': '+254114457516',
            'id_number': '23456789',
            'branch': main_branch,
            'is_staff': True,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1988, 5, 20),
            'gender': 'M',
            'description': 'Can manage loan officers, approve loans, view reports'
        },
        {
            'username': 'loanofficer1',
            'email': 'loanofficer1@havengrazuri.co.ke',
            'password': 'LoanOfficer@2025',
            'first_name': 'Mary',
            'last_name': 'Wanjiku',
            'role': 'loan_officer',
            'phone_number': '+254115451752',
            'id_number': '34567890',
            'branch': main_branch,
            'is_staff': True,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1992, 8, 10),
            'gender': 'F',
            'description': 'Can create and manage loan applications, view assigned clients'
        },
        {
            'username': 'loanofficer2',
            'email': 'loanofficer2@havengrazuri.co.ke',
            'password': 'LoanOfficer@2025',
            'first_name': 'Peter',
            'last_name': 'Omondi',
            'role': 'loan_officer',
            'phone_number': '+254758587153',
            'id_number': '45678901',
            'branch': nairobi_branch,
            'is_staff': True,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1990, 3, 25),
            'gender': 'M',
            'description': 'Nairobi branch loan officer - can manage loans in Nairobi branch'
        },
        {
            'username': 'secretary',
            'email': 'secretary@havengrazuri.co.ke',
            'password': 'Secretary@2025',
            'first_name': 'Grace',
            'last_name': 'Akinyi',
            'role': 'secretary',
            'phone_number': '+254720123456',
            'id_number': '56789012',
            'branch': main_branch,
            'is_staff': True,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1995, 11, 5),
            'gender': 'F',
            'description': 'Can view reports, manage documents, limited loan access'
        },
        {
            'username': 'auditor',
            'email': 'auditor@havengrazuri.co.ke',
            'password': 'Auditor@2025',
            'first_name': 'David',
            'last_name': 'Mwangi',
            'role': 'auditor',
            'phone_number': '+254730234567',
            'id_number': '67890123',
            'branch': main_branch,
            'is_staff': True,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1987, 6, 18),
            'gender': 'M',
            'description': 'Read-only access to all reports and audit trails'
        },
        {
            'username': 'borrower1',
            'email': 'borrower1@example.com',
            'password': 'Borrower@2025',
            'first_name': 'Jane',
            'last_name': 'Njeri',
            'role': 'borrower',
            'phone_number': '+254740345678',
            'id_number': '78901234',
            'branch': main_branch,
            'is_staff': False,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1993, 9, 12),
            'gender': 'F',
            'marital_status': 'single',
            'description': 'Regular borrower - can apply for loans, view own account'
        },
        {
            'username': 'borrower2',
            'email': 'borrower2@example.com',
            'password': 'Borrower@2025',
            'first_name': 'James',
            'last_name': 'Kipchoge',
            'role': 'borrower',
            'phone_number': '+254750456789',
            'id_number': '89012345',
            'branch': nairobi_branch,
            'is_staff': False,
            'is_superuser': False,
            'status': 'active',
            'date_of_birth': date(1991, 4, 22),
            'gender': 'M',
            'marital_status': 'married',
            'description': 'Nairobi branch borrower - can apply for loans'
        },
    ]
    
    created_users = []
    
    with transaction.atomic():
        for user_data in users_data:
            description = user_data.pop('description')
            
            # Check if user already exists
            if CustomUser.objects.filter(username=user_data['username']).exists():
                user = CustomUser.objects.get(username=user_data['username'])
                print(f"⚠ User '{user_data['username']}' already exists - updating...")
                
                # Update user fields
                for key, value in user_data.items():
                    if key != 'password':
                        setattr(user, key, value)
                user.set_password(user_data['password'])
                user.save()
                
                print(f"✓ Updated: {user.get_full_name()} ({user.username})")
            else:
                # Create new user
                password = user_data.pop('password')
                user = CustomUser.objects.create(**user_data)
                user.set_password(password)
                user.save()
                
                print(f"✓ Created: {user.get_full_name()} ({user.username})")
            
            # Set accessible branches for staff users
            if user.is_staff and user.role != 'borrower':
                if user.role == 'admin':
                    # Admin can access all branches
                    user.accessible_branches.set(Branch.objects.all())
                    print(f"  → Access: All branches")
                elif user.role == 'team_leader':
                    # Team leader can access main branch and Nairobi branch
                    user.accessible_branches.set([main_branch, nairobi_branch])
                    print(f"  → Access: Main Branch, Nairobi Branch")
                else:
                    # Other staff can only access their assigned branch
                    user.accessible_branches.set([user.branch])
                    print(f"  → Access: {user.branch.name}")
            
            print(f"  → Role: {user.get_role_display()}")
            print(f"  → Branch: {user.branch.name}")
            print(f"  → Status: {user.status}")
            print(f"  → Description: {description}")
            print()
            
            created_users.append({
                'username': user.username,
                'password': user_data.get('password', 'Borrower@2025' if user.role == 'borrower' else password),
                'role': user.role,
                'email': user.email,
            })
    
    print("=" * 80)
    print("User Creation Summary")
    print("=" * 80 + "\n")
    
    print("Login Credentials:")
    print("-" * 80)
    for user_info in created_users:
        print(f"Username: {user_info['username']:<20} Password: {user_info['password']:<25} Role: {user_info['role']}")
    
    print("\n" + "=" * 80)
    print("Access Level Summary")
    print("=" * 80 + "\n")
    
    print("1. ADMIN (admin)")
    print("   - Full system access")
    print("   - Can manage all users, branches, and settings")
    print("   - Can approve/reject loans at any level")
    print("   - Access to all reports and analytics")
    print()
    
    print("2. TEAM LEADER (teamleader)")
    print("   - Can manage loan officers")
    print("   - Can approve loans up to certain limits")
    print("   - Access to team performance reports")
    print("   - Can view all branches they have access to")
    print()
    
    print("3. LOAN OFFICER (loanofficer1, loanofficer2)")
    print("   - Can create and manage loan applications")
    print("   - Can view and manage assigned clients")
    print("   - Can process loan disbursements")
    print("   - Limited to their assigned branch")
    print()
    
    print("4. SECRETARY (secretary)")
    print("   - Can view reports and documents")
    print("   - Can manage client information")
    print("   - Limited loan management access")
    print("   - Can generate reports")
    print()
    
    print("5. AUDITOR (auditor)")
    print("   - Read-only access to all reports")
    print("   - Can view audit trails")
    print("   - Can export data for analysis")
    print("   - Cannot modify any records")
    print()
    
    print("6. BORROWER (borrower1, borrower2)")
    print("   - Can apply for loans")
    print("   - Can view own loan status and history")
    print("   - Can make payments")
    print("   - Can view own account information")
    print()
    
    print("=" * 80)
    print("✓ All users created successfully!")
    print("=" * 80)
    print("\nYou can now login at: http://127.0.0.1:8000/login/")
    print()

if __name__ == '__main__':
    try:
        create_test_users()
    except Exception as e:
        print(f"\n❌ Error creating users: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
