# ============================================================
# ADDITIVE: Hiring Plus - business logic (no HTTP here)
#
#   * Aadhaar / PAN validation + pluggable Aadhaar OTP provider
#   * maker / checker (M-level) approval of new candidates
#   * hike policy (last CTC vs offered CTC, default limit 10 %)
#   * experience table, fresher / experienced, JD link
#   * hiring kit seed, onboarding trigger, post-hire role map
#
# Every function that is called from existing code is defensive:
# a failure here is logged and never breaks the existing flow.
# ============================================================
import hashlib
import hmac
import json
import logging
import re
import secrets
import urllib.error
import urllib.request
from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP

from django.conf import settings
from django.utils import timezone

from Employee.employee_crud_permissions import _role_is_usable, resolve_actor_role
from Employee.models import (CandidateCompensation, CandidateEducation, CandidateExperience,
                             EmployeeDocument, EmployeeDT)

logger = logging.getLogger(__name__)
LAKH = Decimal("100000")


# ---------------------------------------------------------------
# settings (all optional, safe defaults)
# ---------------------------------------------------------------
def cfg(name, default):
    return getattr(settings, name, default)


def hike_limit_percent():
    return Decimal(str(cfg("HIRING_HIKE_LIMIT_PERCENT", 10)))


def notice_period_options():
    return [int(x) for x in cfg("HIRING_NOTICE_PERIOD_OPTIONS", (30, 60, 90))]


def m_level_role_codes():
    return {str(x).lower() for x in cfg(
        "HIRING_M_LEVEL_ROLE_CODES",
        ("m_level", "manager", "hr_manager", "hiring_manager", "hr_head", "chro", "hcm", "director", "ceo"))}


# ===============================================================
# 1. AADHAAR / PAN
# ===============================================================
_VERHOEFF_D = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]
_VERHOEFF_P = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]


def verhoeff_valid(number):
    c = 0
    for i, ch in enumerate(reversed(number)):
        c = _VERHOEFF_D[c][_VERHOEFF_P[i % 8][int(ch)]]
    return c == 0


def normalize_aadhaar(value):
    """Return the 12 digit Aadhaar string or raise ValueError with a clear message."""
    digits = re.sub(r"[\s-]", "", str(value or ""))
    if not digits.isdigit() or len(digits) != 12:
        raise ValueError("Aadhaar number must be exactly 12 digits.")
    if digits[0] in "01":
        raise ValueError("Aadhaar number cannot start with 0 or 1.")
    if not verhoeff_valid(digits):
        raise ValueError("Aadhaar number is invalid (checksum failed). Please re-check the digits.")
    return digits


def id_hash(value):
    """Keyed hash used for duplicate detection (the number itself is not kept in the verification table)."""
    key = str(settings.SECRET_KEY).encode()
    return hmac.new(key, str(value).strip().upper().encode(), hashlib.sha256).hexdigest()


def mask_aadhaar(value):
    v = str(value or "")
    return ("XXXX XXXX " + v[-4:]) if len(v) >= 4 else None


PAN_RE = re.compile(r"^[A-Z]{5}[0-9]{4}[A-Z]$")
PAN_HOLDER = {"P": "Individual", "C": "Company", "H": "HUF", "F": "Firm", "A": "AOP", "B": "BOI",
              "L": "Local Authority", "J": "Artificial Juridical Person", "G": "Government", "T": "Trust"}


def normalize_pan(value):
    pan = str(value or "").strip().upper()
    if not PAN_RE.match(pan):
        raise ValueError("PAN must look like ABCDE1234F (5 letters, 4 digits, 1 letter).")
    if pan[3] not in PAN_HOLDER:
        raise ValueError("PAN 4th character is not a valid holder type.")
    return pan


def _tokens(name):
    return {t for t in re.sub(r"[^a-z ]", " ", str(name or "").lower()).split() if len(t) > 1}


def names_match(a, b):
    ta, tb = _tokens(a), _tokens(b)
    if not ta or not tb:
        return None
    return len(ta & tb) >= max(1, min(len(ta), len(tb)) - 1) if min(len(ta), len(tb)) > 1 else bool(ta & tb)


# ---------------------------------------------------------------
# Aadhaar OTP providers.
# UIDAI does not allow a plain "number -> details" lookup. The only
# legal online route is OTP to the mobile registered with Aadhaar,
# through a licensed AUA/KUA or an aggregator. Configure one below.
# ---------------------------------------------------------------
class ProviderError(Exception):
    pass


class ProviderUnavailable(ProviderError):
    pass


class ManualProvider:
    name = "manual"

    def send_otp(self, number):
        raise ProviderUnavailable(
            "No Aadhaar verification provider is configured (HIRING_AADHAAR_PROVIDER). "
            "The number format / checksum is validated; use manual document verification to complete it.")

    def submit_otp(self, ref, otp):
        raise ProviderUnavailable("No Aadhaar verification provider is configured.")


class MockProvider:
    """For development and tests only. OTP is always 123456."""
    name = "mock"

    def send_otp(self, number):
        return {"ref": "MOCK-" + secrets.token_hex(6)}

    def submit_otp(self, ref, otp):
        if str(otp) != "123456":
            raise ProviderError("Invalid OTP.")
        return {"name": cfg("HIRING_MOCK_AADHAAR_NAME", None), "dob": cfg("HIRING_MOCK_AADHAAR_DOB", None),
                "gender": None}


class HttpOtpProvider:
    """
    Generic JSON-over-HTTPS aggregator adapter, driven by settings:

    HIRING_AADHAAR_HTTP = {
        "generate_url": "https://<provider>/<generate-otp-path>",
        "submit_url":   "https://<provider>/<submit-otp-path>",
        "token":        os.getenv("AADHAAR_API_TOKEN"),
        "id_field":     "id_number",     # request key carrying the Aadhaar number
        "ref_field":    "client_id",     # key in the generate response `data` and in the submit request
        "otp_field":    "otp",
        "timeout":      20,
    }
    Field names differ per vendor - map them here. Confirm against your vendor's API document.
    """
    name = "http"

    def __init__(self):
        self.c = cfg("HIRING_AADHAAR_HTTP", {}) or {}
        if not (self.c.get("generate_url") and self.c.get("submit_url") and self.c.get("token")):
            raise ProviderUnavailable("HIRING_AADHAAR_HTTP is not fully configured.")

    def _post(self, url, payload):
        req = urllib.request.Request(
            url, data=json.dumps(payload).encode(), method="POST",
            headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.c['token']}"})
        try:
            with urllib.request.urlopen(req, timeout=int(self.c.get("timeout", 20))) as r:
                return json.loads(r.read().decode() or "{}")
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read().decode() or "{}")
            except ValueError:
                body = {}
            raise ProviderError(body.get("message") or f"Provider rejected the request ({e.code}).")
        except (urllib.error.URLError, TimeoutError, ValueError):
            raise ProviderError("Aadhaar provider is not reachable. Try again later.")

    def send_otp(self, number):
        body = self._post(self.c["generate_url"], {self.c.get("id_field", "id_number"): number})
        data = body.get("data") or {}
        ref = data.get(self.c.get("ref_field", "client_id"))
        if not ref:
            raise ProviderError(body.get("message") or "Provider did not return an OTP reference.")
        return {"ref": str(ref)}

    def submit_otp(self, ref, otp):
        body = self._post(self.c["submit_url"], {self.c.get("ref_field", "client_id"): ref,
                                                 self.c.get("otp_field", "otp"): str(otp)})
        data = body.get("data") or {}
        if body.get("success") is False or not data:
            raise ProviderError(body.get("message") or "OTP verification failed.")
        return {"name": data.get("full_name") or data.get("name"), "dob": data.get("dob"),
                "gender": data.get("gender")}


def get_provider():
    kind = str(cfg("HIRING_AADHAAR_PROVIDER", "manual")).lower()
    if kind == "mock":
        return MockProvider()
    if kind == "http":
        return HttpOtpProvider()
    return ManualProvider()


# ===============================================================
# 2. M-LEVEL / maker-checker
# ===============================================================
def is_m_level(user):
    """Company admin, or an employee whose role is an M-level role / can manage recruitment."""
    if resolve_actor_role(user) == "admin":
        return True
    role = _role_is_usable(user)
    if role is None:
        return False
    return (str(role.role_code or "").lower() in m_level_role_codes()
            or bool(getattr(role, "can_manage_recruitment", False)))


def approval_gate_error(c, target_stage):
    """Message when the candidate's creation approval blocks a move, else None."""
    from .models_plus import CandidateApproval
    target = (target_stage or "").upper()
    if target in ("REJECTED", "APPLIED", "SCREENING", "SHORTLISTED"):
        return None
    ap = CandidateApproval.objects.filter(candidate=c).first()
    if ap is None or ap.status == "Approved":
        return None            # old candidates (no record) keep working
    if ap.status == "Rejected":
        return "Candidate creation was rejected by the checker. Reject or re-submit the candidate."
    return ("Candidate creation is awaiting approval from an M-level checker. "
            "The candidate cannot move to Interview or later until it is approved.")


def on_candidate_created(c, actor):
    """Called once, right after a new candidate is saved."""
    from .models_plus import CandidateApproval
    try:
        CandidateApproval.objects.get_or_create(
            candidate=c, defaults={"company": c.company, "maker": actor, "created_by": actor, "updated_by": actor})
        seed_checklist(c, actor)
    except Exception:
        logger.exception("on_candidate_created hook failed for candidate %s", c.pk)


# ===============================================================
# 3. HIRING KIT seed (to-do + documentation checklist)
# ===============================================================
DEFAULT_TODO = [
    ("Screen resume against JD", "Todo", None),
    ("Confirm hiring questions answered", "Todo", None),
    ("Identify interviewer(s)", "Todo", None),
    ("Initiate PAN / Aadhaar / education / experience verification", "Todo", None),
    ("Checker (M-level) approval of candidate", "Todo", None),
]
DEFAULT_DOCS = [
    ("PAN card", "Documentation", "PAN"), ("Aadhaar card", "Documentation", "AADHAAR"),
    ("Education certificates", "Documentation", "EDUCATION"), ("Experience / relieving letters", "Documentation", "EXPERIENCE"),
    ("Passport size photo", "Documentation", "PASSPORT_PHOTO"), ("Bank proof", "Documentation", "BANK"),
]


def seed_checklist(c, actor=None):
    from .models_plus import HiringChecklistItem
    if HiringChecklistItem.objects.filter(candidate=c).exists():
        return
    for i, (title, cat, dt) in enumerate(DEFAULT_TODO + DEFAULT_DOCS, 1):
        HiringChecklistItem.objects.create(company=c.company, candidate=c, title=title, category=cat,
                                           doc_type=dt, sort_order=i, created_by=actor, updated_by=actor)


def checklist_progress(c):
    from .models_plus import HiringChecklistItem
    items = list(HiringChecklistItem.objects.filter(candidate=c, is_active=True))
    done = sum(1 for i in items if i.is_done)
    return {"total": len(items), "done": done, "percent": round(done * 100 / len(items)) if items else 0}


# ===============================================================
# 4. EXPERIENCE TABLE / FRESHER / JD / NOTICE PERIOD
# ===============================================================
def _months_between(a, b):
    return max((b.year - a.year) * 12 + (b.month - a.month) + (1 if b.day >= a.day else 0), 0)


def _human_months(m):
    y, mo = divmod(int(m), 12)
    return " ".join(p for p in (f"{y} yr" if y else "", f"{mo} mo" if mo else "") if p) or "0 mo"


def experience_rows(c, request=None):
    today = timezone.localdate()
    rows, spans = [], []
    for x in CandidateExperience.objects.filter(employee=c, is_active=True).order_by("-start_date", "-id"):
        end = x.end_date or today
        months = _months_between(x.start_date, end) if x.start_date else None
        if x.start_date:
            spans.append((x.start_date, end))
        rows.append({
            "id": x.id, "company_name": x.company_name, "designation": x.designation, "department": x.department,
            "start_date": x.start_date, "end_date": x.end_date, "is_current": x.end_date is None,
            "duration_months": months, "duration": _human_months(months) if months is not None else None,
            "previous_ctc": float(x.previous_ctc) if x.previous_ctc is not None else None,
            "reason_for_leaving": x.reason_for_leaving, "reporting_manager": x.reporting_manager,
            "relieving_proof": (request.build_absolute_uri(x.experience_reliving_proof.url)
                                if request and x.experience_reliving_proof else None),
        })
    # merge overlapping spans so parallel jobs are not double counted
    total, cur = 0, None
    for s, e in sorted(spans):
        if cur is None:
            cur = [s, e]
        elif s <= cur[1]:
            cur[1] = max(cur[1], e)
        else:
            total += _months_between(cur[0], cur[1])
            cur = [s, e]
    if cur:
        total += _months_between(cur[0], cur[1])
    return rows, total


def experience_summary(c, request=None):
    rows, months = experience_rows(c, request)
    from .common import get_profile
    prof = get_profile(c, create=False)
    stored = float(prof.total_experience_years) if prof and prof.total_experience_years is not None else None
    years = round(months / 12, 1) if rows and months else (stored or 0.0)
    return {
        "candidate_type": "Experienced" if (rows or (stored or 0) > 0) else "Fresher",
        "total_experience_years": years, "total_experience_label": _human_months(round(years * 12)),
        "rows": rows,
        "last_ctc_lpa": next((r["previous_ctc"] / 100000 for r in rows if r["previous_ctc"]), None),
    }


def sync_experience(c):
    """Keep CandidateProfile.total_experience_years in step with the experience rows."""
    try:
        from .common import get_profile
        rows, months = experience_rows(c)
        if rows and months:
            prof = get_profile(c)
            prof.total_experience_years = Decimal(months) / Decimal(12)
            prof.total_experience_years = prof.total_experience_years.quantize(Decimal("0.1"), ROUND_HALF_UP)
            prof.save(update_fields=["total_experience_years", "updated_at"])
    except Exception:
        logger.exception("sync_experience failed for candidate %s", c.pk)


def validate_notice_period(data):
    """30 / 60 / 90 only (configurable). Returns None or an error message."""
    v = data.get("notice_period_days")
    if v in (None, ""):
        return None
    try:
        v = int(v)
    except (TypeError, ValueError):
        return "notice_period_days must be a number."
    if v not in notice_period_options():
        return "Notice period must be one of: " + ", ".join(f"{o} days" for o in notice_period_options()) + "."
    return None


def jd_info(prof, request=None):
    if not prof or not prof.requisition_id:
        return None
    r = prof.requisition
    jd = getattr(r, "job_description", None)
    if jd is None:
        return {"requisition_id": r.requisition_id, "has_jd": False}
    return {"requisition_id": r.requisition_id, "has_jd": True, "id": jd.id, "jd_code": jd.jd_code,
            "api": f"/api/recruitment/job-descriptions/{jd.id}/"}


# ===============================================================
# 5. HIKE POLICY
# ===============================================================
def hike_percent(last_lpa, offered_lpa):
    if last_lpa in (None, 0) or offered_lpa is None:
        return None
    last, off = Decimal(str(last_lpa)), Decimal(str(offered_lpa))
    if last <= 0:
        return None
    return ((off - last) * 100 / last).quantize(Decimal("0.01"), ROUND_HALF_UP)


def last_ctc_lpa(c):
    comp = CandidateCompensation.objects.filter(employee=c).first()
    if comp and comp.current_annual_ctc:
        return comp.current_annual_ctc / LAKH
    return None


def hike_info(c, offered_lpa=None):
    """Last vs hike vs current offered - for the candidate grid."""
    comp = CandidateCompensation.objects.filter(employee=c).first()
    last = (comp.current_annual_ctc / LAKH) if comp and comp.current_annual_ctc else None
    if offered_lpa is None and comp and comp.offered_annual_ctc:
        offered_lpa = comp.offered_annual_ctc / LAKH
    pct = hike_percent(last, offered_lpa)
    limit = hike_limit_percent()
    violation = pct is not None and pct > limit
    from .models_plus import HikeApproval
    ap = HikeApproval.objects.filter(candidate=c).order_by("-id").first()
    status = ap.status if ap else None
    return {
        "last_ctc_lpa": float(last) if last is not None else None,
        "offered_ctc_lpa": float(offered_lpa) if offered_lpa is not None else None,
        "hike_percent": float(pct) if pct is not None else None,
        "hike_limit_percent": float(limit),
        "policy_violation": violation,
        "requires_management_approval": violation and status != "Approved",
        "approval_status": status,
        "notice": (f"Policy violation - hike {pct}% is above the {limit}% limit - management approval required"
                   if violation else None),
    }


def evaluate_offer_hike(offer, actor):
    """Create / refresh a HikeApproval when the offered CTC breaks the hike limit."""
    from .models_plus import HikeApproval
    try:
        c = offer.candidate
        last = last_ctc_lpa(c)
        pct = hike_percent(last, offer.offered_ctc_lpa)
        open_ap = HikeApproval.objects.filter(candidate=c, offer=offer).order_by("-id").first()
        if pct is None or pct <= hike_limit_percent():
            if open_ap and open_ap.status == "Pending":
                open_ap.status, open_ap.remarks = "Approved", "Auto-cleared: offer is within the hike limit."
                open_ap.save()
            return None
        if open_ap and open_ap.offered_ctc_lpa == offer.offered_ctc_lpa and open_ap.status in ("Pending", "Approved"):
            return open_ap
        return HikeApproval.objects.create(
            company=offer.company, candidate=c, offer=offer, last_ctc_lpa=last.quantize(Decimal("0.01")),
            offered_ctc_lpa=offer.offered_ctc_lpa, hike_percent=pct, limit_percent=hike_limit_percent(),
            requested_by=actor, created_by=actor, updated_by=actor)
    except Exception:
        logger.exception("evaluate_offer_hike failed for offer %s", getattr(offer, "pk", None))
        return None


def hike_gate_error(offer):
    """Message when the offer may not be sent yet, else None."""
    from .models_plus import HikeApproval
    c = offer.candidate
    pct = hike_percent(last_ctc_lpa(c), offer.offered_ctc_lpa)
    if pct is None or pct <= hike_limit_percent():
        return None
    ap = HikeApproval.objects.filter(candidate=c, offer=offer, offered_ctc_lpa=offer.offered_ctc_lpa) \
        .order_by("-id").first()
    if ap is not None and ap.status == "Approved":
        return None
    return (f"Policy violation: hike of {pct}% is above the {hike_limit_percent()}% limit. "
            "Management approval is required before this offer can be sent.")


# ===============================================================
# 6. VERIFICATION (PAN / Aadhaar / Education / Experience)
# ===============================================================
VERIFY_TYPES = ["AADHAAR", "PAN", "EDUCATION", "EXPERIENCE"]


def candidate_readiness(c):
    """What exists for each verification type, before anything is verified."""
    edu = CandidateEducation.objects.filter(employee=c, is_active=True)
    exp = CandidateExperience.objects.filter(employee=c, is_active=True)
    docs = set(EmployeeDocument.objects.filter(employee=c, is_active=True).values_list("document_type", flat=True))
    return {
        "AADHAAR": {"ready": bool(c.aadhaar_number), "missing": None if c.aadhaar_number else "Aadhaar number",
                    "has_document": bool(c.aadhaar_id_proof) or "AADHAAR" in docs},
        "PAN": {"ready": bool(c.pan_number), "missing": None if c.pan_number else "PAN number",
                "has_document": bool(c.pan_card) or "PAN" in docs},
        "EDUCATION": {"ready": edu.exists(), "missing": None if edu.exists() else "Education details",
                      "has_document": bool(c.educational_certificates) or "EDUCATION" in docs
                      or any(e.degree_certificate for e in edu)},
        "EXPERIENCE": {"ready": True, "missing": None, "fresher": not exp.exists(),
                       "has_document": any(x.experience_reliving_proof for x in exp)},
    }


def verification_summary(c):
    from .models_plus import IdentityVerification
    rows = {v.id_type: v for v in IdentityVerification.objects.filter(candidate=c, is_active=True)}
    out = {}
    for t in VERIFY_TYPES:
        v = rows.get(t)
        out[t] = v.status if v else "Not Started"
    done = all(s in ("Verified", "Not Applicable") for s in out.values())
    return {"items": out, "all_verified": done}


def verification_required_error(c):
    """Only enforced when settings.HIRING_REQUIRE_ID_VERIFICATION is True."""
    if not cfg("HIRING_REQUIRE_ID_VERIFICATION", False):
        return None
    s = verification_summary(c)
    if s["all_verified"]:
        return None
    pending = [k for k, v in s["items"].items() if v not in ("Verified", "Not Applicable")]
    return "Verification pending for: " + ", ".join(pending) + "."


# ===============================================================
# 7. ONBOARDING TRIGGER (Asset, Email, Desk, Kit, Documentation, NDA)
# ===============================================================
ONBOARDING_RESOURCES = [
    ("Asset allocation (laptop / accessories)", "Asset"),
    ("Official email account creation", "Email"),
    ("Desk / seat allocation", "Desk"),
    ("Welcome kit dispatch", "Kit"),
    ("Joining documentation completed", "Documentation"),
    ("NDA signed", "NDA"),
]


def trigger_onboarding(company, c, actor):
    """Idempotent. Creates the People onboarding record + the 6 internal-resource tasks."""
    from People.models import OnboardingRecord, OnboardingTask
    rec, created = OnboardingRecord.objects.get_or_create(
        employee=c, defaults={"company": company, "created_by": actor, "updated_by": actor,
                              "started_on": c.Date_of_Joining or c.expected_joining_date or timezone.localdate()})
    have = set(rec.tasks.values_list("category", flat=True))
    base = rec.tasks.count()
    added = 0
    for i, (title, cat) in enumerate(ONBOARDING_RESOURCES, 1):
        if cat in have:
            continue
        OnboardingTask.objects.create(record=rec, title=title, category=cat, sort_order=base + i,
                                      created_by=actor, updated_by=actor)
        added += 1
    return rec, created, added


# ===============================================================
# 8. POST-HIRE ROLES (HCM / reporting manager / performance reviewer)
# ===============================================================
def apply_post_hire_roles(company, c, actor):
    """Copy the requisition role map (and selection reporting manager) onto the new employee."""
    from People.models import EmployeeExtra
    from People.org_models import EmployeeHrRoles
    from .models import CandidateSelection
    from .common import get_profile
    try:
        prof = get_profile(c, create=False)
        req = prof.requisition if prof and prof.requisition_id else None
        rm = getattr(req, "role_map", None) if req else None
        sel = CandidateSelection.objects.filter(candidate=c).first()
        reporting = (sel.reporting_manager if sel and sel.reporting_manager_id else None) \
            or (rm.reporting_manager if rm and rm.reporting_manager_id else None) \
            or (req.hiring_manager if req and req.hiring_manager_id else None)
        hcm = rm.hcm if rm and rm.hcm_id else None
        reviewer = (rm.performance_reviewer if rm and rm.performance_reviewer_id else None) or reporting
        roles, _ = EmployeeHrRoles.objects.get_or_create(
            employee=c, defaults={"company": company, "created_by": actor, "updated_by": actor})
        changed = False
        for field, val in (("hcm", hcm), ("reporting_manager", reporting), ("performance_reviewer", reviewer)):
            if val is not None and getattr(roles, field + "_id") is None:
                setattr(roles, field, val)
                changed = True
        if changed:
            roles.updated_by = actor
            roles.save()
        if reporting is not None:
            extra, _ = EmployeeExtra.objects.get_or_create(employee=c, defaults={"company": company})
            if extra.reporting_manager_id is None:
                extra.reporting_manager = reporting
                extra.save()
        return roles
    except Exception:
        logger.exception("apply_post_hire_roles failed for candidate %s", c.pk)
        return None


def on_converted(company, c, actor):
    """Called after a candidate becomes an employee."""
    try:
        trigger_onboarding(company, c, actor)
    except Exception:
        logger.exception("trigger_onboarding failed for %s", c.pk)
    apply_post_hire_roles(company, c, actor)


# ===============================================================
# 9. enrich the existing candidate card
# ===============================================================
def enrich_candidate(data, c, prof):
    """Adds new keys to serialize_candidate() output. Never removes or renames existing keys."""
    try:
        from .models_plus import CandidateApproval
        exp_rows = CandidateExperience.objects.filter(employee=c, is_active=True).exists()
        stored = float(prof.total_experience_years) if prof and prof.total_experience_years is not None else 0
        data["candidate_type"] = "Experienced" if (exp_rows or stored > 0) else "Fresher"
        data["notice_period_label"] = (f"{prof.notice_period_days} Days"
                                       if prof and prof.notice_period_days is not None else None)
        data["hike"] = hike_info(c)
        data["jd"] = jd_info(prof)
        data["experience_table_endpoint"] = f"/api/recruitment/hiring-plus/candidates/{c.id}/experience/"
        ap = CandidateApproval.objects.filter(candidate=c).first()
        data["creation_approval"] = ap.status if ap else None
        data["verification"] = verification_summary(c)
    except Exception:
        logger.exception("enrich_candidate failed for candidate %s", getattr(c, "pk", None))
    return data


def requisition_extra(r):
    """Extra keys for serialize_requisition(): role map + who may be picked as hiring manager."""
    try:
        rm = getattr(r, "role_map", None)

        def b(e):
            return {"employee_code": e.employee_code, "name": e.name} if e else None
        return {"roles": {"hcm": b(rm.hcm) if rm else None,
                          "reporting_manager": b(rm.reporting_manager) if rm else None,
                          "performance_reviewer": b(rm.performance_reviewer) if rm else None},
                "post_hire_note": "Once hired: HCM, reporting manager and performance reviewer are assigned "
                                  "from this role map."}
    except Exception:
        logger.exception("requisition_extra failed")
        return {}


def apply_requisition_roles(company, r, data, actor):
    """Inline role map on requisition create / update. Raises ValueError on a bad employee code."""
    from .models_plus import RequisitionRoles
    from .common import employee_by_code
    keys = [k for k in ("hcm", "reporting_manager", "performance_reviewer") if k in data]
    if not keys:
        return
    rm = RequisitionRoles.objects.filter(requisition=r).first() or RequisitionRoles(
        company=company, requisition=r, created_by=actor)
    for k in keys:
        emp = employee_by_code(company, data.get(k))
        if emp is not None and not emp.is_active:
            raise ValueError(f"{k}: employee must be active.")
        setattr(rm, k, emp)
    rm.updated_by = actor
    rm.save()


def dashboard_notices(company):
    """CHRO / recruitment dashboard: policy violations and approvals waiting for an M-level decision."""
    from .models_plus import CandidateApproval, HikeApproval
    hikes = HikeApproval.objects.filter(company=company, is_active=True, status="Pending").select_related("candidate")
    return {
        "chro_notices": [{
            "type": "HIKE_POLICY_VIOLATION", "hike_approval_id": h.id, "candidate": h.candidate.name,
            "last_ctc_lpa": float(h.last_ctc_lpa), "offered_ctc_lpa": float(h.offered_ctc_lpa),
            "hike_percent": float(h.hike_percent),
            "message": f"Policy violation - hike {h.hike_percent}% is above the {h.limit_percent}% limit - "
                       "management approval required"} for h in hikes],
        "pending_candidate_approvals": CandidateApproval.objects.filter(
            company=company, is_active=True, status="Pending").count(),
    }


# ===============================================================
# 10. lookup used by the hiring-plus APIs + health check
# ===============================================================
def person_by_ref(company, ref):
    """
    Candidate first (by id or candidate_id code, e.g. CAN-301); if that is not a candidate,
    any person of the SAME company (by id, employee_code or candidate_id). This lets KYC /
    verification APIs also work for people who are already employees. Never crosses companies.
    """
    from django.db.models import Q
    from .common import candidate_by_ref
    if ref in (None, ""):
        return None
    c = candidate_by_ref(company, ref)
    if c is not None:
        return c
    ref = str(ref).strip()
    q = Q(employee_code=ref) | Q(candidate_id=ref)
    if ref.isdigit():
        q |= Q(pk=int(ref))
    return EmployeeDT.objects.filter(company=company).filter(q).first()


HIRING_PLUS_VERSION = "1.1"


def table_health():
    """Which hiring-plus tables exist in the database (False = migrations not applied)."""
    from django.db import connection
    from .models_plus import (CandidateApproval, DocumentUploadLink, HikeApproval, HiringChecklistItem,
                              HiringQuestion, IdentityVerification, InterviewerAssignment, RequisitionRoles)
    from People.org_models import DepartmentOwnership, EmployeeHrRoles
    existing = set(connection.introspection.table_names())
    models = [CandidateApproval, DocumentUploadLink, HikeApproval, HiringChecklistItem, HiringQuestion,
              IdentityVerification, InterviewerAssignment, RequisitionRoles, DepartmentOwnership, EmployeeHrRoles]
    return {m._meta.db_table: (m._meta.db_table in existing) for m in models}

