import os
import django
from decimal import Decimal

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

from users.models import CustomUser, Branch
from django.utils import timezone

# First, create a main branch if it doesn't exist
try:
    main_branch = Branch.objects.get(name='Main Branch')
    print(f"Using existing branch: {main_branch.name}")
except Branch.DoesNotExist:
    main_branch = Branch.objects.create(
        name='Main Branch',
        code='MAIN',
        address='Nairobi CBD',
        phone_number='+254700000001',
        email='main@branchbusiness.co.ke',
        is_main_branch=True,
        is_active=True
    )
    print(f"Created branch: {main_branch.name}")

# Create additional branches
branches_data = [
    {'name': 'Westlands Branch', 'code': 'WEST', 'address': 'Westlands, Nairobi'},
    {'name': 'Mombasa Branch', 'code': 'MBA', 'address': 'Mombasa Road'},
    {'name': 'Kisumu Branch', 'code': 'KSM', 'address': 'Kisumu Town'},
]

branches = [main_branch]
for branch_data in branches_data:
    branch, created = Branch.objects.get_or_create(
        code=branch_data['code'],
        defaults={
            'name': branch_data['name'],
            'address': branch_data['address'],
            'phone_number': f'+25470000{len(branches):04d}',
            'email': f"{branch_data['code'].lower()}@branchbusiness.co.ke",
            'is_active': True
        }
    )
    branches.append(branch)
    if created:
        print(f"Created branch: {branch.name}")

# Sample users data
users_data = [
    # Admin users
    {
        'username': 'admin',
        'email': 'admin@example.com',
        'password': 'admin123',
        'first_name': 'Admin',
        'last_name': 'User',
        'phone_number': '+254700000000',
        'role': 'admin',
        'is_superuser': True,
        'is_staff': True,
        'branch': main_branch
    },
    {
        'username': 'manager1',
        'email': 'manager1@example.com',
        'password': 'manager123',
        'first_name': 'John',
        'last_name': 'Manager',
        'phone_number': '+254711000001',
        'role': 'manager',
        'is_staff': True,
        'branch': main_branch
    },
    {
        'username': 'manager2',
        'email': 'manager2@example.com',
        'password': 'manager123',
        'first_name': 'Sarah',
        'last_name': 'Williams',
        'phone_number': '+254711000002',
        'role': 'manager',
        'is_staff': True,
        'branch': branches[1] if len(branches) > 1 else main_branch
    },
    
    # Loan Officers
    {
        'username': 'officer1',
        'email': 'officer1@example.com',
        'password': 'officer123',
        'first_name': 'Michael',
        'last_name': 'Johnson',
        'phone_number': '+254722000001',
        'role': 'loan_officer',
        'is_staff': True,
        'branch': main_branch
    },
    {
        'username': 'officer2',
        'email': 'officer2@example.com',
        'password': 'officer123',
        'first_name': 'Emily',
        'last_name': 'Davis',
        'phone_number': '+254722000002',
        'role': 'loan_officer',
        'is_staff': True,
        'branch': main_branch
    },
    {
        'username': 'officer3',
        'email': 'officer3@example.com',
        'password': 'officer123',
        'first_name': 'David',
        'last_name': 'Brown',
        'phone_number': '+254722000003',
        'role': 'loan_officer',
        'is_staff': True,
        'branch': branches[1] if len(branches) > 1 else main_branch
    },
    {
        'username': 'officer4',
        'email': 'officer4@example.com',
        'password': 'officer123',
        'first_name': 'Grace',
        'last_name': 'Mwangi',
        'phone_number': '+254722000004',
        'role': 'loan_officer',
        'is_staff': True,
        'branch': branches[2] if len(branches) > 2 else main_branch
    },
    
    # Accountants
    {
        'username': 'accountant1',
        'email': 'accountant1@example.com',
        'password': 'account123',
        'first_name': 'James',
        'last_name': 'Wilson',
        'phone_number': '+254733000001',
        'role': 'accountant',
        'is_staff': True,
        'branch': main_branch
    },
    {
        'username': 'accountant2',
        'email': 'accountant2@example.com',
        'password': 'account123',
        'first_name': 'Lucy',
        'last_name': 'Kamau',
        'phone_number': '+254733000002',
        'role': 'accountant',
        'is_staff': True,
        'branch': branches[1] if len(branches) > 1 else main_branch
    },
    
    # Borrowers
    {
        'username': 'borrower1',
        'email': 'borrower1@example.com',
        'password': 'borrower123',
        'first_name': 'Peter',
        'last_name': 'Omondi',
        'phone_number': '+254700100001',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID001234567',
        'monthly_income': Decimal('50000.00'),
        'business_name': 'Peter\'s Electronics',
        'business_type': 'retail'
    },
    {
        'username': 'borrower2',
        'email': 'borrower2@example.com',
        'password': 'borrower123',
        'first_name': 'Mary',
        'last_name': 'Wanjiku',
        'phone_number': '+254700100002',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID002345678',
        'monthly_income': Decimal('35000.00'),
        'business_name': 'Mary\'s Salon',
        'business_type': 'service'
    },
    {
        'username': 'borrower3',
        'email': 'borrower3@example.com',
        'password': 'borrower123',
        'first_name': 'Joseph',
        'last_name': 'Kipchoge',
        'phone_number': '+254700100003',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID003456789',
        'monthly_income': Decimal('45000.00'),
        'business_name': 'Joe\'s Hardware',
        'business_type': 'retail'
    },
    {
        'username': 'borrower4',
        'email': 'borrower4@example.com',
        'password': 'borrower123',
        'first_name': 'Jane',
        'last_name': 'Achieng',
        'phone_number': '+254700100004',
        'role': 'borrower',
        'is_staff': False,
        'branch': branches[1] if len(branches) > 1 else main_branch,
        'id_number': 'ID004567890',
        'monthly_income': Decimal('60000.00'),
        'business_name': 'Jane\'s Boutique',
        'business_type': 'retail'
    },
    {
        'username': 'borrower5',
        'email': 'borrower5@example.com',
        'password': 'borrower123',
        'first_name': 'Daniel',
        'last_name': 'Mutua',
        'phone_number': '+254700100005',
        'role': 'borrower',
        'is_staff': False,
        'branch': branches[1] if len(branches) > 1 else main_branch,
        'id_number': 'ID005678901',
        'monthly_income': Decimal('40000.00'),
        'business_name': 'Dan\'s Grocery',
        'business_type': 'retail'
    },
    {
        'username': 'borrower6',
        'email': 'borrower6@example.com',
        'password': 'borrower123',
        'first_name': 'Faith',
        'last_name': 'Njeri',
        'phone_number': '+254700100006',
        'role': 'borrower',
        'is_staff': False,
        'branch': branches[2] if len(branches) > 2 else main_branch,
        'id_number': 'ID006789012',
        'monthly_income': Decimal('55000.00'),
        'business_name': 'Faith\'s Restaurant',
        'business_type': 'food'
    },
    {
        'username': 'borrower7',
        'email': 'borrower7@example.com',
        'password': 'borrower123',
        'first_name': 'Samuel',
        'last_name': 'Otieno',
        'phone_number': '+254700100007',
        'role': 'borrower',
        'is_staff': False,
        'branch': branches[2] if len(branches) > 2 else main_branch,
        'id_number': 'ID007890123',
        'monthly_income': Decimal('38000.00'),
        'business_name': 'Sam\'s Barbershop',
        'business_type': 'service'
    },
    {
        'username': 'borrower8',
        'email': 'borrower8@example.com',
        'password': 'borrower123',
        'first_name': 'Rebecca',
        'last_name': 'Wambui',
        'phone_number': '+254700100008',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID008901234',
        'monthly_income': Decimal('42000.00'),
        'business_name': 'Rebecca\'s Tailoring',
        'business_type': 'service'
    },
    {
        'username': 'borrower9',
        'email': 'borrower9@example.com',
        'password': 'borrower123',
        'first_name': 'Patrick',
        'last_name': 'Kimani',
        'phone_number': '+254700100009',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID009012345',
        'monthly_income': Decimal('48000.00'),
        'business_name': 'Patrick\'s Pharmacy',
        'business_type': 'retail'
    },
    {
        'username': 'borrower10',
        'email': 'borrower10@example.com',
        'password': 'borrower123',
        'first_name': 'Catherine',
        'last_name': 'Nyambura',
        'phone_number': '+254700100010',
        'role': 'borrower',
        'is_staff': False,
        'branch': branches[1] if len(branches) > 1 else main_branch,
        'id_number': 'ID010123456',
        'monthly_income': Decimal('52000.00'),
        'business_name': 'Cathy\'s Bakery',
        'business_type': 'food'
    },
    
    # Pending borrowers (not yet approved)
    {
        'username': 'pending1',
        'email': 'pending1@example.com',
        'password': 'pending123',
        'first_name': 'Thomas',
        'last_name': 'Maina',
        'phone_number': '+254700200001',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID011234567',
        'monthly_income': Decimal('30000.00'),
        'business_name': 'Tom\'s Carpentry',
        'business_type': 'service'
    },
    {
        'username': 'pending2',
        'email': 'pending2@example.com',
        'password': 'pending123',
        'first_name': 'Alice',
        'last_name': 'Wangari',
        'phone_number': '+254700200002',
        'role': 'borrower',
        'is_staff': False,
        'branch': main_branch,
        'id_number': 'ID012345678',
        'monthly_income': Decimal('28000.00'),
        'business_name': 'Alice\'s Boutique',
        'business_type': 'retail'
    },
]

print("\n" + "="*60)
print("Creating Sample Users")
print("="*60 + "\n")

created_count = 0
updated_count = 0
error_count = 0

for user_data in users_data:
    try:
        username = user_data.pop('username')
        password = user_data.pop('password')
        is_superuser = user_data.pop('is_superuser', False)
        
        # Check if user already exists
        user, created = CustomUser.objects.get_or_create(
            username=username,
            defaults=user_data
        )
        
        if created:
            # Set password for new user
            user.set_password(password)
            if is_superuser:
                user.is_superuser = True
                user.is_staff = True
            user.save()
            created_count += 1
            print(f"✓ Created: {username:15} | {user.get_role_display():15} | {user.branch.name if user.branch else 'No Branch'}")
        else:
            # Update existing user
            for key, value in user_data.items():
                setattr(user, key, value)
            user.set_password(password)
            if is_superuser:
                user.is_superuser = True
                user.is_staff = True
            user.save()
            updated_count += 1
            print(f"↻ Updated: {username:15} | {user.get_role_display():15} | {user.branch.name if user.branch else 'No Branch'}")
            
    except Exception as e:
        error_count += 1
        print(f"✗ Error creating {username}: {str(e)}")

print("\n" + "="*60)
print(f"Summary:")
print(f"  Created: {created_count} users")
print(f"  Updated: {updated_count} users")
print(f"  Errors:  {error_count} users")
print(f"  Total:   {created_count + updated_count} users")
print("="*60)

print("\n" + "="*60)
print("Login Credentials:")
print("="*60)
print("\nAdmin:")
print("  Username: admin       | Password: admin123")
print("\nManagers:")
print("  Username: manager1    | Password: manager123")
print("  Username: manager2    | Password: manager123")
print("\nLoan Officers:")
print("  Username: officer1-4  | Password: officer123")
print("\nAccountants:")
print("  Username: accountant1-2 | Password: account123")
print("\nBorrowers (Approved):")
print("  Username: borrower1-10  | Password: borrower123")
print("\nBorrowers (Pending):")
print("  Username: pending1-2    | Password: pending123")
print("="*60 + "\n")
