"""Move roman-rank-style values out of Employee.department into Employee.category.

Also applies known explicit fixes:
  - Anna Anila Widyatantri P -> department="Department of Politics and Social Changes", category="III-C"
  - Nuroji Lukman Syah -> phone_extension="530"
"""
import re
from django.core.management.base import BaseCommand
from django.db import transaction

from apps.hr.models import Employee


# Matches things like I-A, II-B, III-C, IV-D, V-E, etc.
RANK_PATTERN = re.compile(r"^[IVX]+-[A-Z]$")


EXPLICIT_FIXES = {
    "Anna Anila Widyatantri P": {
        "department": "Department of Politics and Social Changes",
        "category": "III-C",
    },
}

PHONE_EXTENSIONS = {
    "Nuroji Lukman Syah": "530",
    "Nuroji Syah": "530",
}


class Command(BaseCommand):
    help = "Move rank-style department values into Employee.category and apply known fixes."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true", help="Show changes without saving")

    @transaction.atomic
    def handle(self, *args, **options):
        dry = options.get("dry_run", False)
        moved = 0
        explicit = 0
        ext_set = 0

        for emp in Employee.objects.select_related("user").all():
            full_name = (emp.user.get_full_name() or "").strip()
            changes = []

            # Move rank-style department -> category
            dep = (emp.department or "").strip()
            if dep and RANK_PATTERN.match(dep) and not emp.category:
                changes.append(f"department '{dep}' -> category")
                emp.category = dep
                emp.department = ""
                moved += 1

            # Explicit overrides
            fix = EXPLICIT_FIXES.get(full_name)
            if fix:
                if "department" in fix and emp.department != fix["department"]:
                    changes.append(f"department -> '{fix['department']}'")
                    emp.department = fix["department"]
                if "category" in fix and emp.category != fix["category"]:
                    changes.append(f"category -> '{fix['category']}'")
                    emp.category = fix["category"]
                explicit += 1

            # Phone extension
            ext = PHONE_EXTENSIONS.get(full_name)
            if ext and emp.phone_extension != ext:
                changes.append(f"phone_extension -> {ext}")
                emp.phone_extension = ext
                ext_set += 1

            if changes:
                self.stdout.write(f"  {full_name or emp.employee_id}: " + "; ".join(changes))
                if not dry:
                    emp.save(update_fields=["department", "category", "phone_extension", "updated_at"])

        suffix = " (dry-run)" if dry else ""
        self.stdout.write(self.style.SUCCESS(
            f"\nMoved {moved} rank values · {explicit} explicit fixes · {ext_set} extensions{suffix}"
        ))
