import os
import django

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

from django.contrib.auth import get_user_model
from apps.users.models import Role

User = get_user_model()

# 1. Clean up existing users (except superusers)
print("Removing existing non-superuser employees...")
deleted_count, _ = User.objects.filter(is_superuser=False).delete()
print(f"Deleted {deleted_count} users.")

# 2. Define the new team structure from Emails.txt
# format: [email, Full Name, [RoleNames], department]
employees = [
    ["asad@cyberarsenals.com", "Muhammad Asad Anwaar", ["TL"], "Tech"],
    ["farhan@cyberarsenals.com", "Farhan Habib Ahmed", ["CEO"], "Admin"],
    ["hammad@cyberarsenals.com", "Hammad", ["Member"], "Tech"],
    ["hassanluqman@cyberarsenals.com", "Hassan Luqman", ["Member"], "Tech"],
    ["hr@cyberarsenals.com", "Reema Shaikh", ["HR"], "Admin"],
    ["husnain@cyberarsenals.com", "Husnain Saeed", ["TL", "BD"], "Sales"], # BD Team Lead
    ["laibanoor@cyberarsenals.com", "Laiba Noor", ["Member"], "Tech"],
    ["sana@cyberarsenals.com", "Sana Waheed", ["Member"], "Tech"],
    ["tayyab@cyberarsenals.com", "Tayyib Ali", ["Member"], "Tech"],
    ["waheed@cyberarsenals.com", "Waheed", ["Member"], "Tech"],
]

DEFAULT_PASSWORD = "CyberArsenal@2026"

print("Importing original team members...")
for email, name, role_names, dept in employees:
    # Create or update user
    user, created = User.objects.get_or_create(
        email=email,
        defaults={
            'full_name': name,
            'department': dept,
            'is_active': True,
        }
    )
    
    if created:
        user.set_password(DEFAULT_PASSWORD)
    
    user.full_name = name
    user.department = dept
    user.save()
    
    # Assign Roles
    user.roles.clear()
    for rname in role_names:
        role_obj = Role.objects.get(name=rname)
        user.roles.add(role_obj)
    
    print(f"  [{'CREATED' if created else 'UPDATED'}] {name} ({email}) as {', '.join(role_names)}")

print("\nImport completed successfully.")
