import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.development")
django.setup()

from apps.accounts.models import User
from apps.hr.models import Employee, Department, Designation
from apps.organizations.models import Organization

default_org = Organization.objects.first()
if not default_org:
    default_org = Organization.objects.create(name="Default Org", code="ORG01")

created_count = 0
users_without_employee = User.objects.filter(employee_profile__isnull=True)

for user in users_without_employee:
    print(f"Creating employee profile for {user.email}")
    org = user.organization or default_org
    
    if not user.organization:
        user.organization = org
        user.save(update_fields=['organization'])

    dept = Department.objects.filter(organization=org).first()
    if not dept:
        dept = Department.objects.create(organization=org, name="General")
    
    desig = Designation.objects.filter(organization=org).first()
    if not desig:
        desig = Designation.objects.create(organization=org, department=dept, title="Staff")

    code = f"EMP-{str(user.id).split('-')[0].upper()}"

    emp = Employee.objects.create(
        user=user,
        organization=org,
        employee_code=code,
        department=dept,
        designation=desig,
        work_email=user.email,
        status="ACTIVE"
    )
    created_count += 1

print(f"Successfully generated {created_count} missing employee profiles!")
