# ============================================================
# ADDITIVE: candidate identity sync for the public candidate portal.
#
# Problem: HR generates a link with a PLACEHOLDER candidate
#   name  = "Applicant - <Role>"
#   email = "apply.<timestamp>@careers.portal"
# The candidate then types his REAL full name / e-mail in the form, but
# clean_profile() / PERSONAL_MAP never wrote `name` / `email` into EmployeeDT,
# so Django-admin (Select User to change) and the Recruitment desk kept
# showing the placeholder.  apply_identity() copies the real values over
# - ONLY while the stored value is still a placeholder (HR-entered real
# data is never overwritten by the candidate).
# ============================================================
from django.core.exceptions import ValidationError
from django.core.validators import validate_email

from Employee.models import EmployeeDT

PLACEHOLDER_EMAIL_MARKERS = ("@careers.portal", "@apply.job", "@apply.portal")
PLACEHOLDER_NAME_PREFIXES = ("applicant", "open applicant", "job applicant")

NAME_KEYS = ("name", "full_name", "fullName", "candidate_name", "candidateName", "applicant_name", "fullname")
EMAIL_KEYS = ("email", "personal_email", "work_email", "workEmail", "candidate_email", "candidateEmail")


def _name_max():
    try:
        return EmployeeDT._meta.get_field("name").max_length or 50
    except Exception:
        return 50


# ---- ADDITIVE (v2): more placeholder shapes seen in the real data --------------------------
#   names : "Direct Applicant xxxx", "Applicant xxxx", "Applicant - Role"
#   emails: nologin_xxxx@example.com, portal_candidate_xxxx@example.com, cand_xxxx@example.com
PLACEHOLDER_NAME_PREFIXES_EXTRA = ("direct applicant", "new applicant", "applicant ", "applicant-", "unknown candidate")
PLACEHOLDER_EMAIL_LOCAL_PREFIXES = ("apply.", "nologin_", "portal_candidate_", "cand_", "placeholder")
PLACEHOLDER_EMAIL_LOCAL_DOMAINS = ("example.com", "example.org", "example.net", "careers.portal")


def is_placeholder_name(value):
    s = (value or "").strip().lower()
    return ((not s) or s == "candidate" or s.startswith(PLACEHOLDER_NAME_PREFIXES)
            or s.startswith(PLACEHOLDER_NAME_PREFIXES_EXTRA))


def is_placeholder_email(value):
    s = (value or "").strip().lower()
    if (not s) or any(m in s for m in PLACEHOLDER_EMAIL_MARKERS):
        return True
    local, _, domain = s.partition("@")
    return domain in PLACEHOLDER_EMAIL_LOCAL_DOMAINS and local.startswith(PLACEHOLDER_EMAIL_LOCAL_PREFIXES)


def _first(d, keys):
    for k in keys:
        v = d.get(k) if hasattr(d, "get") else None
        if v not in (None, ""):
            return str(v).strip()
    return ""


def apply_identity(c, d):
    """Copy the real name / e-mail typed by the candidate onto the candidate row.

    Returns the list of changed field names (e.g. ["name", "email"]).
    Raises ValueError (-> API 400 VALIDATION) for a bad / already-used e-mail.
    The caller saves `c` (PortalHome.patch / DraftCommit.post already do).
    """
    changed = []

    new_name = _first(d, NAME_KEYS)
    if new_name and is_placeholder_name(c.name) and not is_placeholder_name(new_name):
        c.name = " ".join(new_name.split())[: _name_max()]
        changed.append("name")

    new_email = _first(d, EMAIL_KEYS).lower()
    if new_email and is_placeholder_email(c.email) and not is_placeholder_email(new_email):
        try:
            validate_email(new_email)
        except ValidationError:
            raise ValueError("Email is not valid.")
        clash = (EmployeeDT.objects.filter(company=c.company, email__iexact=new_email)
                 .exclude(pk=c.pk).exists())
        if clash:
            raise ValueError("This email is already used by another application. "
                             "Please use a different email or contact HR.")
        c.email = new_email
        changed.append("email")

    # the portal form posts `phone`, clean_profile only understands `phone_number`
    ph = _first(d, ("phone",))
    if ph and not c.phone_number and "phone_number" not in d:
        digits = "".join(ch for ch in ph if ch.isdigit())
        if 10 <= len(digits) <= 15:
            c.phone_number = digits[:20]
            changed.append("phone_number")
    return changed


# ============================================================
# ADDITIVE (v2): sync_identity() - one best-effort call used by Register / Login /
# draft auto-save / Submit, so the REAL name + e-mail the candidate registered with
# always reaches EmployeeDT (Django-admin, HR desk, offer letters, mails).
#
#   name  <- request data -> saved drafts (full_name / name / first+last)
#   email <- request data -> saved drafts -> portal account e-mail -> link.sent_to -> Personal_Email
#
# Only ever overwrites a PLACEHOLDER value; never raises (identity must not break a save).
# ============================================================
def _name_from(d):
    if not hasattr(d, "get"):
        return ""
    n = _first(d, NAME_KEYS)
    if not n:
        n = " ".join(x for x in (_first(d, ("first_name", "firstName")),
                                 _first(d, ("middle_name", "middleName")),
                                 _first(d, ("last_name", "lastName"))) if x)
    return n


def _email_from(d):
    return _first(d, EMAIL_KEYS).lower() if hasattr(d, "get") else ""


def sync_identity(c, link=None, data=None, save=True):
    """Returns the list of changed field names ([] when nothing to do). Never raises."""
    try:
        if not (is_placeholder_name(c.name) or is_placeholder_email(c.email)):
            return []
        names, emails = [], []
        if data is not None:
            names.append(_name_from(data))
            emails.append(_email_from(data))
        try:
            from Recruitment.models_register import CandidatePortalAccount, CandidatePortalDraft
            for dr in CandidatePortalDraft.objects.filter(candidate=c).order_by("-updated_at"):
                if isinstance(dr.data, dict):
                    names.append(_name_from(dr.data))
                    emails.append(_email_from(dr.data))
            acc = CandidatePortalAccount.objects.filter(candidate=c).first()
            if acc is not None:
                emails.append((acc.email or "").strip().lower())
        except Exception:                      # draft / account tables not present
            pass
        if link is not None:
            emails.append((getattr(link, "sent_to", "") or "").strip().lower())
        emails.append((getattr(c, "Personal_Email", "") or "").strip().lower())

        changed = []
        new_name = next((n for n in names if n and not is_placeholder_name(n)), "")
        if new_name:
            try:
                changed += apply_identity(c, {"name": new_name})
            except ValueError:
                pass
        for em in [e for e in emails if e and not is_placeholder_email(e)]:
            try:
                got = apply_identity(c, {"email": em})
            except ValueError:                 # invalid / already used -> try the next source
                continue
            if got:
                changed += got
                break
        if changed and save and c.pk:
            c.save(update_fields=sorted(set(changed)))
        return changed
    except Exception:
        return []
