# ============================================================
# ADDITIVE: Exit Management - shared logic
# Used by People/views_exit.py (Admin / HR) and
# People/views_exit_self.py (Employee).
# Existing People code (views_directory exit/initiate etc.) is untouched;
# the same side effects are re-applied here for cases created through the
# new Resignation API so both entry points behave identically.
# ============================================================

import re
from datetime import timedelta
from decimal import Decimal, ROUND_HALF_UP

from django.utils import timezone

from Company.leave_engine import balances_for, financial_year
from Employee.leave_models import LeavePolicy, ReportingHierarchy
from Employee.models import EmployeeAccount, Payroll

from .common import ensure_extra, emp_brief, iso, log_history
from .exit_models import ExitFnF, ExitInterview, ExitResignationDetail
from .models import AssetAllocation, ExitClearance

ACTIVE = ("Initiated", "In Progress", "Cleared")
DEFAULT_NOTICE_DAYS = 30
DAYS_BASIS = Decimal("30")
GRATUITY_CAP = Decimal("2000000")

# the 4 departments shown in the UI (the existing profile360 flow also adds a manager sign-off)
DEFAULT_DEPARTMENTS = [
    ("HR", "Exit interview & documents"),
    ("IT", "Return laptop & revoke access"),
    ("Finance", "Expense & advance settlement"),
    ("Admin", "ID card & locker keys"),
]
MANAGER_DEPARTMENT = ("Reporting Manager", "Knowledge transfer sign-off")

FNF_LABEL = {None: "Not Generated", "Draft": "Draft", "Calculated": "Calculation Ready",
             "Approved": "Approved", "Paid": "Paid"}

EXIT_LETTER_TYPES = ("RELIEVING_EXPERIENCE", "EXPERIENCE_CERTIFICATE")

Q2 = Decimal("0.01")


def q2(v):
    return Decimal(str(v or 0)).quantize(Q2, rounding=ROUND_HALF_UP)


def fnum(v):
    return None if v is None else float(v)


# ------------------------------------------------------------
# notice / dates
# ------------------------------------------------------------

def parse_notice_days(emp):
    """EmployeeDT.Notice_Period is free text ('45 Days', '2 months', '30')."""
    raw = str(getattr(emp, "Notice_Period", "") or "").strip().lower()
    m = re.search(r"\d+", raw)
    if not m:
        return DEFAULT_NOTICE_DAYS
    n = int(m.group())
    return n * 30 if "month" in raw else n


def days_left(x, today=None):
    if not x.last_working_day:
        return None
    return max(0, (x.last_working_day - (today or timezone.localdate())).days)


def get_detail(x, create=True, actor=None):
    """Detail row of a case. Cases created by the old exit/initiate flow have none
    yet - it is created on first use (Accepted, HR initiated, notice from profile)."""
    d = getattr(x, "_detail_cache", None)
    if d is not None:
        return d
    try:
        d = x.detail
    except ExitResignationDetail.DoesNotExist:
        d = None
    if d is None and create:
        d = ExitResignationDetail.objects.create(
            company=x.company, exit=x, approval_status="Accepted", requested_by="HR",
            notice_period_days=parse_notice_days(x.employee),
            created_by=actor, updated_by=actor)
    x._detail_cache = d
    return d


def virtual_detail(x):
    """Read-only defaults for legacy cases without a detail row (never saved)."""
    return ExitResignationDetail(company=x.company, exit=x, approval_status="Accepted",
                                 requested_by="HR", notice_period_days=parse_notice_days(x.employee))


def detail_or_virtual(x):
    return get_detail(x, create=False) or virtual_detail(x)


# ------------------------------------------------------------
# clearance checklist  (ExitClearance.items JSON, extended)
# ------------------------------------------------------------

def default_items(emp, departments=None, include_manager=False):
    pairs = list(DEFAULT_DEPARTMENTS)
    if departments:
        known = dict(DEFAULT_DEPARTMENTS + [MANAGER_DEPARTMENT])
        pairs = [(d, known.get(d, f"{d} clearance")) for d in departments]
    elif include_manager:
        pairs.append(MANAGER_DEPARTMENT)
    mgr = ReportingHierarchy.objects.filter(
        company=emp.company, Employee_ID=emp.employee_code, is_active=True).first()
    items = []
    for dept, title in pairs:
        items.append({
            "department": dept, "title": title, "cleared": False, "cleared_by": None,
            "cleared_at": None, "status": "Pending", "remarks": None,
            "approver_code": mgr.manager_code if (mgr and dept == "Reporting Manager") else None,
        })
    return items


def norm_item(i):
    """Fill the keys older rows (profile360 flow) do not have."""
    status = i.get("status") or ("Approved" if i.get("cleared") else "Pending")
    return {**i, "status": status, "remarks": i.get("remarks"),
            "approver_code": i.get("approver_code"), "cleared": status == "Approved"}


def items_of(x):
    return [norm_item(i) for i in (x.items or [])]


def clearance_counts(x):
    items = items_of(x)
    done = sum(1 for i in items if i["status"] == "Approved")
    return done, len(items)


def clearance_label(x):
    done, total = clearance_counts(x)
    return f"{done}/{total} Approved"


def all_cleared(x):
    done, total = clearance_counts(x)
    return total > 0 and done == total


def recompute_status(x):
    """Same rule as the existing exit/clear-item: Cleared when every item is approved."""
    if x.status in ("Completed", "Withdrawn"):
        return
    x.status = "Cleared" if all_cleared(x) else "In Progress"


class ExitConflict(Exception):
    """Business-rule conflict -> HTTP 409 in the views."""


def ensure_accepted(x):
    d = detail_or_virtual(x)
    if x.status not in ACTIVE:
        raise ExitConflict(f"This exit is {x.status}; it cannot be changed.")
    if d.approval_status != "Accepted":
        raise ExitConflict(f"The resignation is {d.approval_status}; accept it before working on it.")


def set_item_status(x, department, status, remarks, by, force=False):
    """Approve / reject / reset one department of the clearance checklist."""
    ensure_accepted(x)
    items = list(x.items or [])
    hit = next((i for i in items if i.get("department") == department), None)
    if hit is None:
        raise ValueError(f"Unknown clearance department '{department}'.")
    if status == "Rejected" and not str(remarks or "").strip():
        raise ValueError("remarks are required when rejecting a clearance.")
    if status == "Approved" and department in ("IT", "Admin") and not force:
        pend = pending_assets(x.employee)
        if pend:
            raise ExitConflict(f"{len(pend)} asset(s) are still not returned "
                               f"({', '.join(a['asset_tag'] for a in pend)}). Return them first or pass force=true.")
    ok_ = status == "Approved"
    hit.update(status=status, cleared=ok_, cleared_by=by if status != "Pending" else None,
               cleared_at=timezone.now().isoformat() if status != "Pending" else None)
    if remarks is not None:
        hit["remarks"] = remarks
    x.items = items
    recompute_status(x)
    x.updated_by = by
    x.save()
    return hit


def pending_assets(emp):
    """Assets still with the employee (blocks IT / Admin clearance)."""
    rows = (AssetAllocation.objects.filter(employee=emp, status="Allocated", is_active=True)
            .select_related("asset"))
    return [{"allocation_id": a.id, "asset_tag": a.asset.asset_tag, "device_name": a.asset.device_name,
             "category": a.asset.category, "purchase_cost": fnum(a.asset.purchase_cost),
             "return_due_date": iso(a.return_due_date or a.expected_return)} for a in rows]


# ------------------------------------------------------------
# side effects (identical to People/views_directory exit_* actions)
# ------------------------------------------------------------

def apply_exit_effects(x, actor):
    e = x.employee
    e.Resignation_Date, e.Resignation_Status = str(x.resignation_date), "Resigned"
    if x.last_working_day:
        e.Last_Working_Day = str(x.last_working_day)
    e.save()
    ex = ensure_extra(e)
    ex.lifecycle_status = "Notice"
    ex.save()
    log_history(e.company, e, "EXIT", "Resignation recorded", x.reason, x.resignation_date, actor=actor)


def revert_exit_effects(x, actor, note="Resignation withdrawn"):
    e = x.employee
    e.Resignation_Status, e.Resignation_Date = None, None
    e.save()
    ex = ensure_extra(e)
    ex.lifecycle_status = "Confirmed" if ex.confirmation_date else "Probation"
    ex.save()
    log_history(e.company, e, "NOTE", note, actor=actor)


def complete_exit_effects(x, actor):
    e = x.employee
    e.is_active, e.Employee_Status = False, "Exited"
    e.save()
    EmployeeAccount.objects.filter(employee=e).update(is_login_enabled=False)
    ex = ensure_extra(e)
    ex.lifecycle_status = "Exited"
    ex.save()
    log_history(e.company, e, "EXIT", "Exit completed", "Login disabled; employee marked as exited.",
                x.last_working_day, actor=actor)


# ------------------------------------------------------------
# F&F calculator
# ------------------------------------------------------------

MANUAL_EARNINGS = ("bonus", "other_earnings")
MANUAL_DEDUCTIONS = ("asset_recovery", "advance_recovery", "tds_deduction", "other_deductions")
MANUAL_FIELDS = MANUAL_EARNINGS + MANUAL_DEDUCTIONS
AUTO_OVERRIDE_FIELDS = ("pending_salary_days", "leave_encashment_days", "gratuity", "notice_shortfall_days")


def tenure_years(emp, end):
    doj = getattr(emp, "Date_of_Joining", None)
    if not doj or not end or end < doj:
        return Decimal("0")
    return Decimal((end - doj).days) / Decimal("365.25")


def calc_fnf(x, overrides=None):
    """
    Returns {"fields": {...}, "components": {...}} for the exit case.

      pending salary  = per-day rate x days worked in the last-working-day month
                        (0 when payroll for that month is already processed)
      leave encashment= encashable leave balance (policy.encashable, capped by
                        max_encashable_days) x per-day rate
      gratuity        = basic x 15/26 x completed years (>= 5 years of service,
                        6+ month remainder counts as a year, capped at Rs 20 lakh)
      notice recovery = (notice days - waived - served days) x per-day rate
      per-day rate    = monthly basic / 30

    `overrides` may set: bonus, other_earnings, asset_recovery, advance_recovery,
    tds_deduction, other_deductions, pending_salary_days, leave_encashment_days,
    gratuity, notice_shortfall_days, unpaid_days, include_gratuity.
    """
    ov = overrides or {}
    e, company = x.employee, x.company
    lwd = x.last_working_day or timezone.localdate()
    d = detail_or_virtual(x)
    warnings, notes = [], []

    basic = q2(getattr(e, "Basic_Salary", None))
    if basic <= 0:
        warnings.append("Basic salary is not set on the employee - salary based components are 0.")
    per_day = q2(basic / DAYS_BASIS) if basic > 0 else Decimal("0")

    # ---- pending salary ----
    payroll_done = Payroll.objects.filter(company=company, Employee_ID=e.employee_code,
                                          month=lwd.month, year=lwd.year).exists()
    if "pending_salary_days" in ov:
        sal_days = q2(ov["pending_salary_days"])
    elif payroll_done:
        sal_days = Decimal("0")
        notes.append(f"Salary for {lwd.strftime('%B %Y')} is already processed in payroll.")
    else:
        sal_days = max(Decimal("0"), Decimal(lwd.day) - Decimal(str(ov.get("unpaid_days", 0) or 0)))
    pending_salary = q2(per_day * sal_days)

    # ---- leave encashment ----
    enc_rows, enc_days = [], Decimal("0")
    if "leave_encashment_days" in ov:
        enc_days = q2(ov["leave_encashment_days"])
    else:
        policies = {p.leave_type: p for p in LeavePolicy.objects.filter(company=company, is_active=True)}
        for b in balances_for(company, e.employee_code, financial_year(lwd)):
            p = policies.get(b["leave_type"])
            if p is None or not p.encashable or b["unlimited"]:
                continue
            avail = max(Decimal("0"), Decimal(b["available"] or 0))
            cap = p.max_encashable_days
            days = min(avail, Decimal(cap)) if cap is not None else avail
            if days > 0:
                enc_rows.append({"leave_type": b["leave_type"], "available": float(avail), "encashed_days": float(days)})
                enc_days += days
    leave_enc = q2(per_day * enc_days)

    # ---- gratuity ----
    yrs = tenure_years(e, lwd)
    gratuity, grat_note = Decimal("0"), None
    if "gratuity" in ov:
        gratuity = q2(ov["gratuity"])
    elif str(ov.get("include_gratuity", "true")).lower() in ("false", "0", "no"):
        grat_note = "Gratuity excluded by request."
    elif yrs >= 5 and basic > 0:
        whole = int(yrs)
        counted = whole + (1 if (yrs - whole) >= Decimal("0.5") else 0)
        gratuity = min(q2(basic * Decimal(15) / Decimal(26) * counted), GRATUITY_CAP)
        grat_note = f"{counted} year(s) x basic x 15/26"
    else:
        grat_note = f"Not eligible - {float(q2(yrs))} year(s) of service (5 required)."

    # ---- notice recovery ----
    required = max(0, (d.notice_period_days or 0) - (d.notice_waived_days or 0))
    served = max(0, (lwd - x.resignation_date).days) if x.resignation_date else required
    shortfall = Decimal(str(ov["notice_shortfall_days"])) if "notice_shortfall_days" in ov \
        else Decimal(max(0, required - served))
    notice_recovery = q2(per_day * shortfall)

    pend = pending_assets(e)
    if pend:
        warnings.append(f"{len(pend)} asset(s) still not returned - add asset_recovery if they are to be recovered.")
    if not all_cleared(x):
        warnings.append("Departmental clearances are not complete yet.")

    f = {
        "basic_monthly": basic, "per_day_rate": per_day,
        "pending_salary_days": q2(sal_days), "pending_salary": pending_salary,
        "leave_encashment_days": q2(enc_days), "leave_encashment": leave_enc,
        "gratuity": gratuity,
        "notice_shortfall_days": q2(shortfall), "notice_recovery": notice_recovery,
    }
    for k in MANUAL_FIELDS:
        f[k] = q2(ov.get(k))
    f.update(totals(f))

    comp = {
        "last_working_day": iso(lwd), "days_basis": int(DAYS_BASIS),
        "tenure_years": float(q2(yrs)), "gratuity_note": grat_note,
        "notice": {"required_days": required, "served_days": served,
                   "notice_period_days": d.notice_period_days, "waived_days": d.notice_waived_days},
        "leave_encashment": enc_rows, "payroll_already_processed": payroll_done,
        "pending_assets": pend, "warnings": warnings, "notes": notes,
    }
    return {"fields": f, "components": comp}


def totals(f):
    gross = q2(f["pending_salary"] + f["leave_encashment"] + f["gratuity"] + f["bonus"] + f["other_earnings"])
    ded = q2(f["notice_recovery"] + f["asset_recovery"] + f["advance_recovery"]
             + f["tds_deduction"] + f["other_deductions"])
    return {"gross_earnings": gross, "total_deductions": ded, "net_payable": q2(gross - ded)}


def fnf_row(f, with_components=True):
    if f is None:
        return None
    row = {
        "id": f.id, "statement_no": f.statement_no, "status": f.status, "status_label": FNF_LABEL[f.status],
        "basic_monthly": fnum(f.basic_monthly), "per_day_rate": fnum(f.per_day_rate),
        "earnings": {"pending_salary_days": fnum(f.pending_salary_days), "pending_salary": fnum(f.pending_salary),
                     "leave_encashment_days": fnum(f.leave_encashment_days),
                     "leave_encashment": fnum(f.leave_encashment), "gratuity": fnum(f.gratuity),
                     "bonus": fnum(f.bonus), "other_earnings": fnum(f.other_earnings),
                     "total": fnum(f.gross_earnings)},
        "deductions": {"notice_shortfall_days": fnum(f.notice_shortfall_days),
                       "notice_recovery": fnum(f.notice_recovery), "asset_recovery": fnum(f.asset_recovery),
                       "advance_recovery": fnum(f.advance_recovery), "tds_deduction": fnum(f.tds_deduction),
                       "other_deductions": fnum(f.other_deductions), "total": fnum(f.total_deductions)},
        "net_payable": fnum(f.net_payable), "remarks": f.remarks,
        "approved_by": f.approved_by, "approved_on": iso(f.approved_on), "paid_on": iso(f.paid_on),
        "payment_mode": f.payment_mode, "payment_reference": f.payment_reference,
        "created_at": iso(f.created_at), "updated_at": iso(f.updated_at),
    }
    if with_components:
        row["components"] = f.components
    return row


# ------------------------------------------------------------
# rows
# ------------------------------------------------------------

def fnf_of(x):
    try:
        return x.fnf
    except ExitFnF.DoesNotExist:
        return None


def interview_of(x):
    try:
        return x.interview
    except ExitInterview.DoesNotExist:
        return None


def letters_ready(x):
    return x.status != "Withdrawn" and all_cleared(x)


def resignation_row(x, request=None, today=None):
    e, d, f = x.employee, detail_or_virtual(x), fnf_of(x)
    done, total = clearance_counts(x)
    ho = d.handover_to
    return {
        "id": x.id, "employee": emp_brief(e, request),
        "employee_label": f"{e.name}", "employee_subtitle": f"{e.employee_code} • {e.Designation}",
        "status": x.status, "approval_status": d.approval_status, "separation_type": d.separation_type,
        "requested_by": d.requested_by, "resignation_date": iso(x.resignation_date),
        "last_working_day": iso(x.last_working_day), "reason": x.reason,
        "notice_period_days": d.notice_period_days, "notice_period": f"{d.notice_period_days} Days",
        "notice_waived_days": d.notice_waived_days, "days_left": days_left(x, today),
        "clearance": {"approved": done, "total": total, "label": f"{done}/{total} Approved"},
        "clearance_status": f"{done}/{total} Approved",
        "fnf_status": f.status if f else None, "fnf_status_label": FNF_LABEL[f.status if f else None],
        "handover_to": ({"employee_code": ho.employee_code, "name": ho.name} if ho else None),
        "handover_notes": d.handover_notes, "hr_remarks": d.hr_remarks,
        "accepted_by": d.accepted_by, "accepted_on": iso(d.accepted_on), "rejection_reason": d.rejection_reason,
        "actions": {"clearances": f"/api/exit/clearances/{x.id}/", "fnf": f"/api/exit/fnf/?exit_id={x.id}",
                    "relieving_letter_ready": letters_ready(x),
                    "relieving_letter": "/api/exit/letters/generate/",       # POST {exit_id, letter_type}
                    "experience_certificate_ready": letters_ready(x)},
        "created_at": iso(x.created_at), "updated_at": iso(x.updated_at),
    }


def clearance_detail(x, request=None):
    e = x.employee
    items = items_of(x)
    done, total = clearance_counts(x)
    pend = pending_assets(e)
    rows = []
    for n, i in enumerate(items, 1):
        r = {"no": n, "heading": f"{n}. {i['department']} Clearance", **i}
        if i["department"] in ("IT", "Admin") and pend and i["status"] != "Approved":
            r["pending_assets"] = pend
        rows.append(r)
    return {"exit_id": x.id, "employee": emp_brief(e, request),
            "heading": f"Departmental Offboarding Clearances - {e.name} ({e.employee_code})",
            "status": x.status, "approved": done, "total": total, "summary": f"{done} / {total} Done",
            "departments": [i["department"] for i in items], "pending_assets": pend, "items": rows}


def interview_row(iv, request=None):
    if iv is None:
        return None
    e = iv.exit.employee
    return {
        "id": iv.id, "exit_id": iv.exit_id, "employee": emp_brief(e, request),
        "employee_title": f"{e.name} ({e.Designation})", "status": iv.status, "mode": iv.mode,
        "scheduled_for": iso(iv.scheduled_for), "conducted_on": iso(iv.conducted_on),
        "conducted_by": iv.conducted_by, "overall_rating": fnum(iv.overall_rating),
        "rating_label": (f"{float(iv.overall_rating):.1f} / 5.0 Workplace Rating"
                         if iv.overall_rating is not None else None),
        "reason_for_leaving": iv.reason_for_leaving, "feedback": iv.feedback, "liked_most": iv.liked_most,
        "improvement_suggestions": iv.improvement_suggestions, "would_recommend": iv.would_recommend,
        "would_rejoin": iv.would_rejoin, "submitted_by": iv.submitted_by,
        "created_at": iso(iv.created_at), "updated_at": iso(iv.updated_at),
    }


# ------------------------------------------------------------
# dashboard
# ------------------------------------------------------------

def active_cases(company):
    return (ExitClearance.objects.filter(company=company, is_active=True, status__in=ACTIVE)
            .select_related("employee", "employee__department"))


def dashboard(company, request=None):
    today = timezone.localdate()
    cases = [x for x in active_cases(company) if detail_or_virtual(x).approval_status != "Rejected"]
    accepted = [x for x in cases if detail_or_virtual(x).approval_status == "Accepted"]

    notice_days = [detail_or_virtual(x).notice_period_days for x in accepted]
    avg_notice = (sum(notice_days) / len(notice_days)) if notice_days else None

    done = tot = 0
    depts = []
    for x in accepted:
        a, t = clearance_counts(x)
        done, tot = done + a, tot + t
        for i in items_of(x):
            if i["department"] not in depts:
                depts.append(i["department"])

    fnf = {None: 0, "Draft": 0, "Calculated": 0, "Approved": 0, "Paid": 0}
    ready = 0
    for x in accepted:
        f = fnf_of(x)
        fnf[f.status if f else None] += 1
        if f and f.status in ("Calculated", "Approved") and all_cleared(x):
            ready += 1
    if not accepted:
        fnf_label, fnf_caption = "-", "No active exits"
    elif ready:
        fnf_label, fnf_caption = "Ready", "Relieving letter ready"
    elif fnf["Paid"] == len(accepted):
        fnf_label, fnf_caption = "Paid", "All settlements paid"
    else:
        fnf_label, fnf_caption = "Pending", "Clearance / calculation pending"

    pipeline = []
    for x in cases:
        r = resignation_row(x, request, today)
        pipeline.append({
            "exit_id": x.id, "employee": r["employee"], "employee_label": r["employee_label"],
            "employee_subtitle": r["employee_subtitle"], "resignation_date": r["resignation_date"],
            "notice_period": r["notice_period"], "days_left": r["days_left"],
            "clearance_status": r["clearance_status"], "fnf_status": r["fnf_status_label"],
            "approval_status": r["approval_status"], "actions": r["actions"]})

    return {
        "title": "Exit Management, Clearances & Full & Final (F&F) Settlement",
        "subtitle": "Resignation workflow, multi-department clearances, F&F calculator, and relieving letters",
        "cards": {
            "notice_period_active": {"title": "Notice Period Active", "value": len(accepted),
                                     "label": str(len(accepted)), "caption": "Serving formal notice"},
            "average_notice_period": {"title": "Average Notice Period",
                                      "value": round(avg_notice, 1) if avg_notice is not None else None,
                                      "label": f"{avg_notice:g} Days" if avg_notice is not None else "-",
                                      "caption": "Standard employment clause"},
            "departmental_clearances": {"title": "Departmental Clearances", "approved": done, "total": tot,
                                        "label": f"{done} / {tot} Done", "caption": ", ".join(depts)},
            "fnf_settlement_status": {"title": "F&F Settlement Status", "label": fnf_label,
                                      "caption": fnf_caption,
                                      "counts": {"not_generated": fnf[None], "draft": fnf["Draft"],
                                                 "calculated": fnf["Calculated"], "approved": fnf["Approved"],
                                                 "paid": fnf["Paid"]}},
        },
        "pipeline_title": "Active Resignation & Offboarding Pipeline",
        "pipeline_note": "Mandatory statutory clearance prior to relieving document generation",
        "pipeline": pipeline,
    }
