# ============================================================
# ADDITIVE: Candidate Portal API  (mounted via Recruitment/urls_portal.py)
#
#   HR / Admin (JWT):   /api/recruitment/hiring-plus/candidate-links/...
#   Candidate (no login, private token in the URL):
#                       /api/recruitment/hiring-plus/public/portal/<token>/...
#
# The candidate writes into the SAME rows the HR screens already read
# (EmployeeDT, CandidateEducation, CandidateExperience, EmployeeDocument,
# DocumentReview, CandidateCompensation, CandidateProfile) - so there is no
# copy step: after interviews / offer, the normal "convert to employee"
# flow carries everything over.
# ============================================================
import logging
import os
import secrets
from datetime import date, timedelta

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from Company.models import get_client_ip
from Employee.models import (CandidateCompensation, CandidateEducation, CandidateExperience, EmployeeDocument,
                             EmployeeDT)

from . import hiring_plus as hp
from .portal_identity import apply_identity, sync_identity      # ADDITIVE: real name/email sync (was used but never imported)
from .common import (RecruitmentAuthMixin, candidate_by_ref, err, get_profile, ok, set_stage, to_bool,
                     to_decimal)
from .models import DocumentReview, JobRequisition, StageHistory
from .models_plus import HiringChecklistItem, IdentityVerification
from .models_portal import CandidatePortalActivity, CandidatePortalLink
from .views_candidates import (EDU_TEXT, EXP_TEXT, PERSONAL_MAP, STATUS_TEXT, apply_education, apply_experience,
                               apply_personal)

logger = logging.getLogger(__name__)

LAKH = 100000
MAX_FILE = 10 * 1024 * 1024
BASE_EXT = {".pdf", ".jpg", ".jpeg", ".png"}
RESUME_EXT = BASE_EXT | {".doc", ".docx"}
MAGIC = {".pdf": (b"%PDF",), ".png": (b"\x89PNG\r\n\x1a\n",), ".jpg": (b"\xff\xd8\xff",), ".jpeg": (b"\xff\xd8\xff",),
         ".docx": (b"PK\x03\x04",), ".doc": (b"\xd0\xcf\x11\xe0",)}

DOC_LABELS = dict(EmployeeDocument.DOCUMENT_TYPE_CHOICES)
# documents a candidate may add / replace himself (offer / appointment letters, PF, ESIC, BGV are HR-only)
CAND_DOC_TYPES = ["RESUME", "AADHAAR", "PAN", "ADDRESS_PROOF", "PASSPORT_PHOTO", "EDUCATION", "EXPERIENCE",
                  "BANK", "SALARY_SLIP", "OTHER"]
SINGLE_DOC_TYPES = {"RESUME", "AADHAAR", "PAN", "ADDRESS_PROOF", "PASSPORT_PHOTO", "BANK"}   # a new upload replaces
DOC_COLUMN = {"RESUME": "resume", "AADHAAR": "aadhaar_id_proof", "PAN": "pan_card",
              "ADDRESS_PROOF": "address_proof", "PASSPORT_PHOTO": "passport_photo"}     # mirrored on EmployeeDT

CLOSED_STAGES = {"JOINED", "REJECTED"}
COMP_LOCKED_STAGES = {"SELECTED", "OFFER_SENT", "OFFER_ACCEPTED", "DOCS_PENDING", "BGV", "READY_TO_JOIN"}
COMP_KEYS = ("current_ctc_lpa", "expected_ctc_lpa", "notice_period_days")
MAX_EDU, MAX_EXP, MAX_DOCS = 15, 20, 40


class Locked(Exception):
    """Raised when the candidate tries to change something HR has already frozen."""


# ============================================================
# small helpers
# ============================================================
def _nf(what="Candidate"):
    return err("NOT_FOUND", f"{what} not found.", 404)


def _stage(c):
    return (c.candidate_status or "").upper()


def _clip(v, n, label):
    s = "" if v is None else str(v).strip()
    if len(s) > n:
        raise ValueError(f"{label} is too long (max {n} characters).")
    return s


def _review_of(doc):
    try:
        return doc.review
    except DocumentReview.DoesNotExist:
        return None


def _base_urls():
    base = str(getattr(settings, "CANDIDATE_PORTAL_BASE_URL", "") or getattr(settings, "SITE_BASE_URL", "") or "")
    return base.rstrip("/")


def check_upload(f, doc_type=None):
    """Extension + size + magic-byte check. Raises ValueError with a friendly message."""
    ext = os.path.splitext(f.name or "")[1].lower()
    allowed = RESUME_EXT if doc_type == "RESUME" else BASE_EXT
    if ext not in allowed:
        raise ValueError("Only " + ", ".join(sorted(e.strip(".").upper() for e in allowed)) + " files are accepted.")
    if f.size <= 0:
        raise ValueError("The file is empty.")
    if f.size > MAX_FILE:
        raise ValueError("File too large (max 10 MB).")
    head = f.read(8)
    f.seek(0)
    if not any(head.startswith(m) for m in MAGIC[ext]):
        raise ValueError("The file content does not match its extension. Please upload the original file.")
    return ext


def log_activity(link, c, action_name, detail=None, request=None, edit=True):
    now = timezone.now()
    CandidatePortalActivity.objects.create(
        company=c.company, candidate=c, link=link, action=action_name, detail=detail or {},
        ip_address=(get_client_ip(request) if request is not None else None) or None,
        created_by=f"candidate-link:{link.pk}", updated_by=f"candidate-link:{link.pk}")
    if edit:
        link.last_edit_at = now
        link.save(update_fields=["last_edit_at", "updated_at"])


# ============================================================
# serializers (public side never returns file URLs or full Aadhaar / PAN)
# ============================================================
def _comp_lpa(c):
    try:
        comp = c.compensation_package
    except CandidateCompensation.DoesNotExist:
        return None, None
    cur = float(comp.current_annual_ctc / LAKH) if comp.current_annual_ctc is not None else None
    exp = float(comp.expected_annual_ctc / LAKH) if comp.expected_annual_ctc is not None else None
    return cur, exp


def ser_edu(e):
    return {"id": e.id, **{f: getattr(e, f) for f in EDU_TEXT}, "passing_year": e.passing_year,
            "has_certificate": bool(e.degree_certificate)}


def ser_exp(x):
    return {"id": x.id, **{f: getattr(x, f) for f in EXP_TEXT}, "start_date": x.start_date, "end_date": x.end_date,
            "previous_ctc": float(x.previous_ctc) if x.previous_ctc is not None else None,
            "has_relieving_proof": bool(x.experience_reliving_proof)}


def ser_doc(d):
    rv = _review_of(d)
    status = rv.status if rv else "Pending"
    return {"id": d.id, "document_type": d.document_type, "label": DOC_LABELS.get(d.document_type, d.document_type),
            "file_name": os.path.basename(d.file.name) if d.file else None, "uploaded_at": d.uploaded_at,
            "status": status,
            "reject_reason": (rv.remarks if rv and status == "Rejected" else None),     # only a rejection reason is shown
            "can_replace": status != "Verified", "can_delete": status != "Verified"}


def active_docs(c):
    return EmployeeDocument.objects.filter(employee=c, is_active=True, document_type__in=CAND_DOC_TYPES).order_by("id")


def missing_items(c, link):
    """What is still needed before the candidate can press Submit."""
    miss = []
    for key, label in (("Date_of_Birth", "Date of birth"), ("Gender", "Gender"),
                       ("Current_Address", "Current address")):
        if not getattr(c, key, None):
            miss.append({"section": "profile", "field": label.lower().replace(" ", "_"), "label": label})
    if not (getattr(c, "Permanent_Address", None) or getattr(c, "same_as_current_address", False)):
        miss.append({"section": "profile", "field": "permanent_address", "label": "Permanent address"})
    if not CandidateEducation.objects.filter(employee=c, is_active=True).exists():
        miss.append({"section": "education", "field": "education", "label": "At least one education record"})
    have = set(active_docs(c).values_list("document_type", flat=True))
    for t in dict.fromkeys(["RESUME"] + list(link.document_types or [])):
        if t not in have:
            miss.append({"section": "documents", "field": t, "label": f"{DOC_LABELS.get(t, t)} document"})
    return miss


def lock_state(c):
    st = _stage(c)
    return {"closed": st in CLOSED_STAGES or (c.Employee_Status or "") == "Activate",
            "compensation": st in COMP_LOCKED_STAGES,
            "aadhaar": IdentityVerification.objects.filter(candidate=c, id_type="AADHAAR", status="Verified").exists(),
            "pan": IdentityVerification.objects.filter(candidate=c, id_type="PAN", status="Verified").exists()}


def snapshot(link, c):
    lk = lock_state(c)
    prof = get_profile(c, create=False)
    cur, exp = _comp_lpa(c)
    miss = missing_items(c, link)
    total_required = 5 + len(dict.fromkeys(["RESUME"] + list(link.document_types or [])))
    co = getattr(link.company, "Registered_Company_Name", None) or str(link.company)
    aad, pan = getattr(c, "aadhaar_number", None), getattr(c, "pan_number", None)
    locked = [k for k in ("compensation", "aadhaar", "pan") if lk[k]]
    return {
        "company": co,
        "candidate": {"name": c.name, "email": c.email, "phone_number": c.phone_number,
                      "applied_position": c.applied_position, "candidate_id": c.candidate_id},
        "status_text": STATUS_TEXT.get(_stage(c), "In progress"),
        "link": {"expires_at": link.expires_at, "submitted_at": link.submitted_at, "last_edit_at": link.last_edit_at,
                 "editable": not lk["closed"], "locked_sections": locked},
        "profile": {k: getattr(c, col, None) for k, col in PERSONAL_MAP.items() if k not in ("aadhaar_number", "pan_number")}
                   | {"same_as_current_address": bool(getattr(c, "same_as_current_address", False)),
                      "aadhaar_masked": hp.mask_aadhaar(aad), "pan_masked": ("******" + str(pan)[-4:]) if pan else None},
        "career": {"current_company": getattr(prof, "current_company", None),
                   "total_experience_years": (float(prof.total_experience_years)
                                              if prof and prof.total_experience_years is not None else None),
                   "notice_period_days": getattr(prof, "notice_period_days", None),
                   "current_ctc_lpa": cur, "expected_ctc_lpa": exp,
                   "notice_period_options": list(hp.notice_period_options())},
        "education": [ser_edu(e) for e in CandidateEducation.objects.filter(employee=c, is_active=True).order_by("id")],
        "experience": [ser_exp(x) for x in CandidateExperience.objects.filter(employee=c, is_active=True).order_by("id")],
        "documents": [ser_doc(d) for d in active_docs(c)],
        "requested_documents": [{"code": t, "label": DOC_LABELS.get(t, t)} for t in (link.document_types or [])],
        "document_types": [{"code": t, "label": DOC_LABELS.get(t, t), "replaces_existing": t in SINGLE_DOC_TYPES}
                           for t in CAND_DOC_TYPES],
        "progress": {"percent": max(0, round(100 * (total_required - len(miss)) / total_required)), "missing": miss},
        "limits": {"max_mb": MAX_FILE // (1024 * 1024), "allowed_types": sorted(BASE_EXT),
                   "resume_types": sorted(RESUME_EXT)},
    }


# ============================================================
# profile update rules
# ============================================================
def clean_profile(c, d):
    """Validate the candidate's own profile fields. Returns (cleaned dict for apply_personal, changed field names)."""
    lk = lock_state(c)
    out, changed = {}, []
    if "phone_number" in d:
        ph = _clip(d.get("phone_number"), 20, "Phone number")
        digits = "".join(ch for ch in ph if ch.isdigit())
        if ph and not (10 <= len(digits) <= 15):
            raise ValueError("Phone number must have 10 to 15 digits.")
        c.phone_number = ph or c.phone_number
        changed.append("phone_number")
    for k in PERSONAL_MAP:
        if k not in d:
            continue
        v = d.get(k)
        v = None if v in (None, "") else v
        if k == "date_of_birth" and v is not None:
            from .common import to_date
            dob = to_date(v)
            if dob is None or dob >= date.today() or dob.year < date.today().year - 100:
                raise ValueError("Please enter a valid date of birth.")
        elif k == "personal_email" and v is not None:
            try:
                validate_email(str(v).strip())
            except ValidationError:
                raise ValueError("Personal email is not valid.")
            v = str(v).strip().lower()
        elif k == "alternate_phone_number" and v is not None:
            v = _clip(v, 20, "Alternate phone")
            if not (10 <= sum(ch.isdigit() for ch in v) <= 15):
                raise ValueError("Alternate phone must have 10 to 15 digits.")
        elif k in ("current_address", "permanent_address") and v is not None:
            v = _clip(v, 500, k.replace("_", " ").capitalize())
        elif k == "aadhaar_number" and v is not None:
            v = hp.normalize_aadhaar(v)
            if v != (getattr(c, "aadhaar_number", None) or "") and lk["aadhaar"]:
                raise Locked("Your Aadhaar is already verified by HR, so it can no longer be changed here.")
            if v == (getattr(c, "aadhaar_number", None) or ""):
                continue
        elif k == "pan_number" and v is not None:
            v = hp.normalize_pan(v)
            if v != (getattr(c, "pan_number", None) or "") and lk["pan"]:
                raise Locked("Your PAN is already verified by HR, so it can no longer be changed here.")
            if v == (getattr(c, "pan_number", None) or ""):
                continue
        elif v is not None:
            v = _clip(v, 100, k.replace("_", " ").capitalize())
        out[k] = v if v is not None else ""
        changed.append(k)
    if "same_as_current_address" in d:
        out["same_as_current_address"] = d.get("same_as_current_address")
        changed.append("same_as_current_address")
    return out, changed


def apply_career(c, d):
    """current company / notice period / CTC. Locked once HR has selected the candidate (hike policy depends on it)."""
    keys = [k for k in ("current_company", "total_experience_years", *COMP_KEYS) if k in d]
    if not keys:
        return []
    if any(k in COMP_KEYS for k in keys) and lock_state(c)["compensation"]:
        raise Locked("Salary and notice-period details are frozen now that HR has moved your application forward. "
                     "Please contact HR to change them.")
    bad = hp.validate_notice_period(d)
    if bad:
        raise ValueError(bad)
    prof = get_profile(c, c.company)
    if "current_company" in d:
        prof.current_company = _clip(d.get("current_company"), 150, "Current company") or None
    if "total_experience_years" in d:
        v = to_decimal(d.get("total_experience_years"))
        if v is not None and not (0 <= v <= 60):
            raise ValueError("Total experience must be between 0 and 60 years.")
        prof.total_experience_years = v
    if d.get("notice_period_days") not in (None, ""):
        prof.notice_period_days = int(d.get("notice_period_days"))
        c.Current_Notice_Period = f"{prof.notice_period_days} Days"
    prof.updated_by = f"candidate:{c.pk}"
    prof.save()
    if any(k in d for k in ("current_ctc_lpa", "expected_ctc_lpa")):
        comp, _ = CandidateCompensation.objects.get_or_create(employee=c)
        for key, col in (("current_ctc_lpa", "current_annual_ctc"), ("expected_ctc_lpa", "expected_annual_ctc")):
            if key in d:
                v = to_decimal(d.get(key))
                if v is not None and not (0 <= v <= 1000):
                    raise ValueError(f"{key.replace('_', ' ')} must be between 0 and 1000 (in LPA).")
                setattr(comp, col, v * LAKH if v is not None else None)
        comp.save()
    return keys


# ============================================================
# ADMIN / HR side
# ============================================================
def ser_link(l, request=None):
    now = timezone.now()
    if l.revoked:
        status = "Revoked"
    elif l.expires_at < now:
        status = "Expired"
    elif l.submitted_at and l.last_edit_at and l.last_edit_at > l.submitted_at:
        status = "Updated after submit"
    elif l.submitted_at:
        status = "Submitted"
    elif l.last_edit_at:
        status = "In progress"
    elif l.first_opened_at:
        status = "Opened"
    else:
        status = "Not opened"
    base = _base_urls()
    return {"id": l.id, "candidate": l.candidate_id, "candidate_name": l.candidate.name,
            "candidate_code": l.candidate.candidate_id, "status": status, "document_types": l.document_types,
            "expires_at": l.expires_at, "revoked": l.revoked, "sent_to": l.sent_to,
            "first_opened_at": l.first_opened_at, "last_opened_at": l.last_opened_at, "last_edit_at": l.last_edit_at,
            "submitted_at": l.submitted_at, "submit_count": l.submit_count, "created_at": l.created_at,
            "frontend_path": f"/candidate-portal/{l.token}", "frontend_url": f"{base}/candidate-portal/{l.token}",
            "portal_api": f"/api/recruitment/hiring-plus/public/portal/{l.token}/"}


class CandidatePortalLinkViewSet(RecruitmentAuthMixin, ViewSet):
    permission_action_map = {"revoke": "edit", "activity": "view"}

    def _qs(self):
        return CandidatePortalLink.objects.filter(company=self.company(), is_active=True).select_related("candidate")

    def list(self, request):
        qs = self._qs()
        ref = request.query_params.get("candidate")
        if ref:
            c = candidate_by_ref(self.company(), ref)
            qs = qs.filter(candidate=c) if c else qs.none()
        s = request.query_params.get("submitted")
        if s not in (None, ""):
            qs = qs.filter(submitted_at__isnull=not to_bool(s))
        return ok("PORTAL_LINKS", "Candidate portal links.", [ser_link(l, request) for l in qs[:200]])

    def retrieve(self, request, pk=None):
        l = self._qs().filter(pk=pk if str(pk).isdigit() else -1).first()
        if l is None:
            return _nf("Link")
        return ok("PORTAL_LINK", "Link.", ser_link(l, request))

    def _new_candidate(self, d):
        company = self.company()
        name, email = (d.get("name") or "").strip(), (d.get("email") or "").strip().lower()
        if not name or not email:
            raise ValueError("Pass an existing 'candidate' OR a new candidate's name and email.")
        try:
            validate_email(email)
        except ValidationError:
            raise ValueError("Email is not valid.")
        if EmployeeDT.objects.filter(company=company, email__iexact=email).exists():
            raise LookupError("A candidate/employee with this email already exists. Send the link with that 'candidate' id.")
        req = None
        if d.get("requisition"):
            ref = str(d.get("requisition"))
            req = JobRequisition.objects.filter(company=company, is_active=True).filter(
                Q(requisition_id=ref) | Q(pk=int(ref) if ref.isdigit() else -1)).first()
            if req is None:
                raise ValueError("Requisition not found.")
        c = EmployeeDT(company=company, name=name, email=email,
                       phone_number=d.get("phone_number") or d.get("phone"),
                       applied_position=d.get("applied_position") or (req.position_title if req else None),
                       candidate_source=d.get("source") or "Candidate portal link",
                       candidate_status="APPLIED", Employee_Status="Candidate", is_active=False,
                       application_submitted=False, created_by=self.actor(), updated_by=self.actor())
        c.save()
        if req is not None:
            prof = get_profile(c, company)
            prof.requisition = req
            prof.updated_by = self.actor()
            prof.save()
        StageHistory.objects.create(company=company, candidate=c, from_stage=None, to_stage="APPLIED",
                                    note="Candidate invited via portal link", changed_by=self.actor())
        hp.on_candidate_created(c, self.actor())
        return c

    @transaction.atomic
    def create(self, request):
        d = request.data
        company = self.company()
        types = d.get("document_types") or []
        types = [t.strip() for t in (types if isinstance(types, list) else str(types).split(",")) if str(t).strip()]
        types = [t.upper() for t in types]
        bad = [t for t in types if t not in CAND_DOC_TYPES]
        if bad:
            return err("VALIDATION", f"Document type(s) not allowed on this link: {', '.join(bad)}.")
        try:
            days = min(max(int(d.get("expires_in_days") or 7), 1), 30)
        except (TypeError, ValueError):
            return err("VALIDATION", "expires_in_days must be a number.")
        c = None
        if d.get("candidate"):
            c = candidate_by_ref(company, d.get("candidate"))
            if c is None:
                return _nf()
        else:
            try:
                c = self._new_candidate(d)
            except ValueError as e:
                return err("VALIDATION", str(e))
            except LookupError as e:
                return err("DUPLICATE", str(e), 409)
        if lock_state(c)["closed"]:
            return err("CLOSED", "This person has already joined or was rejected, so a details link cannot be sent.")
        # one live link per candidate: older ones stop working as soon as a new one is issued
        CandidatePortalLink.objects.filter(candidate=c, revoked=False).update(revoked=True)
        link = CandidatePortalLink.objects.create(
            company=company, candidate=c, token=secrets.token_urlsafe(32), document_types=types,
            expires_at=timezone.now() + timedelta(days=days), created_by=self.actor(), updated_by=self.actor())
        mailed = False
        to = d.get("send_to") or (c.email if to_bool(d.get("send_email")) else None)
        if to:
            try:
                from django.core.mail import send_mail
                url = f"{_base_urls()}/candidate-portal/{link.token}"
                send_mail("Please complete your application details",
                          f"Hello {c.name},\n\nPlease use the private link below to fill in your details and upload "
                          f"your documents. You can come back and update them until the link expires "
                          f"({days} days).\n\n{url}\n\nPlease do not share this link with anyone.\n\nHR Team",
                          getattr(settings, "DEFAULT_FROM_EMAIL", None), [to], fail_silently=False)
                link.sent_to, mailed = to, True
                link.save(update_fields=["sent_to", "updated_at"])
            except Exception:
                logger.exception("candidate portal link email failed")
        return ok("PORTAL_LINK_CREATED", "Candidate link created.", ser_link(link, request), status=201,
                  email_sent=mailed)

    @action(detail=True, methods=["post"])
    def revoke(self, request, pk=None):
        l = self._qs().filter(pk=pk if str(pk).isdigit() else -1).first()
        if l is None:
            return _nf("Link")
        l.revoked, l.updated_by = True, self.actor()
        l.save()
        return ok("PORTAL_LINK_REVOKED", "Link revoked.", ser_link(l, request))

    @action(detail=True, methods=["get"])
    def activity(self, request, pk=None):
        l = self._qs().filter(pk=pk if str(pk).isdigit() else -1).first()
        if l is None:
            return _nf("Link")
        rows = CandidatePortalActivity.objects.filter(candidate=l.candidate, company=self.company())[:200]
        return ok("PORTAL_ACTIVITY", "What the candidate did through the link.",
                  [{"id": a.id, "action": a.action, "detail": a.detail, "ip_address": a.ip_address,
                    "at": a.created_at, "link": a.link_id} for a in rows])


# ============================================================
# PUBLIC side (no login - the private token is the credential)
# ============================================================
class PortalThrottle(SimpleRateThrottle):
    rate = "120/min"
    scope = "candidate_portal"

    def get_cache_key(self, request, view):
        return f"throttle_{self.scope}_{self.get_ident(request)}"


class PortalBase(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]
    throttle_classes = [PortalThrottle]

    def _ctx(self, token, write=False):
        """-> (link, candidate, error_response)"""
        l = CandidatePortalLink.objects.filter(token=token, is_active=True).select_related(
            "candidate", "company").first()
        if l is None:
            return None, None, err("INVALID_LINK", "This link is not valid.", 404)
        if l.revoked or l.expires_at < timezone.now():
            return None, None, err("LINK_EXPIRED", "This link has expired. Please ask HR for a new one.", 410)
        c = l.candidate
        if write and lock_state(c)["closed"]:
            return None, None, err("CLOSED", "Your application is closed, so changes can no longer be made.", 403)
        return l, c, None

    def _locked(self, e):
        return err("LOCKED", str(e), 403)


class PortalHome(PortalBase):
    """GET snapshot of everything - PATCH/POST profile + career fields."""

    def get(self, request, token):
        l, c, e = self._ctx(token)
        if e:
            return e
        now = timezone.now()
        l.first_opened_at = l.first_opened_at or now
        l.last_opened_at = now
        l.save(update_fields=["first_opened_at", "last_opened_at", "updated_at"])
        return ok("PORTAL", "Your application details.", snapshot(l, c))

    @transaction.atomic
    def patch(self, request, token):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        d = request.data
        try:
            cleaned, changed = clean_profile(c, d)
            apply_personal(c, cleaned, None)
            changed += apply_identity(c, d)      
            changed += apply_career(c, d)
        except Locked as x:
            transaction.set_rollback(True)
            return self._locked(x)
        except ValueError as x:
            transaction.set_rollback(True)
            return err("VALIDATION", str(x))
        c.updated_by = f"candidate-link:{l.pk}"
        c.save()
        if changed:
            log_activity(l, c, "PROFILE_UPDATED", {"fields": sorted(set(changed))}, request)
        return ok("PORTAL_UPDATED", "Saved.", snapshot(l, c))

    post = patch


class _ChildList(PortalBase):
    model = apply_fn = ser_fn = None
    file_field, label, limit = None, "", 0

    def _fill(self, obj, d):
        raise NotImplementedError

    @transaction.atomic
    def post(self, request, token):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        if self.model.objects.filter(employee=c, is_active=True).count() >= self.limit:
            return err("LIMIT", f"You can add at most {self.limit} {self.label} records.")
        obj = self.model(employee=c, created_by=f"candidate-link:{l.pk}", updated_by=f"candidate-link:{l.pk}")
        try:
            self._fill(obj, request.data)
            up = request.FILES.get(self.file_field)
            if up is not None:
                check_upload(up)
                setattr(obj, self.file_field, up)
            obj.save()
        except ValueError as x:
            transaction.set_rollback(True)
            return err("VALIDATION", str(x))
        self._after(c)
        log_activity(l, c, f"{self.label.upper()}_ADDED", {"id": obj.id}, request)
        return ok(f"PORTAL_{self.label.upper()}_ADDED", "Saved.", type(self).ser_fn(obj), status=201)

    def _after(self, c):
        pass


class _ChildItem(PortalBase):
    model = ser_fn = None
    file_field, label = None, ""

    def _fill(self, obj, d):
        raise NotImplementedError

    def _get(self, c, pk):
        return self.model.objects.filter(employee=c, is_active=True, pk=pk).first()

    @transaction.atomic
    def patch(self, request, token, pk):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        obj = self._get(c, pk)
        if obj is None:
            return _nf("Record")
        try:
            self._fill(obj, request.data)
            up = request.FILES.get(self.file_field)
            if up is not None:
                check_upload(up)
                setattr(obj, self.file_field, up)
        except ValueError as x:
            transaction.set_rollback(True)
            return err("VALIDATION", str(x))
        obj.updated_by = f"candidate-link:{l.pk}"
        obj.save()
        self._after(c)
        log_activity(l, c, f"{self.label.upper()}_UPDATED", {"id": obj.id}, request)
        return ok(f"PORTAL_{self.label.upper()}_UPDATED", "Saved.", type(self).ser_fn(obj))

    put = patch

    @transaction.atomic
    def delete(self, request, token, pk):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        obj = self._get(c, pk)
        if obj is None:
            return _nf("Record")
        obj.is_active, obj.updated_by = False, f"candidate-link:{l.pk}"
        obj.save()
        self._after(c)
        log_activity(l, c, f"{self.label.upper()}_DELETED", {"id": obj.id}, request)
        return ok(f"PORTAL_{self.label.upper()}_DELETED", "Deleted.")

    def _after(self, c):
        pass


def _fill_edu(obj, d):
    for f in EDU_TEXT:
        if f in d:
            _clip(d.get(f), 255, f.replace("_", " ").capitalize())
    if "passing_year" in d and d.get("passing_year") not in (None, ""):
        try:
            y = int(d["passing_year"])
        except (TypeError, ValueError):
            raise ValueError("passing_year must be a year, e.g. 2019.")
        if not 1950 <= y <= date.today().year + 6:
            raise ValueError("passing_year is out of range.")
    apply_education(obj, d)


def _fill_exp(obj, d):
    for f in EXP_TEXT:
        if f in d:
            _clip(d.get(f), 2000 if f == "core_responsibilities" else 255, f.replace("_", " ").capitalize())
    apply_experience(obj, d)
    if "previous_ctc" in d and obj.previous_ctc is not None and obj.previous_ctc < 0:
        raise ValueError("previous_ctc cannot be negative.")


class PortalEducationList(_ChildList):
    model, ser_fn, label, limit, file_field = CandidateEducation, staticmethod(ser_edu), "education", MAX_EDU, "degree_certificate"
    _fill = staticmethod(_fill_edu)


class PortalEducationItem(_ChildItem):
    model, ser_fn, label, file_field = CandidateEducation, staticmethod(ser_edu), "education", "degree_certificate"
    _fill = staticmethod(_fill_edu)


class PortalExperienceList(_ChildList):
    model, ser_fn, label, limit, file_field = CandidateExperience, staticmethod(ser_exp), "experience", MAX_EXP, "experience_reliving_proof"
    _fill = staticmethod(_fill_exp)

    def _after(self, c):
        hp.sync_experience(c)


class PortalExperienceItem(_ChildItem):
    model, ser_fn, label, file_field = CandidateExperience, staticmethod(ser_exp), "experience", "experience_reliving_proof"
    _fill = staticmethod(_fill_exp)

    def _after(self, c):
        hp.sync_experience(c)


# ---------------- documents ----------------
def _store_document(link, c, dtype, f, replacing=None):
    actor = f"candidate-link:{link.pk}"
    if replacing is not None:
        olds = [replacing]
    elif dtype in SINGLE_DOC_TYPES:
        olds = list(EmployeeDocument.objects.filter(employee=c, is_active=True, document_type=dtype))
    else:
        olds = []
        if EmployeeDocument.objects.filter(employee=c, is_active=True, document_type__in=CAND_DOC_TYPES).count() >= MAX_DOCS:
            raise ValueError(f"You can keep at most {MAX_DOCS} documents.")
    for o in olds:
        rv = _review_of(o)
        if rv is not None and rv.status == "Verified":
            raise Locked(f"Your {DOC_LABELS.get(dtype, dtype)} is already verified by HR and cannot be replaced.")
    check_upload(f, dtype)
    doc = EmployeeDocument.objects.create(
        company=c.company, employee=c, document_type=dtype, document_name=f"{c.name} {DOC_LABELS.get(dtype, dtype)}",
        file=f, created_by=actor, updated_by=actor)
    DocumentReview.objects.create(document=doc, status="Pending")
    for o in olds:
        o.is_active, o.updated_by = False, actor
        o.remarks = "Replaced by candidate through portal link"
        o.save()
    col = DOC_COLUMN.get(dtype)
    if col:
        setattr(c, col, doc.file.name)
        c.save(update_fields=[col])
    HiringChecklistItem.objects.filter(candidate=c, doc_type=dtype, is_done=False).update(
        is_done=True, done_by=actor, done_at=timezone.now())
    if _stage(c) == "OFFER_ACCEPTED":
        set_stage(c, "DOCS_PENDING", actor, "Documents uploaded via candidate link")
    return doc, bool(olds)


class PortalDocuments(PortalBase):
    @transaction.atomic
    def post(self, request, token):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        dtype = (request.data.get("document_type") or "").upper()
        if dtype not in CAND_DOC_TYPES:
            return err("VALIDATION", "document_type must be one of: " + ", ".join(CAND_DOC_TYPES) + ".")
        f = request.FILES.get("file")
        if f is None:
            return err("VALIDATION", "file is required.")
        try:
            doc, replaced = _store_document(l, c, dtype, f)
        except Locked as x:
            transaction.set_rollback(True)
            return self._locked(x)
        except ValueError as x:
            transaction.set_rollback(True)
            return err("VALIDATION", str(x))
        log_activity(l, c, "DOC_REPLACED" if replaced else "DOC_UPLOADED", {"type": dtype, "id": doc.id}, request)
        return ok("PORTAL_DOCUMENT_SAVED", "Document received.", ser_doc(doc), status=201, replaced=replaced)


class PortalDocumentItem(PortalBase):
    def _doc(self, c, pk):
        return active_docs(c).filter(pk=pk).first()

    @transaction.atomic
    def put(self, request, token, pk):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        old = self._doc(c, pk)
        if old is None:
            return _nf("Document")
        f = request.FILES.get("file")
        if f is None:
            return err("VALIDATION", "file is required.")
        try:
            doc, _ = _store_document(l, c, old.document_type, f, replacing=old)
        except Locked as x:
            transaction.set_rollback(True)
            return self._locked(x)
        except ValueError as x:
            transaction.set_rollback(True)
            return err("VALIDATION", str(x))
        log_activity(l, c, "DOC_REPLACED", {"type": doc.document_type, "id": doc.id}, request)
        return ok("PORTAL_DOCUMENT_REPLACED", "Document replaced.", ser_doc(doc))

    patch = put

    @transaction.atomic
    def delete(self, request, token, pk):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        d = self._doc(c, pk)
        if d is None:
            return _nf("Document")
        rv = _review_of(d)
        if rv is not None and rv.status == "Verified":
            return self._locked("This document is already verified by HR and cannot be removed.")
        d.is_active, d.updated_by = False, f"candidate-link:{l.pk}"
        d.remarks = "Removed by candidate through portal link"
        d.save()
        if not active_docs(c).filter(document_type=d.document_type).exists():
            HiringChecklistItem.objects.filter(candidate=c, doc_type=d.document_type, is_done=True,
                                               done_by__startswith="candidate-link:").update(
                is_done=False, done_by=None, done_at=None)
            col = DOC_COLUMN.get(d.document_type)
            if col and getattr(c, col, None) and getattr(c, col).name == d.file.name:
                setattr(c, col, None)
                c.save(update_fields=[col])
        log_activity(l, c, "DOC_DELETED", {"type": d.document_type, "id": d.id}, request)
        return ok("PORTAL_DOCUMENT_DELETED", "Document removed.")


class PortalSubmit(PortalBase):
    """Candidate says 'I'm done'. Can be pressed again after later edits (HR sees 'Updated after submit')."""

    @transaction.atomic
    def post(self, request, token):
        l, c, e = self._ctx(token, write=True)
        if e:
            return e
        sync_identity(c, l)                        # ADDITIVE: make sure HR sees the real name / e-mail
        miss = missing_items(c, l)
        if miss:
            return err("INCOMPLETE", "Please complete the missing items before submitting.", errors=miss)
        now = timezone.now()
        c.application_submitted, c.application_submitted_at = True, c.application_submitted_at or now
        c.save(update_fields=["application_submitted", "application_submitted_at"])
        l.submitted_at, l.submit_count = now, l.submit_count + 1
        l.save(update_fields=["submitted_at", "submit_count", "updated_at"])
        log_activity(l, c, "SUBMITTED" if l.submit_count == 1 else "RESUBMITTED", {}, request, edit=False)
        try:                                       # best-effort heads-up to the recruiter
            prof = get_profile(c, create=False)
            to = getattr(getattr(prof, "recruiter", None), "email", None)
            if to:
                from django.core.mail import send_mail
                send_mail(f"{c.name} completed the application details",
                          f"{c.name} ({c.candidate_id}) has submitted the details and documents through the "
                          f"candidate link. Please review them in the Recruitment module.",
                          getattr(settings, "DEFAULT_FROM_EMAIL", None), [to], fail_silently=True)
        except Exception:
            logger.exception("portal submit notification failed")
        return ok("PORTAL_SUBMITTED", "Thank you! HR has been notified.", snapshot(l, c))
