# ADDITIVE management command.
#
#   python manage.py fix_placeholder_candidates            # dry-run (default) - only prints
#   python manage.py fix_placeholder_candidates --apply    # really saves
#
# For candidates still carrying the placeholder name/email
# ("Applicant - <Role>" / "apply.<ts>@careers.portal") it recovers the REAL
# values the candidate already typed:
#   email <- Personal_Email   (portal always posted it), else saved portal draft
#   name  <- saved portal draft (fullName / full_name / name), if any
# Nothing is deleted; rows with nothing to recover are only reported.
from django.core.management.base import BaseCommand
from django.core.validators import validate_email
from django.core.exceptions import ValidationError

from Employee.models import EmployeeDT
from Recruitment.portal_identity import is_placeholder_email, is_placeholder_name, NAME_KEYS, EMAIL_KEYS, _name_max


class Command(BaseCommand):
    help = "Replace placeholder candidate names/emails with the real values the candidate submitted."

    def add_arguments(self, parser):
        parser.add_argument("--apply", action="store_true", help="Save changes (default is dry-run).")

    def handle(self, *args, **opts):
        apply_ = opts["apply"]
        try:
            from Recruitment.models_register import CandidatePortalDraft
        except Exception:      # draft table not present
            CandidatePortalDraft = None

        fixed = skipped = 0
        for c in EmployeeDT.objects.all().order_by("id"):
            bad_name, bad_email = is_placeholder_name(c.name), is_placeholder_email(c.email)
            if not (bad_name or bad_email):
                continue
            if (c.email or "").lower().endswith("@example.com"):      # automated test rows - leave alone
                continue
            draft = {}
            if CandidatePortalDraft is not None:
                for dr in CandidatePortalDraft.objects.filter(candidate=c):
                    if isinstance(dr.data, dict):
                        draft.update(dr.data)
            new_name = next((str(draft[k]).strip() for k in NAME_KEYS if draft.get(k)), "")
            cand_emails = [getattr(c, "Personal_Email", None)] + [draft.get(k) for k in EMAIL_KEYS]
            new_email = next((str(e).strip().lower() for e in cand_emails
                              if e and not is_placeholder_email(e)), "")
            changes = []
            if bad_name and new_name and not is_placeholder_name(new_name):
                changes.append(("name", c.name, " ".join(new_name.split())[: _name_max()]))
            if bad_email and new_email:
                try:
                    validate_email(new_email)
                    clash = EmployeeDT.objects.filter(company=c.company, email__iexact=new_email).exclude(pk=c.pk).exists()
                    if not clash:
                        changes.append(("email", c.email, new_email))
                except ValidationError:
                    pass
            if not changes:
                skipped += 1
                self.stdout.write(f"- {c.candidate_id or c.pk}: nothing to recover ({c.name} / {c.email})")
                continue
            for field, old, new in changes:
                self.stdout.write(f"* {c.candidate_id or c.pk}: {field}: {old!r} -> {new!r}")
                if apply_:
                    setattr(c, field, new)
            if apply_:
                c.save(update_fields=[f for f, _, _ in changes])
            fixed += 1
        mode = "APPLIED" if apply_ else "DRY-RUN (use --apply to save)"
        self.stdout.write(self.style.SUCCESS(f"{mode}: {fixed} candidate(s) fixable, {skipped} nothing to recover."))
