# ============================================================
# ADDITIVE: Leave Management & WFH engine - shared logic
# ------------------------------------------------------------
# Used by BOTH:
#   Company/leave_api_views.py   (Admin / HR  -> /api/leave-hub/...)
#   Employee/leave_self_views.py (Employee    -> /employee/leave/...)
#
# Nothing in the existing hr_api_views.py is modified; the
# existing helpers are imported and reused so attendance /
# payroll keep working exactly as before.
# ============================================================

from datetime import date, datetime, time, timedelta
from decimal import Decimal

from django.db.models import Sum
from django.utils import timezone

from Company.hr_api_views import (   # existing, unchanged
    _err,
    _ok,
    _truthy,
    apply_leave_to_attendance,
    employee_brief,
    employee_map,
    revert_leave_attendance,
    working_dates,
)
from Employee.employee_crud_permissions import (
    actor_label,
    user_can,
)
from Employee.models import LeaveRequest
from Employee.leave_models import (
    ApprovalAction,
    ApprovalWorkflowStep,
    LeaveBalance,
    LeavePolicy,
    ReportingHierarchy,
    WFHPolicy,
    WFHRequest,
)


# ------------------------------------------------------------
# constants
# ------------------------------------------------------------

LEAVE_TYPES = ["Paid Leave", "Casual Leave", "Sick Leave", "Unpaid Leave"]

DEFAULT_LEAVE_POLICIES = [
    {
        "leave_type": "Paid Leave", "code": "PL",
        "title": "Earned & Privilege Leaves (PL)",
        "description": (
            "Credited at 1.5 days per completed month of active service. "
            "Maximum 45 days encashable upon separation."
        ),
        "annual_quota": Decimal("18"), "accrual_per_month": Decimal("1.5"),
        "carry_forward": True, "max_carry_forward_days": Decimal("45"),
        "encashable": True, "max_encashable_days": Decimal("45"),
        "medical_certificate_after_days": None, "is_paid": True,
    },
    {
        "leave_type": "Casual Leave", "code": "CL",
        "title": "Casual Leaves (CL)",
        "description": "Short personal absences. Not carried forward or encashable.",
        "annual_quota": Decimal("12"), "accrual_per_month": None,
        "carry_forward": False, "max_carry_forward_days": Decimal("0"),
        "encashable": False, "max_encashable_days": Decimal("0"),
        "medical_certificate_after_days": None, "is_paid": True,
    },
    {
        "leave_type": "Sick Leave", "code": "SL",
        "title": "Sick & Medical Leaves (SL)",
        "description": (
            "Medical certificate mandatory for sick leave absences "
            "exceeding 2 consecutive working days."
        ),
        "annual_quota": Decimal("10"), "accrual_per_month": None,
        "carry_forward": False, "max_carry_forward_days": Decimal("0"),
        "encashable": False, "max_encashable_days": Decimal("0"),
        "medical_certificate_after_days": 2, "is_paid": True,
    },
    {
        "leave_type": "Unpaid Leave", "code": "UL",
        "title": "Unpaid Leave (LOP)",
        "description": "Loss of pay. No quota; deducted in payroll.",
        "annual_quota": None, "accrual_per_month": None,
        "carry_forward": False, "max_carry_forward_days": Decimal("0"),
        "encashable": False, "max_encashable_days": Decimal("0"),
        "medical_certificate_after_days": None, "is_paid": False,
    },
]

# Built-in approval chain (used until a company configures its own).
DEFAULT_WORKFLOW = [
    {"step_order": 1, "name": "Reporting Manager", "approver_type": "reporting_manager",
     "sla_hours": 12, "description": "12-Hour SLA Review"},
    {"step_order": 2, "name": "Department HOD", "approver_type": "hod",
     "sla_hours": 12, "description": "Final Workload Sign-off"},
    {"step_order": 3, "name": "HR Compliance & Payroll", "approver_type": "hr",
     "sla_hours": 24, "description": "Automated reconciliation"},
]

APPROVER_SHORT = {"reporting_manager": "Manager", "hod": "HOD", "hr": "HR Ops"}


# ------------------------------------------------------------
# financial year (India: April - March)
# ------------------------------------------------------------

def financial_year(d=None):
    d = d or timezone.localdate()
    start = d.year if d.month >= 4 else d.year - 1
    return f"{start}-{(start + 1) % 100:02d}"


def fy_range(fy):
    """'2026-27' -> (date(2026,4,1), date(2027,3,31))"""
    start = int(str(fy).split("-")[0])
    return date(start, 4, 1), date(start + 1, 3, 31)


def valid_fy(value):
    try:
        start = int(str(value).split("-")[0])
        return f"{start}-{(start + 1) % 100:02d}" == str(value)
    except (TypeError, ValueError):
        return False


# ------------------------------------------------------------
# references shown in the UI (LEV-101, WFH-2026-001)
# ------------------------------------------------------------

def leave_ref(leave):
    return f"LEV-{leave.pk}"


def wfh_ref(wfh):
    return f"WFH-{wfh.wfh_date.year}-{wfh.pk:03d}"


# ------------------------------------------------------------
# policies
# ------------------------------------------------------------

def ensure_default_policies(company, actor=None):
    """Create the default PL / CL / SL / Unpaid policies once."""
    if LeavePolicy.objects.filter(company=company).exists():
        return
    for row in DEFAULT_LEAVE_POLICIES:
        LeavePolicy.objects.get_or_create(
            company=company, leave_type=row["leave_type"],
            defaults={**row, "created_by": actor, "updated_by": actor},
        )


def get_wfh_policy(company, actor=None):
    policy, _ = WFHPolicy.objects.get_or_create(
        company=company, defaults={"created_by": actor, "updated_by": actor},
    )
    return policy


def wfh_policy_dict(company):
    policy = get_wfh_policy(company)
    steps = get_workflow(company, "wfh")
    chain = " → ".join(
        f"{APPROVER_SHORT.get(s['approver_type'], s['name'])}"
        + (f" ({s['sla_hours']}h)" if s["approver_type"] != "hr" else "")
        for s in steps
    )
    return {
        "id": policy.pk,
        "is_enabled": policy.is_enabled,
        "weekly_quota_days": policy.weekly_quota_days,
        "advance_notice_hours": policy.advance_notice_hours,
        "work_start_time": policy.work_start_time.strftime("%H:%M"),
        "description": policy.description or (
            f"Max {policy.weekly_quota_days} days/week allowed. Advance notice of "
            f"{policy.advance_notice_hours} hours required. Requires reporting "
            "manager and department HOD approval."
        ),
        "approval_hierarchy": {
            "tiers": len(steps),
            "label": f"{len(steps)}-Tier Routing",
            "chain": chain,
        },
        "cards": {
            "weekly_wfh_allowance": f"{policy.weekly_quota_days} Days",
            "advance_notice_window": f"{policy.advance_notice_hours} Hours",
            "approval_hierarchy": f"{len(steps)}-Tier Routing",
        },
        "updated_at": policy.updated_at,
    }


def leave_policy_dict(p):
    return {
        "id": p.pk,
        "leave_type": p.leave_type,
        "code": p.code,
        "title": p.title or p.leave_type,
        "description": p.description,
        "annual_quota": p.annual_quota,
        "accrual_per_month": p.accrual_per_month,
        "carry_forward": p.carry_forward,
        "max_carry_forward_days": p.max_carry_forward_days,
        "encashable": p.encashable,
        "max_encashable_days": p.max_encashable_days,
        "medical_certificate_after_days": p.medical_certificate_after_days,
        "min_notice_hours": p.min_notice_hours,
        "is_paid": p.is_paid,
        "is_active": p.is_active,
        "updated_at": p.updated_at,
    }


def policy_framework(company):
    """Leave & Remote Work Policy Framework (3 numbered policies)."""
    ensure_default_policies(company)
    wfh = wfh_policy_dict(company)
    out = [{"no": 1, "title": "Work From Home (WFH) & Remote Policy",
            "description": wfh["description"]}]
    n = 2
    for p in LeavePolicy.objects.filter(company=company, is_active=True).exclude(
        leave_type="Unpaid Leave"
    ):
        out.append({"no": n, "title": p.title or p.leave_type,
                    "description": p.description})
        n += 1
    return out


# ------------------------------------------------------------
# workflow
# ------------------------------------------------------------

def get_workflow(company, request_type):
    rows = list(
        ApprovalWorkflowStep.objects.filter(
            company=company, request_type=request_type, is_active=True
        ).order_by("step_order")
    )
    if not rows:
        return [dict(s, id=None) for s in DEFAULT_WORKFLOW]
    return [
        {"id": r.pk, "step_order": r.step_order, "name": r.name,
         "approver_type": r.approver_type, "sla_hours": r.sla_hours,
         "description": r.description}
        for r in rows
    ]


def workflow_chain(company, request_type):
    """The 4-box chain shown on the Approval Workflow tab."""
    steps = get_workflow(company, request_type)
    chain = [{
        "no": 1, "name": "Employee Submission",
        "description": "Quota & notice validated",
        "approver_type": "employee",
    }]
    for i, s in enumerate(steps, start=2):
        chain.append({
            "no": i, "name": s["name"],
            "description": s["description"] or f"{s['sla_hours']}-Hour SLA Review",
            "approver_type": s["approver_type"], "sla_hours": s["sla_hours"],
            "step_id": s["id"],
        })
    return chain


# ------------------------------------------------------------
# hierarchy / approvers
# ------------------------------------------------------------

def hierarchy_for(company, employee_code):
    return ReportingHierarchy.objects.filter(
        company=company, Employee_ID=employee_code, is_active=True
    ).first()


def resolve_approver_code(company, employee_code, approver_type):
    if approver_type == "hr":
        return None
    h = hierarchy_for(company, employee_code)
    if h is None:
        return None
    return h.manager_code if approver_type == "reporting_manager" else h.hod_code


def create_approval_actions(company, request_type, req, actor=None):
    """Create the pipeline rows for a freshly submitted request."""
    if ApprovalAction.objects.filter(
        company=company, request_type=request_type, request_id=req.pk
    ).exists():
        return

    now = timezone.now()
    first = True
    for s in get_workflow(company, request_type):
        approver = resolve_approver_code(company, req.Employee_ID, s["approver_type"])
        # an employee can never approve their own request
        if approver and approver == req.Employee_ID:
            approver = None
        ApprovalAction.objects.create(
            company=company, request_type=request_type, request_id=req.pk,
            step_order=s["step_order"], step_name=s["name"],
            approver_type=s["approver_type"], approver_code=approver,
            sla_hours=s["sla_hours"],
            due_at=now + timedelta(hours=s["sla_hours"]) if first else None,
            created_by=actor, updated_by=actor,
        )
        first = False


def actions_map(company, request_type, ids):
    """{request_id: [ApprovalAction, ...]} in one query."""
    out = {}
    if not ids:
        return out
    for a in ApprovalAction.objects.filter(
        company=company, request_type=request_type, request_id__in=list(ids)
    ).order_by("step_order"):
        out.setdefault(a.request_id, []).append(a)
    return out


def _effective_status(action, req_status):
    """
    Requests approved / rejected through the pre-existing single-step
    endpoints (/api/leaves/<id>/approve/) never touched their pipeline
    rows - show them as resolved instead of forever Pending.
    """
    if action.status != "Pending":
        return action.status
    if req_status == "Approved":
        return "Approved"
    if req_status in ("Rejected", "Cancelled"):
        return "Skipped"
    return "Pending"


def pipeline_dict(actions, req_status, emp_lookup=None, request=None):
    pipeline, current = [], None
    now = timezone.now()
    for a in actions:
        eff = _effective_status(a, req_status)
        if eff == "Pending" and current is None:
            current = a
        approver = None
        if a.approver_code and emp_lookup:
            approver = employee_brief(emp_lookup.get(a.approver_code), request)
        pipeline.append({
            "id": a.pk,
            "step_order": a.step_order,
            "name": a.step_name,
            "approver_type": a.approver_type,
            "approver_code": a.approver_code,
            "approver": approver,
            "sla_hours": a.sla_hours,
            "due_at": a.due_at,
            "overdue": bool(eff == "Pending" and a.due_at and a.due_at < now
                            and a is current),
            "status": eff,
            "acted_by": a.acted_by,
            "acted_at": a.acted_at,
            "comment": a.comment,
        })
    return pipeline, current


def current_tier_label(current, req_status):
    if req_status != "Pending" or current is None:
        return req_status
    return f"{APPROVER_SHORT.get(current.approver_type, current.step_name)} Review"


# ------------------------------------------------------------
# who may act on an approval tier
# ------------------------------------------------------------

def can_act_on(user, action, requester_code):
    """
    Company Admin            -> any tier
    Employee with leave 'approve' / manage checkbox (HR) -> any tier
    Employee who is the designated manager / HOD of the requester
                             -> only their own tier
    Nobody can approve their own request (except Company Admin).
    """
    from Employee.models import EmployeeDT
    from Company.models import company_details

    if isinstance(user, company_details):
        return True

    if not isinstance(user, EmployeeDT):
        return False

    if user.employee_code == requester_code:
        return False

    if user_can(user, "leave", "approve"):
        return True

    return bool(action.approver_code and action.approver_code == user.employee_code)


# ------------------------------------------------------------
# balances
# ------------------------------------------------------------

def _policy_map(company):
    ensure_default_policies(company)
    return {p.leave_type: p for p in LeavePolicy.objects.filter(company=company)}


def balances_for(company, employee_code, fy=None):
    """Per-leave-type balance of one employee for one financial year."""
    fy = fy or financial_year()
    start, end = fy_range(fy)
    policies = _policy_map(company)
    overrides = {
        b.leave_type: b
        for b in LeaveBalance.objects.filter(
            company=company, Employee_ID=employee_code,
            financial_year=fy, is_active=True,
        )
    }

    def total(status):
        return {
            r["leave_type"]: r["t"] or Decimal("0")
            for r in LeaveRequest.objects.filter(
                company=company, Employee_ID=employee_code, is_active=True,
                status=status, from_date__gte=start, from_date__lte=end,
            ).values("leave_type").annotate(t=Sum("total_days"))
        }

    used, pending = total("Approved"), total("Pending")
    rows = []

    for leave_type in LEAVE_TYPES:
        policy = policies.get(leave_type)
        if policy is None or not policy.is_active:
            continue
        ov = overrides.get(leave_type)

        if ov is not None:
            allocated = ov.allocated
            carried, adj = ov.carried_forward, ov.adjustment
        else:
            allocated = policy.annual_quota
            carried = adj = Decimal("0")

        if allocated is None:       # unlimited
            total_days = remaining = available = None
        else:
            total_days = allocated + carried + adj
            remaining = total_days - used.get(leave_type, Decimal("0"))
            available = remaining - pending.get(leave_type, Decimal("0"))

        rows.append({
            "leave_type": leave_type,
            "code": policy.code,
            "title": policy.title or leave_type,
            "financial_year": fy,
            "allocated": allocated,
            "carried_forward": carried,
            "adjustment": adj,
            "total": total_days,
            "used": used.get(leave_type, Decimal("0")),
            "pending": pending.get(leave_type, Decimal("0")),
            "remaining": remaining,
            "available": available,
            "unlimited": allocated is None,
            "has_override": ov is not None,
            "override_id": ov.pk if ov else None,
        })
    return rows


# ------------------------------------------------------------
# WFH helpers
# ------------------------------------------------------------

def week_bounds(d):
    monday = d - timedelta(days=d.weekday())
    return monday, monday + timedelta(days=6)


def wfh_quota_used(company, employee_code, wfh_date, exclude_pk=None):
    monday, sunday = week_bounds(wfh_date)
    qs = WFHRequest.objects.filter(
        company=company, Employee_ID=employee_code, is_active=True,
        status__in=["Pending", "Approved"],
        wfh_date__gte=monday, wfh_date__lte=sunday,
    )
    if exclude_pk:
        qs = qs.exclude(pk=exclude_pk)
    return qs.count()


def notice_hours_for(policy, wfh_date, now=None):
    now = now or timezone.now()
    start = timezone.make_aware(datetime.combine(wfh_date, policy.work_start_time))
    return Decimal(str(round((start - now).total_seconds() / 3600, 1)))


def validate_wfh(company, employee_code, wfh_date, exclude_pk=None):
    """Returns (policy, notice_hours, error_response_or_None)."""
    from rest_framework import status as http_status

    policy = get_wfh_policy(company)

    if not policy.is_enabled:
        return policy, None, _err("wfh_disabled", "Work From Home is disabled for your company.")

    if not working_dates(company, wfh_date, wfh_date):
        return policy, None, _err(
            "no_working_day", "WFH date must be a working day (not a Sunday / holiday)."
        )

    notice = notice_hours_for(policy, wfh_date)

    if notice < policy.advance_notice_hours:
        return policy, notice, _err(
            "insufficient_notice",
            f"WFH must be applied at least {policy.advance_notice_hours} hours in advance "
            f"(only {max(notice, Decimal('0'))}h given).",
        )

    if WFHRequest.objects.filter(
        company=company, Employee_ID=employee_code, wfh_date=wfh_date,
        is_active=True, status__in=["Pending", "Approved"],
    ).exclude(pk=exclude_pk or 0).exists():
        return policy, notice, _err(
            "wfh_duplicate", "A WFH request already exists for this date.",
            http_status.HTTP_409_CONFLICT,
        )

    if LeaveRequest.objects.filter(
        company=company, Employee_ID=employee_code, is_active=True,
        status__in=["Pending", "Approved"],
        from_date__lte=wfh_date, to_date__gte=wfh_date,
    ).exists():
        return policy, notice, _err(
            "leave_conflict", "You have a leave request covering this date.",
            http_status.HTTP_409_CONFLICT,
        )

    used = wfh_quota_used(company, employee_code, wfh_date, exclude_pk)
    if used >= policy.weekly_quota_days:
        return policy, notice, _err(
            "wfh_quota_exceeded",
            f"Weekly WFH quota reached ({used}/{policy.weekly_quota_days} days).",
            http_status.HTTP_409_CONFLICT,
        )

    return policy, notice, None


def wfh_quota_utilization(company, ref_date=None):
    """Weekly company average (used / allowed) for the dashboard card."""
    ref_date = ref_date or timezone.localdate()
    monday, sunday = week_bounds(ref_date)
    policy = get_wfh_policy(company)

    from Employee.models import EmployeeDT
    active = EmployeeDT.objects.filter(company=company, is_active=True).count()
    used = WFHRequest.objects.filter(
        company=company, is_active=True,
        status__in=["Pending", "Approved"],
        wfh_date__gte=monday, wfh_date__lte=sunday,
    ).count()

    avg = round(used / active, 1) if active else 0.0
    return {
        "average_days_used": avg,
        "weekly_quota_days": policy.weekly_quota_days,
        "label": f"{avg} / {float(policy.weekly_quota_days):.1f}",
        "week_start": monday, "week_end": sunday,
        "wfh_days_this_week": used, "active_employees": active,
    }


# ------------------------------------------------------------
# row serializers
# ------------------------------------------------------------

def leave_row(leave, emp_lookup=None, acts=None, request=None, with_pipeline=True):
    emp = (emp_lookup or {}).get(leave.Employee_ID)
    row = {
        "id": leave.pk,
        "request_ref": leave_ref(leave),
        "employee_code": leave.Employee_ID,
        "employee_name": leave.Name,
        "employee": employee_brief(emp, request) if emp else None,
        "leave_type": leave.leave_type,
        "from_date": leave.from_date,
        "to_date": leave.to_date,
        "total_days": leave.total_days,
        "reason": leave.reason,
        "status": leave.status,
        "display_status": "Pending Approval" if leave.status == "Pending" else leave.status,
        "reviewed_by": leave.reviewed_by,
        "reviewed_at": leave.reviewed_at,
        "review_comment": leave.review_comment,
        "created_at": leave.created_at,
        "updated_at": leave.updated_at,
    }
    if with_pipeline:
        pipeline, current = pipeline_dict(acts or [], leave.status, emp_lookup, request)
        row["pipeline"] = pipeline
        row["current_tier"] = current_tier_label(current, leave.status)
        row["current_tier_id"] = current.pk if current else None
    return row


def wfh_row(wfh, emp_lookup=None, acts=None, request=None, company=None):
    emp = (emp_lookup or {}).get(wfh.Employee_ID)
    company = company or wfh.company
    policy = get_wfh_policy(company)
    used = wfh_quota_used(company, wfh.Employee_ID, wfh.wfh_date)
    left = max(policy.weekly_quota_days - used, 0)
    pipeline, current = pipeline_dict(acts or [], wfh.status, emp_lookup, request)
    return {
        "id": wfh.pk,
        "request_ref": wfh_ref(wfh),
        "employee_code": wfh.Employee_ID,
        "employee_name": wfh.Name,
        "employee": employee_brief(emp, request) if emp else None,
        "wfh_date": wfh.wfh_date,
        "days": 1,
        "reason": wfh.reason,
        "status": wfh.status,
        "notice_hours": wfh.notice_hours,
        "notice_validation": {
            "hours": wfh.notice_hours,
            "required_hours": policy.advance_notice_hours,
            "compliant": wfh.notice_hours >= policy.advance_notice_hours,
            "label": f"{int(wfh.notice_hours)}h Notice "
                     + ("(Compliant)" if wfh.notice_hours >= policy.advance_notice_hours
                        else "(Short)"),
        },
        "weekly_quota_status": {
            "used": used, "quota": policy.weekly_quota_days, "left": left,
            "label": f"{used}/{policy.weekly_quota_days} Days Used ({left} Left)",
        },
        "approval_tier": current_tier_label(current, wfh.status),
        "current_tier_id": current.pk if current else None,
        "pipeline": pipeline,
        "reviewed_by": wfh.reviewed_by,
        "reviewed_at": wfh.reviewed_at,
        "review_comment": wfh.review_comment,
        "created_at": wfh.created_at,
        "updated_at": wfh.updated_at,
    }


# ------------------------------------------------------------
# tier processing (shared by admin/HR and employee approvers)
# ------------------------------------------------------------

def current_pending_action(company, request_type, req):
    from rest_framework import status as http_status  # noqa: F401
    return ApprovalAction.objects.filter(
        company=company, request_type=request_type, request_id=req.pk,
        status="Pending",
    ).order_by("step_order").first()


def _finalize(company, request_type, req, final_status, actor, comment):
    now = timezone.now()
    extra = {}

    if request_type == "leave" and final_status == "Approved":
        applied, skipped = apply_leave_to_attendance(req, company, actor)
        extra = {
            "attendance_marked": [d.isoformat() for d in applied],
            "attendance_skipped_worked_days": [d.isoformat() for d in skipped],
        }

    req.status = final_status
    req.reviewed_by = actor
    req.reviewed_at = now
    req.review_comment = comment or req.review_comment
    req.updated_by = actor
    req.id_version = (req.id_version or 1) + 1
    req.save()
    return extra


def process_tier(user, company, request_type, req, decision, comment=None):
    """
    decision: "approve" | "reject".
    Returns (extra_dict, error_response_or_None).
    """
    from rest_framework import status as http_status

    if req.status != "Pending":
        return None, _err(
            "invalid_state",
            f"Only a Pending request can be actioned (this one is {req.status}).",
            http_status.HTTP_409_CONFLICT,
        )

    create_approval_actions(company, request_type, req, actor_label(user))
    action = current_pending_action(company, request_type, req)

    if action is None:
        return None, _err("no_pending_tier", "This request has no pending approval tier.",
                          http_status.HTTP_409_CONFLICT)

    if not can_act_on(user, action, req.Employee_ID):
        return None, _err(
            "permission_denied",
            "You are not the approver for the current tier of this request.",
            http_status.HTTP_403_FORBIDDEN,
        )

    actor = actor_label(user)
    now = timezone.now()

    action.acted_by = actor
    action.acted_at = now
    action.comment = comment or None
    action.updated_by = actor
    action.id_version = (action.id_version or 1) + 1

    if decision == "reject":
        action.status = "Rejected"
        action.save()
        ApprovalAction.objects.filter(
            company=company, request_type=request_type, request_id=req.pk,
            status="Pending",
        ).update(status="Skipped")
        extra = _finalize(company, request_type, req, "Rejected", actor, comment)
        return {"final": "Rejected", **extra}, None

    action.status = "Approved"
    action.save()

    nxt = current_pending_action(company, request_type, req)

    if nxt is not None:
        nxt.due_at = now + timedelta(hours=nxt.sla_hours)
        nxt.save(update_fields=["due_at"])
        return {"final": None, "next_tier": nxt.step_name}, None

    extra = _finalize(company, request_type, req, "Approved", actor, comment)
    return {"final": "Approved", **extra}, None


# ------------------------------------------------------------
# leave submission validation (shared)
# ------------------------------------------------------------

def check_leave_balance(company, employee_code, leave_type, from_date, days, exclude_pk=None):
    """Returns error_response or None."""
    from rest_framework import status as http_status

    policy = _policy_map(company).get(leave_type)
    if policy is None:
        return None
    if not policy.is_active:
        return _err("leave_type_disabled", f"{leave_type} is not enabled for your company.")

    fy = financial_year(from_date)
    row = next(
        (b for b in balances_for(company, employee_code, fy) if b["leave_type"] == leave_type),
        None,
    )
    if row is None or row["unlimited"]:
        return None

    available = row["available"]
    if exclude_pk:
        old = LeaveRequest.objects.filter(pk=exclude_pk, status="Pending").first()
        if old and financial_year(old.from_date) == fy and old.leave_type == leave_type:
            available += old.total_days

    if Decimal(days) > available:
        return _err(
            "insufficient_balance",
            f"Insufficient {policy.code or leave_type} balance: {available} day(s) "
            f"available, {days} requested.",
            http_status.HTTP_409_CONFLICT,
        )
    return None


def check_leave_policy_rules(company, leave_type, from_date, days, has_document=False):
    policy = _policy_map(company).get(leave_type)
    if policy is None:
        return None
    if policy.min_notice_hours:
        start = timezone.make_aware(datetime.combine(from_date, time(9, 0)))
        if (start - timezone.now()).total_seconds() / 3600 < policy.min_notice_hours:
            return _err(
                "insufficient_notice",
                f"{leave_type} needs at least {policy.min_notice_hours} hours notice.",
            )
    return None


# ------------------------------------------------------------
# calendar (Leave Calendar tab) - shared by Admin/HR and Employee
# ------------------------------------------------------------

MAX_CALENDAR_DAYS = 93


def build_calendar(company, start, end, include_pending=True, only_employee=None,
                   department=None, request=None, hide_reasons=False):
    from Company.models import Holiday
    from Employee.models import EmployeeDT

    codes_map = _policy_map(company)
    code_of = {k: (v.code or k) for k, v in codes_map.items()}

    statuses = ["Approved", "Pending"] if include_pending else ["Approved"]

    leaves = LeaveRequest.objects.filter(
        company=company, is_active=True, status__in=statuses,
        from_date__lte=end, to_date__gte=start,
    )
    wfhs = WFHRequest.objects.filter(
        company=company, is_active=True, status__in=statuses,
        wfh_date__gte=start, wfh_date__lte=end,
    )
    if only_employee:
        leaves = leaves.filter(Employee_ID=only_employee)
        wfhs = wfhs.filter(Employee_ID=only_employee)

    leaves, wfhs = list(leaves), list(wfhs)

    emp_lookup = employee_map(
        company, [l.Employee_ID for l in leaves] + [w.Employee_ID for w in wfhs]
    )

    if department:
        def in_dept(code):
            e = emp_lookup.get(code)
            if e is None:
                return False
            name = e.department.name if getattr(e, "department_id", None) else e.Department
            return (name or "").strip().lower() == department.strip().lower()
        leaves = [l for l in leaves if in_dept(l.Employee_ID)]
        wfhs = [w for w in wfhs if in_dept(w.Employee_ID)]

    holidays = {
        h.date: h for h in Holiday.objects.filter(
            company=company, is_active=True, date__range=(start, end))
    }

    today = timezone.localdate()
    days = []
    cur = start

    while cur <= end:
        on_leave = []
        for l in leaves:
            if l.from_date <= cur <= l.to_date:
                emp = emp_lookup.get(l.Employee_ID)
                on_leave.append({
                    "employee_code": l.Employee_ID,
                    "name": l.Name or (emp.name if emp else l.Employee_ID),
                    "leave_type": l.leave_type,
                    "code": code_of.get(l.leave_type, l.leave_type),
                    "status": l.status,
                    "request_ref": leave_ref(l),
                    "reason": None if hide_reasons else l.reason,
                })
        wfh_list = []
        for w in wfhs:
            if w.wfh_date == cur:
                emp = emp_lookup.get(w.Employee_ID)
                wfh_list.append({
                    "employee_code": w.Employee_ID,
                    "name": w.Name or (emp.name if emp else w.Employee_ID),
                    "status": w.status,
                    "request_ref": wfh_ref(w),
                })

        holiday = holidays.get(cur)
        parts = [f"{x['name']} ({x['code']})" for x in on_leave]
        parts += [f"{x['name']} (WFH)" for x in wfh_list]

        if holiday:
            label = f"Holiday - {holiday.name}"
        elif cur.weekday() == 6:
            label = "Weekly Off"
        elif parts:
            label = ", ".join(parts)
        else:
            label = "Full Team In Attendance"

        days.append({
            "date": cur,
            "weekday": cur.strftime("%a"),
            "is_today": cur == today,
            "is_weekly_off": cur.weekday() == 6,
            "is_holiday": holiday is not None,
            "holiday_name": holiday.name if holiday else None,
            "on_leave": on_leave,
            "wfh": wfh_list,
            "on_leave_count": len(on_leave),
            "wfh_count": len(wfh_list),
            "label": label,
            "full_attendance": not (on_leave or wfh_list or holiday or cur.weekday() == 6),
        })
        cur += timedelta(days=1)

    return days


def parse_calendar_range(params):
    """(start, end, error_message). month/year or start_date/end_date."""
    today = timezone.localdate()
    try:
        if params.get("start_date") and params.get("end_date"):
            start = date.fromisoformat(params["start_date"])
            end = date.fromisoformat(params["end_date"])
        else:
            month = int(params.get("month") or today.month)
            year = int(params.get("year") or today.year)
            start = date(year, month, 1)
            end = (date(year + 1, 1, 1) if month == 12 else date(year, month + 1, 1)) - timedelta(days=1)
    except (TypeError, ValueError):
        return None, None, "Invalid month / year / start_date / end_date."

    if end < start:
        return None, None, "end_date cannot be before start_date."
    if (end - start).days + 1 > MAX_CALENDAR_DAYS:
        return None, None, f"Calendar range cannot exceed {MAX_CALENDAR_DAYS} days."
    return start, end, None


# Employees may back-date a leave request by at most this many days
# (e.g. sick leave applied after returning). Older -> ask HR.
PAST_LEAVE_GRACE_DAYS = 7

