"""Deterministic, offline mock of erp-api for the accuracy-evaluation harness.

Every erp-api call in this codebase goes through ``services.erp_client._request``.
``fake_request`` has the same signature and is installed with::

    from services import erp_client
    from evals.accuracy import mock_erp
    erp_client._request = mock_erp.fake_request      # or monkeypatch.setattr

It NEVER touches the network. It:

* identifies the caller from the bearer token (``make_token("employee")`` /
  ``make_token("manager")`` build unsigned JWT-shaped tokens);
* answers every GET route erp_client uses with a body in the shape the
  callers parse (shapes copied from the fixtures under tests/ and from the
  erp_client docstrings);
* records every write (any non-GET) in ``WRITES`` and answers with a
  plausible success body - nothing is ever sent anywhere;
* raises ``ErpApiUnavailable`` for an unknown route and records it in
  ``UNKNOWN_PATHS``;
* mirrors ``_request``'s status handling: a non-2xx status is returned as
  data only when the caller opted that status in (allow_*_body), otherwise
  it raises exactly as the real function would (401 -> ErpApiUnauthorized,
  anything else -> ErpApiUnavailable carrying status_code and body).

The world is frozen on TODAY = 2026-10-28 (Wednesday). ``FACTS`` is the
ground truth a grader can check answers against.

Reads are stateless: a write is recorded but does not change later reads,
so every conversation sees the same world.
"""
from __future__ import annotations

import base64
import json
import re
from datetime import date, timedelta
from typing import Optional
from urllib.parse import parse_qsl, urlsplit

from services import erp_client

TODAY = date(2026, 10, 28)
YEAR = 2026

WRITES: list = []
UNKNOWN_PATHS: list = []
CALLS: list = []          # every (method, path, params, persona) seen - for debugging

# The live /leave/team/members route 404s on the deployed erp-api (see the
# project notes); the app then falls back to the pending-leave name search.
# Default False = answer it with the documented members shape.
TEAM_MEMBERS_LIVE_404 = False

_PREFIX = "/api/v1/ai"

# ════════════════════════════════════════════════════════════════════════════
# The world
# ════════════════════════════════════════════════════════════════════════════

COMPANY_ID = 26
COMPANY_NAME = "Helixta Demo Pvt Ltd"

MANAGER = {
    "user_id": 4001, "employee_id": 4001, "name": "Anita Desai", "emp_no": "EMP-4001",
    "designation": "Engineering Manager", "department": "Engineering",
    "email": "anita.desai@helixta-demo.com", "doj": "2019-07-01",
    "probation_end_date": "2020-01-01", "is_confirmed": True,
}
MANAGERS_MANAGER = {"id": 3901, "employee_number": "EMP-3901", "name": "Vikram Mehta"}

# Direct reports of the manager persona. Ravi Kumar IS the employee persona,
# so his own leaves/regularizations appear in the manager's team queues too.
TEAM = [
    {"employee_id": 4101, "employee_number": "EMP-4101", "employee_name": "Ravi Kumar",
     "employee_designation": "Software Engineer", "employee_email": "ravi.kumar@helixta-demo.com"},
    {"employee_id": 4102, "employee_number": "EMP-4102", "employee_name": "Priya Sharma",
     "employee_designation": "QA Engineer", "employee_email": "priya.sharma@helixta-demo.com"},
    {"employee_id": 4103, "employee_number": "EMP-4103", "employee_name": "Dileep Anumula",
     "employee_designation": "Backend Developer", "employee_email": "dileep.anumula@helixta-demo.com"},
    {"employee_id": 4104, "employee_number": "EMP-4104", "employee_name": "Meera Iyer",
     "employee_designation": "UI Designer", "employee_email": "meera.iyer@helixta-demo.com"},
    {"employee_id": 4105, "employee_number": "EMP-4105", "employee_name": "Arjun Nair",
     "employee_designation": "DevOps Engineer", "employee_email": "arjun.nair@helixta-demo.com"},
    {"employee_id": 4106, "employee_number": "EMP-4106", "employee_name": "Sneha Kulkarni",
     "employee_designation": "Business Analyst", "employee_email": "sneha.kulkarni@helixta-demo.com"},
]
_TEAM_BY_ID = {m["employee_id"]: m for m in TEAM}

EMPLOYEE = {
    "user_id": 4101, "employee_id": 4101, "name": "Ravi Kumar", "emp_no": "EMP-4101",
    "designation": "Software Engineer", "department": "Engineering",
    "email": "ravi.kumar@helixta-demo.com", "doj": "2023-04-10",
    "probation_end_date": "2023-10-10", "is_confirmed": True,
}

PERSONAS = {
    "employee": {**EMPLOYEE, "is_manager": False, "is_hr": False, "role": "employee",
                 "role_id": "6", "user_type": "3", "manager_name": "Anita Desai"},
    "manager": {**MANAGER, "is_manager": True, "is_hr": False, "role": "manager",
                "role_id": "5", "user_type": "3", "manager_name": "Vikram Mehta"},
}
_PERSONA_BY_USER_ID = {p["user_id"]: k for k, p in PERSONAS.items()}

# ── Shifts ──────────────────────────────────────────────────────────────────
GENERAL_SHIFT = {
    "shift_id": 301, "shift_name": "General Shift", "shift_code": "SHIFT-26-0301",
    "shift_type": "NORMAL", "start_time": "09:30:00", "end_time": "18:30:00",
    "working_minutes": 540, "break_time_minutes": 60, "relief_time_minutes": 15,
    "week_off_day": ["Saturday", "Sunday"], "status": "1",
    "is_general_shift": True, "is_readonly": False,
    "session_summary": {"total_sessions": 0, "total_working_minutes": 0,
                        "total_break_time_minutes": 0, "total_relief_time_minutes": 0},
    "sessions": [],
}
MANAGEMENT_SHIFT = {
    **GENERAL_SHIFT, "shift_id": 305, "shift_name": "Management Shift",
    "shift_code": "SHIFT-26-0305", "start_time": "10:00:00", "end_time": "19:00:00",
    "is_general_shift": False,
}


def _shift_for(employee_id: int) -> dict:
    return MANAGEMENT_SHIFT if employee_id == MANAGER["employee_id"] else GENERAL_SHIFT


# ── Holidays (department calendar, 2026) ────────────────────────────────────
HOLIDAYS = [
    ("New Year's Day", "2026-01-01"), ("Republic Day", "2026-01-26"),
    ("Holi", "2026-03-04"), ("Good Friday", "2026-04-03"),
    ("Labour Day", "2026-05-01"), ("Independence Day", "2026-08-15"),
    ("Ganesh Chaturthi", "2026-09-14"), ("Gandhi Jayanti", "2026-10-02"),
    ("Diwali", "2026-11-08"), ("Guru Nanak Jayanti", "2026-11-24"),
    ("Christmas", "2026-12-25"),
]
_HOLIDAY_ON = {d: n for n, d in HOLIDAYS}

# ── Leave balances (distinctive figures) ────────────────────────────────────
BALANCES = {
    "employee": {
        "casual_leave": {"total": 12, "used": 4.5, "remaining": 7.5},
        "sick_leave": {"total": 8, "used": 2, "remaining": 6},
        "earned_leave": {"total": 15, "used": 3, "remaining": 11},
        "short_leave": {"total": 6, "used": 2, "remaining": 4},
        "comp_off": {"total": 2, "used": 1, "remaining": 1},
        "leave_without_pay": {"total": 0, "used": 0, "remaining": 0},
    },
    "manager": {
        "casual_leave": {"total": 12, "used": 2.5, "remaining": 9.5},
        "sick_leave": {"total": 8, "used": 0, "remaining": 8},
        "earned_leave": {"total": 18, "used": 5, "remaining": 13},
        "short_leave": {"total": 6, "used": 1, "remaining": 5},
        "comp_off": {"total": 0, "used": 0, "remaining": 0},
        "leave_without_pay": {"total": 0, "used": 0, "remaining": 0},
    },
}
LEAVE_TYPE_NAMES = {
    "casual_leave": "Casual Leave", "sick_leave": "Sick Leave", "earned_leave": "Earned Leave",
    "short_leave": "Short Leave", "comp_off": "Comp Off", "leave_without_pay": "Leave Without Pay",
}
REGULARIZATION_MAX_PER_CYCLE = 3
REGULARIZATION_ALLOWED_DAYS = 30
PAYROLL_CYCLE = {"type": "custom", "start_date": "2026-10-21", "end_date": "2026-11-20"}


def _leave_settings() -> dict:
    return {
        "back_date_leave_allow": "1",
        "is_leave_monthy_credit": "1",
        "comp_off_expire_days": 30,
        "session_type": [{"name": "Full Day", "slug": "full_day"},
                         {"name": "First Half", "slug": "first_half"},
                         {"name": "Second Half", "slug": "second_half"}],
        "regularization_allowed_days": REGULARIZATION_ALLOWED_DAYS,
        "regularization_limit": str(REGULARIZATION_MAX_PER_CYCLE),
        "leave_type": [
            {"name": "Casual Leave", "slug": "casual_leave", "quota": 12, "max_apply_in_month": 3,
             "benefit_start": "joining", "oneTypeMax": "3", "is_carry_forward": False,
             "notice_period_applicable": "0", "salary_settlement": "0"},
            {"name": "Sick Leave", "slug": "sick_leave", "quota": 8, "max_apply_in_month": 4,
             "benefit_start": "joining", "oneTypeMax": "4", "is_carry_forward": False,
             "notice_period_applicable": "1", "salary_settlement": "0"},
            {"name": "Earned Leave", "slug": "earned_leave", "quota": 15, "max_apply_in_month": 10,
             "benefit_start": "confirmation", "oneTypeMax": "10", "is_carry_forward": True,
             "notice_period_applicable": "0", "salary_settlement": "1"},
            {"name": "Short Leave", "slug": "short_leave", "quota": 6, "max_apply_in_month": 2,
             "benefit_start": "joining", "oneTypeMax": "1", "is_carry_forward": False,
             "notice_period_applicable": "0", "salary_settlement": "0"},
            # erp-api sends the regularization policy as a leave_type entry;
            # erp_client._split_regularization_policy moves it out.
            {"name": "Regularization", "slug": "regularization",
             "max_apply_in_month": REGULARIZATION_MAX_PER_CYCLE, "benefit_start": "joining",
             "regularization_allowed_days": REGULARIZATION_ALLOWED_DAYS},
        ],
    }


# ── Leave requests ──────────────────────────────────────────────────────────
_STATUS_CODE = {"pending": 0, "approved": 1, "rejected": 2, "cancelled": 3}


def _leave(id_, emp_id, slug, frm, to, count, status, reason, applied, approver,
           session="Full Day", extra=None):
    m = _TEAM_BY_ID.get(emp_id) or {"employee_number": MANAGER["emp_no"],
                                    "employee_name": MANAGER["name"],
                                    "employee_designation": MANAGER["designation"]}
    row = {
        "id": id_, "employee_id": emp_id, "employee_number": m["employee_number"],
        "employee_name": m["employee_name"], "employee_designation": m["employee_designation"],
        "leave_type": LEAVE_TYPE_NAMES[slug], "leave_type_slug": slug,
        "session_type": session, "session_type_slug": session.lower().replace(" ", "_"),
        "from_date": frm, "to_date": to, "leave_count": str(count), "total_days": count,
        "status": _STATUS_CODE[status], "status_name": status, "reason": reason,
        "applied_date": applied, "approver_name": approver["name"], "role": "manager",
        "rejection_reason": None, "cancel_reason": None,
    }
    row.update(extra or {})
    return row


_ANITA = {"name": "Anita Desai"}
_VIKRAM = {"name": "Vikram Mehta"}

# Every leave in the world. Ravi's (4101) are the employee persona's own;
# 4001's are the manager persona's own; the rest are the manager's team.
LEAVES = [
    # Ravi Kumar (employee persona)
    _leave(9101, 4101, "casual_leave", "2026-11-02", "2026-11-03", 2, "pending",
           "Family function in Pune", "2026-10-26", _ANITA),
    _leave(9085, 4101, "casual_leave", "2026-10-16", "2026-10-16", 1, "approved",
           "Personal work", "2026-10-12", _ANITA),
    _leave(9060, 4101, "sick_leave", "2026-09-08", "2026-09-08", 1, "approved",
           "Fever", "2026-09-08", _ANITA),
    _leave(9040, 4101, "earned_leave", "2026-08-24", "2026-08-25", 2, "cancelled",
           "Trip postponed", "2026-08-10", _ANITA, extra={"cancel_reason": "Plans changed"}),
    _leave(9020, 4101, "short_leave", "2026-07-10", "2026-07-10", 0.5, "rejected",
           "Bank work", "2026-07-08", _ANITA, session="First Half",
           extra={"rejection_reason": "Release deadline that day"}),
    # The rest of the team
    _leave(9102, 4102, "sick_leave", "2026-10-29", "2026-10-29", 1, "pending",
           "Medical appointment", "2026-10-27", _ANITA),
    _leave(9103, 4103, "earned_leave", "2026-11-09", "2026-11-13", 5, "pending",
           "Diwali vacation with family", "2026-10-20", _ANITA),
    _leave(9090, 4104, "casual_leave", "2026-10-19", "2026-10-19", 1, "approved",
           "House shifting", "2026-10-14", _ANITA),
    _leave(9070, 4105, "sick_leave", "2026-10-05", "2026-10-05", 1, "cancelled",
           "Feeling unwell", "2026-10-05", _ANITA, extra={"cancel_reason": "Recovered"}),
    _leave(9095, 4102, "casual_leave", "2026-10-28", "2026-10-28", 1, "approved",
           "Personal errand", "2026-10-22", _ANITA),
    # Anita Desai (manager persona's own leaves; her approver is Vikram Mehta)
    _leave(9200, 4001, "earned_leave", "2026-09-21", "2026-09-22", 2, "approved",
           "Family trip", "2026-09-10", _VIKRAM),
    _leave(9210, 4001, "casual_leave", "2026-11-20", "2026-11-20", 1, "pending",
           "Personal work", "2026-10-25", _VIKRAM),
]


def _own_leaves(persona: str) -> list:
    uid = PERSONAS[persona]["user_id"]
    return [l for l in LEAVES if l["employee_id"] == uid]


def _team_leaves() -> list:
    return [l for l in LEAVES if l["employee_id"] in _TEAM_BY_ID]


# ── Regularizations ─────────────────────────────────────────────────────────
def _reg(id_, emp_id, apply_date, frm, to, reason, status, created, applied_to, action_by=None,
         extra=None):
    m = _TEAM_BY_ID.get(emp_id) or {"employee_number": MANAGER["emp_no"],
                                    "employee_name": MANAGER["name"]}
    row = {
        "regularization_id": id_, "applied_to": applied_to, "action_by": action_by,
        "created_at": created, "employee_id": emp_id, "employee_number": m["employee_number"],
        "employee_name": m["employee_name"], "apply_date": apply_date,
        "from_time": frm, "to_time": to, "reason": reason,
        "status": _STATUS_CODE[status], "status_name": status,
    }
    row.update(extra or {})
    return row


REGULARIZATIONS = [
    # Ravi Kumar
    _reg(5501, 4101, "2026-10-14", "09:31:00", "18:30:00", "Forgot to punch out", "pending",
         "2026-10-15", "Anita Desai"),
    _reg(5480, 4101, "2026-09-17", "09:30:00", "18:35:00", "Biometric device not working",
         "approved", "2026-09-18", "Anita Desai", "Anita Desai"),
    _reg(5460, 4101, "2026-08-12", "10:00:00", "18:30:00", "Client visit", "rejected",
         "2026-08-13", "Anita Desai", "Anita Desai",
         extra={"rejection_reason": "No gate-pass entry for the client visit"}),
    # Team
    _reg(5601, 4103, "2026-10-23", "09:30:00", "18:30:00", "Missed punch-out", "pending",
         "2026-10-24", "Anita Desai"),
    _reg(5602, 4104, "2026-10-26", "09:45:00", "18:40:00", "Biometric device not working",
         "pending", "2026-10-27", "Anita Desai"),
    # Anita Desai's own
    _reg(5300, 4001, "2026-09-30", "10:00:00", "19:05:00", "Forgot to punch in", "approved",
         "2026-10-01", "Vikram Mehta", "Vikram Mehta"),
]


# ── Attendance ──────────────────────────────────────────────────────────────
# Per-employee overrides on top of the default pattern (weekday Present,
# weekend Off, calendar holiday Holiday, TODAY no status, future no status).
ATTENDANCE_OVERRIDES = {
    4101: {  # Ravi Kumar (employee persona)
        "2026-10-07": "Half Day Absent",
        "2026-10-14": "Missing Punch",
        "2026-10-16": "Leave",
        "2026-10-20": "Absent",
        "2026-09-08": "Leave",
        "2026-09-23": "Half Day Absent",
    },
    4001: {  # Anita Desai (manager persona)
        "2026-10-09": "Half Day Absent",
        "2026-10-21": "Missing Punch",
        "2026-09-21": "Leave", "2026-09-22": "Leave",
    },
    4102: {"2026-10-28": "Leave", "2026-10-13": "Half Day Absent"},
    4103: {"2026-10-23": "Missing Punch", "2026-10-28": "Present"},
    4104: {"2026-10-26": "Missing Punch", "2026-10-19": "Leave", "2026-10-28": "Present"},
    4105: {"2026-10-28": "Missing Punch", "2026-10-05": "Absent"},
    4106: {"2026-10-28": "Present", "2026-10-22": "Absent"},
}
# Team members' "today" defaults to Present where not overridden (mid-day
# data for a team view); the PERSONAS' own today is unrecorded.
_TEAM_TODAY_DEFAULT = "Present"


def _status_on(emp_id: int, d: date) -> Optional[str]:
    iso = d.isoformat()
    ov = ATTENDANCE_OVERRIDES.get(emp_id, {})
    if iso in ov:
        return ov[iso]
    if d > TODAY:
        return None
    if d == TODAY:
        return _TEAM_TODAY_DEFAULT if emp_id in _TEAM_BY_ID and emp_id != EMPLOYEE["employee_id"] else None
    if iso in _HOLIDAY_ON:
        return "Holiday"
    if d.weekday() >= 5:
        return "Off"
    return "Present"


_ATT_CODE = {
    "Present": ("P", "Present"), "Off": ("O", "Off"), "Holiday": ("O", "Holiday"),
    "Absent": ("A", "Absent"), "Half Day Absent": ("PA", "Half Day Absent"),
    "Missing Punch": ("A", "Missing punch"), "Leave": ("L", "Leave"),
}


def _punch_times(emp_id: int, d: date):
    """Deterministic check-in/out minutes for a normal day."""
    shift = _shift_for(emp_id)
    sh, sm = int(shift["start_time"][:2]), int(shift["start_time"][3:5])
    jitter = (d.day * 7 + emp_id) % 14 - 6        # -6..+7 minutes
    cin = sh * 60 + sm + jitter
    cout = cin + 9 * 60 + (d.day * 3 + emp_id) % 20
    return cin, cout


def _hm(minutes: int) -> str:
    return f"{minutes // 60:02d}:{minutes % 60:02d}"


def _punch_details(emp_id: int, d: date) -> dict:
    iso = d.isoformat()
    status = _status_on(emp_id, d)
    shift = _shift_for(emp_id)
    shift_block = {"id": shift["shift_id"], "name": shift["shift_name"],
                   "start_time": shift["start_time"], "end_time": shift["end_time"],
                   "week_off_days": list(shift["week_off_day"]), "relief_time": "15", "status": "1"}
    base = {"requested_date": iso, "logical_shift_date": iso, "shift": shift_block,
            "day_status": None}
    cin, cout = _punch_times(emp_id, d)

    def ts(m):
        return f"{iso} {_hm(m)}:00"

    reg = next((r for r in REGULARIZATIONS if r["employee_id"] == emp_id and r["apply_date"] == iso
                and r["status_name"] in ("pending", "approved")), None)
    is_reg = bool(reg and reg["status_name"] == "approved")

    if d > TODAY:
        return {**base, "attendance": None, "punch_status": "no_records", "punch_count": 0,
                "punches": [], "work_hours": {"available": False, "value": None,
                                              "source": "users_attendence",
                                              "reason": "No punch records found"}}
    if d == TODAY and status is None:
        # Checked in this morning, shift still running: no status yet.
        return {**base, "attendance": None, "punch_status": "incomplete", "punch_count": 1,
                "punches": [{"punch_number": 1, "check_in": ts(cin), "check_out": None,
                             "complete": False, "missing": "check_out"}],
                "work_hours": {"available": False, "value": None, "source": "users_attendence",
                               "reason": "Shift in progress"}}
    code, remark = _ATT_CODE.get(status, ("P", status))
    att = {"attendance": code, "attendance_remark": remark, "working_type": "1",
           "reason": None, "is_regularized": is_reg}
    if is_reg:
        att["attendance"] = "R(" + code + ")"
    if status in ("Off", "Holiday", "Leave", "Absent"):
        if status == "Holiday":
            att["attendance_remark"] = f"Holiday - {_HOLIDAY_ON.get(iso, '')}".strip(" -")
            base["day_status"] = "Holiday"
        elif status == "Off":
            base["day_status"] = "Weekly Off"
        return {**base, "attendance": att, "punch_status": "no_records", "punch_count": 0,
                "punches": [], "work_hours": {"available": False, "value": None,
                                              "source": "users_attendence",
                                              "reason": "No punch records found"}}
    if status == "Missing Punch":
        return {**base, "attendance": att, "punch_status": "incomplete", "punch_count": 1,
                "punches": [{"punch_number": 1, "check_in": ts(cin), "check_out": None,
                             "complete": False, "missing": "check_out"}],
                "work_hours": {"available": False, "value": None, "source": "users_attendence",
                               "reason": "Check-out missing"}}
    if status == "Half Day Absent":
        cout = cin + 4 * 60 + 5
    return {**base, "attendance": att, "punch_status": "complete", "punch_count": 1,
            "punches": [{"punch_number": 1, "check_in": ts(cin), "check_out": ts(cout),
                         "complete": True, "missing": None}],
            "work_hours": {"available": True, "value": _hm(cout - cin),
                           "source": "users_attendence", "reason": None}}


# ════════════════════════════════════════════════════════════════════════════
# Tokens
# ════════════════════════════════════════════════════════════════════════════

def _b64(obj) -> str:
    raw = json.dumps(obj, separators=(",", ":")).encode()
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")


def token_claims(persona: str) -> dict:
    p = PERSONAS[persona]
    return {
        "user_id": p["user_id"], "employee_id": p["employee_id"], "company_id": COMPANY_ID,
        "company_name": COMPANY_NAME, "name": p["name"], "username": p["name"],
        "emp_no": p["emp_no"], "role": p["role"], "role_name": p["role"],
        "role_id": p["role_id"], "user_type": p["user_type"],
        "iat": 1792000000, "exp": 4102444800, "eval_persona": persona,
    }


def make_token(persona: str) -> str:
    """Unsigned JWT-shaped token for 'employee' or 'manager'."""
    if persona not in PERSONAS:
        raise ValueError(f"unknown persona {persona!r}; use one of {sorted(PERSONAS)}")
    return f"{_b64({'alg': 'HS256', 'typ': 'JWT'})}.{_b64(token_claims(persona))}.mock-signature"


def persona_from_token(bearer_token: Optional[str]) -> Optional[str]:
    if not bearer_token:
        return None
    tok = bearer_token.split(" ", 1)[-1] if bearer_token.lower().startswith("bearer ") else bearer_token
    try:
        seg = tok.split(".")[1]
        claims = json.loads(base64.urlsafe_b64decode(seg + "=" * (-len(seg) % 4)))
    except Exception:
        return None
    p = claims.get("eval_persona")
    if p in PERSONAS:
        return p
    try:
        return _PERSONA_BY_USER_ID.get(int(claims.get("user_id")))
    except (TypeError, ValueError):
        return None


# ════════════════════════════════════════════════════════════════════════════
# Helpers
# ════════════════════════════════════════════════════════════════════════════

class _Reply(Exception):
    """Raised inside a handler to answer with a non-2xx status."""

    def __init__(self, status: int, body):
        super().__init__(status)
        self.status = status
        self.body = body


def _ok(data, message="success") -> dict:
    return {"success": True, "message": message, "data": data}


def _fail(status: int, message: str, data=None):
    body = {"success": False, "message": message}
    if data is not None:
        body["data"] = data
    raise _Reply(status, body)


def _d(s) -> Optional[date]:
    try:
        return date.fromisoformat(str(s)[:10])
    except (TypeError, ValueError):
        return None


def _norm(s) -> str:
    return re.sub(r"\s+", " ", str(s or "").strip().lower())


def _search_team(name: str) -> list:
    """erp-api's name search inside the caller's team: case-insensitive,
    the term matches the full name, or a whole-word prefix of it."""
    q = _norm(name)
    hits = []
    for m in TEAM:
        full = _norm(m["employee_name"])
        toks = full.split()
        if q == full or q in full and len(q) >= 3 or any(t.startswith(q) for t in toks) \
                or all(any(t.startswith(w) for t in toks) for w in q.split()):
            hits.append(m)
    return hits


def _menu_row(m, with_designation=False) -> dict:
    row = {"employee_id": m["employee_id"], "employee_number": m["employee_number"],
           "employee_name": m["employee_name"]}
    if with_designation:
        row["designation"] = m["employee_designation"]
    return row


def _select_employee(name: str, *, with_designation=False) -> dict:
    """The select_employee answer erp-api gives for an employee_name lookup."""
    if len(str(name or "").strip()) < 2:
        _fail(400, "Please enter at least 2 characters of the employee name.",
              {"action_required": "search_employee"})
    hits = _search_team(name)
    if hits:
        return {"success": True, "message": "Please select an employee.",
                "data": {"action_required": "select_employee", "search_matched": True,
                         "employees": [_menu_row(m, with_designation) for m in hits]}}
    return {"success": True,
            "message": "No employee matched that name. Please select an employee from your team.",
            "data": {"action_required": "select_employee", "search_matched": False,
                     "employees": [_menu_row(m, with_designation) for m in TEAM]}}


_OTHER_EMPLOYEE_403 = ("I cannot retrieve information for other employees. "
                       "You can only view your own records.")
_TEAM_LEAVES_403 = ("Team leave requests are only available to HR, admin or managers with "
                    "direct reports. You can still check your own leave requests.")


def _require_manager(persona, message=_TEAM_LEAVES_403):
    if persona != "manager":
        _fail(403, message)


def _target_employee(persona, params, *, allow_self_id=True):
    """Resolve employee_id/employee_name params -> (employee_id, name, menu_body).
    menu_body is set when erp-api would answer with a selection menu."""
    me = PERSONAS[persona]
    emp_id = params.get("employee_id")
    emp_name = params.get("employee_name")
    if emp_id not in (None, ""):
        try:
            emp_id = int(emp_id)
        except (TypeError, ValueError):
            _fail(403, "Employee not found in your team.")
        if emp_id == me["employee_id"]:
            if allow_self_id:
                return emp_id, me["name"], None
            _fail(403, "Employee not found in your team.")
        if persona == "manager" and emp_id in _TEAM_BY_ID:
            return emp_id, _TEAM_BY_ID[emp_id]["employee_name"], None
        _fail(403, _OTHER_EMPLOYEE_403 if persona != "manager" else "Employee not found in your team.")
    if emp_name:
        if _norm(emp_name) in (_norm(me["name"]), _norm(me["emp_no"])):
            return me["employee_id"], me["name"], None
        if persona != "manager":
            _fail(403, _OTHER_EMPLOYEE_403)
        return None, None, _select_employee(emp_name)
    return me["employee_id"], me["name"], None


def _split_path(path: str, params: Optional[dict]):
    """Split a baked-in querystring off the path and merge it with params."""
    parts = urlsplit(path)
    merged = dict(parse_qsl(parts.query))
    merged.update({k: v for k, v in (params or {}).items() if v is not None})
    route = parts.path
    if route.startswith(_PREFIX):
        route = route[len(_PREFIX):]
    return route, merged


# ════════════════════════════════════════════════════════════════════════════
# GET handlers
# ════════════════════════════════════════════════════════════════════════════

def _h_ping(persona, params):
    return _ok({"status": "ok", "user_id": PERSONAS[persona]["user_id"],
                "server_time": f"{TODAY.isoformat()} 11:00:00"}, "pong")


def _context_for(p: dict) -> dict:
    return {"user_id": p["user_id"], "name": p["name"], "emp_no": p["emp_no"],
            "company_id": COMPANY_ID, "is_manager": p["is_manager"], "is_hr": p["is_hr"],
            "is_confirmed": p["is_confirmed"], "probation_end_date": p["probation_end_date"],
            "doj": p["doj"], "designation": p["designation"], "department": p["department"]}


def _h_leave_context(persona, params):
    name = params.get("employee_name")
    me = PERSONAS[persona]
    if name and _norm(name) not in (_norm(me["name"]), _norm(me["emp_no"])):
        if persona != "manager":
            _fail(400, _OTHER_EMPLOYEE_403)
        hits = _search_team(name)
        if len(hits) != 1:
            return _select_employee(name)
        m = hits[0]
        return _ok({"user_id": m["employee_id"], "name": m["employee_name"],
                    "emp_no": m["employee_number"], "company_id": COMPANY_ID,
                    "is_manager": False, "is_hr": False, "is_confirmed": True,
                    "probation_end_date": "2024-01-15", "doj": "2023-07-15",
                    "designation": m["employee_designation"], "department": "Engineering"})
    return _ok(_context_for(me))


def _h_leave_balance(persona, params):
    name = params.get("employee_name")
    me = PERSONAS[persona]
    if name and _norm(name) not in (_norm(me["name"]), _norm(me["emp_no"])):
        _fail(400, "You are not authorized to view another employee's leave balance.")
    quota = {slug: dict(v) for slug, v in BALANCES[persona].items()}
    return _ok({"leave_quota": quota, "leave_settings": _leave_settings(),
                "payroll_cycle": dict(PAYROLL_CYCLE)})


def _h_abbreviations(persona, params):
    return _ok({"A": "Absent", "L": "Leave", "EL": "Earned Leave", "CL": "Casual Leave",
                "SL": "Sick Leave", "CO": "Comp Off", "LWP": "Leave Without Pay",
                "HD": "Half Day Leave", "SHL": "Short Leave", "P": "Present", "O": "Off",
                "PA": "Half Day Absent", "R(PA)": "Approved Regularization",
                "R(A)": "Approved Regularization", "R(P)": "Approved Regularization",
                "LC": "Half Day Absent", "NCNS": "No Come No Show"})


def _h_holidays(persona, params):
    rows = [{"id": 700 + i, "holiday_name": n, "holiday_date": d,
             "day": date.fromisoformat(d).strftime("%A")} for i, (n, d) in enumerate(HOLIDAYS, 1)]
    return _ok({"year": YEAR, "department": "Engineering", "total_holidays": len(rows),
                "holidays": rows})


def _date_filter(rows, applied_leave_date):
    if not applied_leave_date:
        return rows
    return [r for r in rows if applied_leave_date in (r["from_date"], r["to_date"])]


def _own_leave_row(r):
    keep = ("id", "leave_type", "leave_type_slug", "session_type", "session_type_slug",
            "from_date", "to_date", "status", "status_name", "reason", "applied_date",
            "total_days", "leave_count", "approver_name", "role", "rejection_reason",
            "cancel_reason")
    return {k: r[k] for k in keep}


def _sorted_desc(rows):
    return sorted(rows, key=lambda r: r["id"], reverse=True)


def _h_leave_pending(persona, params):
    rows = [r for r in _own_leaves(persona) if r["status_name"] == "pending"]
    rows = _date_filter(rows, params.get("applied_leave_date"))
    return _ok({"leaves": [_own_leave_row(r) for r in _sorted_desc(rows)]})


def _h_leave_applied(persona, params):
    status = _norm(params.get("leave_status") or "all")
    rows = _own_leaves(persona)
    if status != "all":
        rows = [r for r in rows if r["status_name"] == status]
    rows = _date_filter(rows, params.get("applied_leave_date"))
    rows = [_own_leave_row(r) for r in _sorted_desc(rows)]
    return _ok({"leave_status": status, "total_leaves": len(rows), "leaves": rows})


def _h_leave_status(persona, params):
    # The route is believed gone live (see erp_client.get_leave_status); no
    # caller uses it. Answered with the applied shape for completeness.
    rows = _date_filter(_own_leaves(persona), params.get("applied_leave_date"))
    return _ok({"leaves": [_own_leave_row(r) for r in _sorted_desc(rows)]})


def _team_row(r):
    keep = ("id", "employee_id", "employee_number", "employee_name", "employee_designation",
            "leave_type", "leave_type_slug", "session_type", "session_type_slug", "from_date",
            "to_date", "leave_count", "status", "status_name", "reason", "applied_date",
            "rejection_reason", "cancel_reason")
    return {k: r[k] for k in keep}


def _h_team_leaves(persona, params):
    _require_manager(persona)
    typ = _norm(params.get("type") or "pending")
    rows = _team_leaves()
    if typ != "all":
        rows = [r for r in rows if r["status_name"] == typ]
    rows = sorted(rows, key=lambda r: (r["from_date"], r["id"]))
    employee = None
    if params.get("employee_id") not in (None, ""):
        try:
            emp_id = int(params["employee_id"])
        except (TypeError, ValueError):
            emp_id = None
        if emp_id not in _TEAM_BY_ID:
            _fail(403, "Employee not found in your team.")
        rows = [r for r in rows if r["employee_id"] == emp_id]
        m = _TEAM_BY_ID[emp_id]
        employee = {"name": m["employee_name"], "emp_no": m["employee_number"]}
    elif params.get("employee_name"):
        return _select_employee(params["employee_name"])
    all_team = _team_leaves()
    if employee:
        all_team = [r for r in all_team if r["employee_id"] == int(params["employee_id"])]
    data = {"access_scope": "direct_reports", "type": typ,
            "total_leaves": len(rows),
            "total_pending_leaves": sum(1 for r in all_team if r["status_name"] == "pending"),
            "leaves": [_team_row(r) for r in rows]}
    if employee:
        data["employee"] = employee
    return _ok(data)


def _h_team_members(persona, params):
    if TEAM_MEMBERS_LIVE_404:
        raise _Reply(404, {"message": "Not Found"})
    _require_manager(persona, "Team members are only available to managers with direct reports.")
    members = [{**m, "relation": "direct"} for m in TEAM]
    return _ok({"access_scope": "direct_reports", "total_members": len(members),
                "members": members})


def _h_attendance_summary(persona, params):
    _require_manager(persona, "Team attendance summary is only available to managers.")
    d = _d(params.get("date")) if params.get("date") else TODAY
    if d is None:
        _fail(400, "The date field must match the format Y-m-d.")
    present = absent = on_leave = off = not_recorded = 0
    missing = []
    for m in TEAM:
        st = _status_on(m["employee_id"], d)
        if st is None:
            not_recorded += 1
        elif st in ("Present", "Half Day Absent"):
            present += 1
        elif st == "Missing Punch":
            present += 1
            cin, _ = _punch_times(m["employee_id"], d)
            missing.append({"employee_id": m["employee_id"], "employee_number": m["employee_number"],
                            "employee_name": m["employee_name"], "attendance_status": "missing punch",
                            "relation": "direct", "reporting_manager": MANAGER["name"],
                            "check_in": f"{d.isoformat()} {_hm(cin)}:00", "check_out": None})
        elif st == "Absent":
            absent += 1
        elif st == "Leave":
            on_leave += 1
        else:
            off += 1
    total = len(TEAM)
    return _ok({
        "type": "team_attendance_summary", "date": d.isoformat(), "scope": "direct_reports",
        "summary_cards": {
            "total_team": {"label": "Total Team", "value": total},
            "present": {"label": "Present", "value": present},
            "absent": {"label": "Absent", "value": absent},
            "on_leave": {"label": "On Leave", "value": on_leave},
            "missing_punches": {"label": "Missing Punches", "value": len(missing),
                                "missed_punch_count": len(missing)}},
        "breakdown": {"attendance_recorded": total - not_recorded - off,
                      "not_recorded": not_recorded, "off": off},
        "missing_punch_details": {
            "employee_count": len(missing), "incomplete_session_count": len(missing),
            "missing_check_ins": 0, "missing_check_outs": len(missing),
            "missed_punch_count": len(missing), "employees": missing}})


def _h_shift_details(persona, params):
    me = PERSONAS[persona]
    has_target = params.get("employee_id") not in (None, "") or params.get("employee_name")
    if persona == "manager" and not has_target:
        # Live behaviour: a manager with no target gets a selection menu
        # (shift_query then falls back to punch-details for "my shift").
        return {"success": True, "message": "Please select an employee to view shift details.",
                "data": {"action_required": "select_employee", "access_scope": "direct_reports",
                         "total_employees": len(TEAM),
                         "employees": [{**_menu_row(m), "department_id": 70, "designation_id": 96,
                                        "has_shift_assignment": True} for m in TEAM]}}
    emp_id, name, menu = _target_employee(persona, params, allow_self_id=(persona != "manager"))
    if menu is not None:
        return menu
    m = _TEAM_BY_ID.get(emp_id)
    employee = {
        "employee_id": emp_id,
        "employee_number": m["employee_number"] if m else me["emp_no"],
        "employee_name": name,
        "email": m["employee_email"] if m else me["email"],
        "phone": "98450" + str(emp_id)[-5:].rjust(5, "0"),
        "department_id": 70, "department_name": "Engineering", "designation_id": 96,
        "designation_name": m["employee_designation"] if m else me["designation"],
    }
    shift = _shift_for(emp_id)
    return _ok({"shift": dict(shift), "employee": employee,
                "assignment": {"assignment_id": 800 + emp_id % 100, "selected_session_id": None,
                               "effective_from": "2026-01-01"},
                "work_calendar": {"week_off_days": list(shift["week_off_day"])}})


def _h_punch_details(persona, params):
    emp_id, name, menu = _target_employee(persona, params)
    if menu is not None:
        return menu
    d = _d(params.get("date")) if params.get("date") else TODAY
    if d is None:
        raise _Reply(400, {"date": ["The date field must match the format Y-m-d."]})
    data = _punch_details(emp_id, d)
    msg = ("No punch records found for " + d.isoformat() + ".") if not data["punches"] else "ok"
    return {"success": True, "message": msg, "data": data}


def _h_attendance_query(persona, params):
    frm, to = _d(params.get("from")), _d(params.get("to"))
    if not frm or not to or to < frm:
        _fail(422, "Invalid attendance query.")
    me = PERSONAS[persona]
    if params.get("employee_name") and _norm(params["employee_name"]) not in (
            _norm(me["name"]), _norm(me["emp_no"])):
        if persona != "manager":
            _fail(403, _OTHER_EMPLOYEE_403)
        hits = _search_team(params["employee_name"])
        if len(hits) != 1:
            menu = _select_employee(params["employee_name"])
            menu["data"]["records"] = []
            return menu
        emp_id = hits[0]["employee_id"]
        extra = {"search_matched": True, "employee": {"name": hits[0]["employee_name"],
                                                      "emp_no": hits[0]["employee_number"]}}
    else:
        emp_id, _, _ = _target_employee(persona, {"employee_id": params.get("employee_id")})
        extra = {}
    days = (to - frm).days + 1
    statuses = [(frm + timedelta(i), _status_on(emp_id, frm + timedelta(i))) for i in range(days)]
    if days > 31:
        cnt = lambda *names: sum(1 for d, s in statuses if s in names)
        return _ok({"type": "summary", "from": frm.isoformat(), "to": to.isoformat(),
                    "total_days": days,
                    "summary": {"present": cnt("Present", "Missing Punch"), "absent": cnt("Absent"),
                                "leave": cnt("Leave"), "half_day_absent": cnt("Half Day Absent"),
                                "off": cnt("Off", "Holiday"), "regularized": 0,
                                "not_recorded": sum(1 for d, s in statuses if s is None and d <= TODAY),
                                "upcoming": sum(1 for d, s in statuses if d > TODAY)},
                    "navigation": {"module": "attendance", "from": frm.isoformat(),
                                   "to": to.isoformat()}, **extra},
                   "Attendance summary retrieved successfully.")
    records = [{"date": d.isoformat(), "day": d.strftime("%A"), "status": s} for d, s in statuses]
    return _ok({"type": "single" if days == 1 else "daily", "from": frm.isoformat(),
                "to": to.isoformat(), "total_days": days, "records": records, **extra},
               "Attendance retrieved successfully.")


def _h_attendance_explain(persona, params):
    # No production caller; shape follows tests/test_attendance_explain.py.
    d = _d(params.get("date"))
    if d is None:
        _fail(422, "Invalid date.")
    emp_id = PERSONAS[persona]["employee_id"]
    st = _status_on(emp_id, d)
    pd = _punch_details(emp_id, d)
    shift = _shift_for(emp_id)
    violations = []
    if st in ("Half Day Absent", "Missing Punch", "Absent"):
        p = (pd["punches"] or [{}])[0]
        violations.append({
            "type": st.lower().replace(" ", "_"),
            "reason": {"Half Day Absent": "Worked hours were below the full-day threshold of 8 hours.",
                       "Missing Punch": "No check-out was recorded for the shift.",
                       "Absent": "No punches were recorded for a working day."}[st],
            "policy_rule": "Standard Attendance Policy",
            "shift": {"start": shift["start_time"][:5], "end": shift["end_time"][:5],
                      "grace_minutes": 15},
            "actual": {"check_in": (p.get("check_in") or "")[11:16] or None,
                       "check_out": (p.get("check_out") or "")[11:16] or None},
        })
    return _ok({"date": d.isoformat(), "status": (st or "not_recorded").lower().replace(" ", "_"),
                "violations": violations})


def _h_regularizations(persona, params):
    status = _norm(params.get("status") or "all")
    if params.get("type") == "all":
        _require_manager(persona, "Only Manager/HR users can view team regularization requests.")
        rows = [r for r in REGULARIZATIONS if r["employee_id"] in _TEAM_BY_ID]
    else:
        uid = PERSONAS[persona]["user_id"]
        rows = [r for r in REGULARIZATIONS if r["employee_id"] == uid]
    if status != "all":
        rows = [r for r in rows if r["status_name"] == status]
    rows = sorted(rows, key=lambda r: (r["created_at"], r["regularization_id"]), reverse=True)
    data = {
        "total_regularizations": len(rows),
        "total_pending_regularizations": sum(r["status_name"] == "pending" for r in rows),
        "total_approved_regularizations": sum(r["status_name"] == "approved" for r in rows),
        "total_rejected_regularizations": sum(r["status_name"] == "rejected" for r in rows),
        "total_cancelled_regularizations": sum(r["status_name"] == "cancelled" for r in rows),
        "regularizations": [dict(r) for r in rows],
    }
    return _ok(data)


GET_ROUTES = {
    "/ping": _h_ping,
    "/leave/context": _h_leave_context,
    "/leave/balance": _h_leave_balance,
    "/leaves/abbreviations": _h_abbreviations,
    "/leave/holidays": _h_holidays,
    "/leave/pending": _h_leave_pending,
    "/leave/applied": _h_leave_applied,
    "/leave/status": _h_leave_status,
    "/team/leaves": _h_team_leaves,
    "/leave/pending/teams": _h_team_leaves,     # older alias of the same list
    "/leave/team/members": _h_team_members,
    "/attendance/summary": _h_attendance_summary,
    "/shift-details": _h_shift_details,
    "/attendance/punch-details": _h_punch_details,
    "/attendance/query": _h_attendance_query,
    "/attendance/explain": _h_attendance_explain,
    "/regularizations": _h_regularizations,
}


# ════════════════════════════════════════════════════════════════════════════
# Writes (recorded, never sent)
# ════════════════════════════════════════════════════════════════════════════

def _weekdays_between(frm: date, to: date) -> int:
    n, d = 0, frm
    while d <= to:
        if d.weekday() < 5 and d.isoformat() not in _HOLIDAY_ON:
            n += 1
        d += timedelta(days=1)
    return n


def _w_apply_leave(persona, body):
    body = body or {}
    slug = body.get("leave_type_slug")
    frm, to = _d(body.get("from_date")), _d(body.get("to_date"))
    quota = BALANCES[persona]
    if slug not in quota or slug not in LEAVE_TYPE_NAMES:
        _fail(400, "Invalid leave type selected.")
    if not frm or not to or to < frm:
        _fail(400, "The to date must be a date after or equal to from date.")
    half = body.get("session_type_slug") in ("first_half", "second_half")
    days = 0.5 if half else _weekdays_between(frm, to)
    if days == 0:
        _fail(400, "The selected dates fall on weekly offs or holidays. No leave is required.")
    for r in _own_leaves(persona):
        if r["status_name"] in ("pending", "approved") and not (
                to < date.fromisoformat(r["from_date"]) or frm > date.fromisoformat(r["to_date"])):
            _fail(400, f"You have already applied {r['leave_type']} from {r['from_date']} "
                       f"to {r['to_date']}.")
    if float(quota[slug]["remaining"]) < days:
        _fail(400, f"Insufficient leave balance. You have {quota[slug]['remaining']} "
                   f"{LEAVE_TYPE_NAMES[slug]} remaining.")
    new_id = 9300 + len(WRITES)
    rows = [{"id": r["id"], "from_date": r["from_date"]} for r in _own_leaves(persona)]
    rows.append({"id": new_id, "from_date": frm.isoformat()})
    return 200, {"success": True, "message": "Leave applied successfully.", "data": rows}


def _w_cancel_leave(persona, body):
    body = body or {}
    try:
        lid = int(body.get("leave_id"))
    except (TypeError, ValueError):
        _fail(400, "Invalid leave id.")
    row = next((r for r in _own_leaves(persona) if r["id"] == lid), None)
    if row is None:
        _fail(400, "Leave request not found.")
    if row["status_name"] not in ("pending", "approved"):
        _fail(400, f"This leave request is already {row['status_name']} and cannot be cancelled.")
    if row["status_name"] == "approved" and date.fromisoformat(row["from_date"]) < TODAY:
        _fail(400, "A past approved leave cannot be cancelled. Please contact HR.")
    return 200, {"success": True, "message": "Leave request cancelled successfully.",
                 "data": {"leave_id": lid, "status": 3, "status_name": "Cancelled",
                          "leave_type_slug": row["leave_type_slug"],
                          "leave_count": row["leave_count"],
                          "cancel_reason": body.get("cancel_reason")}}


def _team_pending_leave(persona, lid):
    if persona != "manager":
        _fail(400, "Pending leave request was not found in your team.")
    row = next((r for r in _team_leaves() if r["id"] == lid and r["status_name"] == "pending"), None)
    if row is None:
        _fail(404, "Pending leave request was not found in your team.")
    return row


def _w_leave_decision(persona, lid, decision, body):
    row = _team_pending_leave(persona, lid)
    data = {k: row[k] for k in ("employee_id", "employee_number", "employee_name", "leave_type",
                                "leave_type_slug", "session_type", "session_type_slug",
                                "from_date", "to_date", "leave_count", "reason", "applied_date")}
    data["leave_request_id"] = lid
    me = {"id": MANAGER["user_id"], "employee_number": MANAGER["emp_no"], "name": MANAGER["name"]}
    if decision == "approve":
        data.update({"status": 1, "status_name": "approved", "approved_by": me})
        return 200, {"success": True, "message": "Leave request approved successfully.", "data": data}
    data.update({"status": 2, "status_name": "rejected",
                 "rejection_reason": (body or {}).get("rejection_reason"), "decided_by": me})
    return 200, {"success": True, "message": "Leave request rejected successfully.", "data": data}


def _w_apply_regularization(persona, body):
    body = body or {}
    d = _d(body.get("apply_date"))
    if d is None:
        _fail(422, "The apply date field must be a valid date.")
    if d > TODAY:
        _fail(422, "Regularization cannot be applied for a future date.")
    if (TODAY - d).days > REGULARIZATION_ALLOWED_DAYS:
        _fail(422, "Regularization period has expired")
    return 200, {"success": True, "message": "Regularization applied successfully.",
                 "data": {"regularization_id": 5700 + len(WRITES), "apply_date": d.isoformat(),
                          "status": 0, "status_name": "pending"}}


def _w_reg_decision(persona, path, body):
    body = body or {}
    try:
        rid = int(body.get("regularization_id"))
    except (TypeError, ValueError):
        _fail(400, "The regularization id field is required.")
    action = path.rsplit("/", 1)[-1]
    if action == "cancel":
        uid = PERSONAS[persona]["user_id"]
        row = next((r for r in REGULARIZATIONS if r["regularization_id"] == rid
                    and r["employee_id"] == uid), None)
        if row is None:
            _fail(404, "Regularization request not found.")
        if row["status_name"] != "pending":
            _fail(422, f"Only pending regularization requests can be cancelled. This one is {row['status_name']}.")
        return 200, {"success": True, "message": "Regularization request cancelled successfully.",
                     "data": {"regularization_id": rid, "status": 3, "status_name": "cancelled",
                              "cancel_reason": body.get("cancel_reason")}}
    if persona != "manager":
        _fail(400, "Pending regularization request was not found in your team.")
    row = next((r for r in REGULARIZATIONS if r["regularization_id"] == rid
                and r["employee_id"] in _TEAM_BY_ID and r["status_name"] == "pending"), None)
    if row is None:
        _fail(404, "Pending regularization request was not found in your team.")
    base = {"regularization_id": rid, "employee_id": row["employee_id"],
            "employee_name": row["employee_name"], "emp_no": row["employee_number"],
            "apply_date": row["apply_date"]}
    if action == "approve":
        return 200, {"success": True, "message": "Regularization request approved successfully.",
                     "data": {**base, "status": 1, "status_name": "approved"}}
    return 200, {"success": True, "message": "Regularization request rejected successfully.",
                 "data": {**base, "status": 2, "status_name": "rejected",
                          "rejection_reason": body.get("rejection_reason"),
                          "action_by": MANAGER["name"]}}


_LEAVE_DECISION_RE = re.compile(r"^/leave/requests/(\d+)/(approve|reject)$")


def _handle_write(persona, method, route, body):
    if route == "/leave/apply":
        return _w_apply_leave(persona, body)
    if route == "/leave/cancel":
        return _w_cancel_leave(persona, body)
    m = _LEAVE_DECISION_RE.match(route)
    if m:
        return _w_leave_decision(persona, int(m.group(1)), m.group(2), body)
    if route == "/apply/regularization":
        return _w_apply_regularization(persona, body)
    if route in ("/regularization/approve", "/regularization/reject", "/regularization/cancel"):
        return _w_reg_decision(persona, route, body)
    return None


# ════════════════════════════════════════════════════════════════════════════
# The drop-in
# ════════════════════════════════════════════════════════════════════════════

def _deliver(status, body, path, allow_business_error_body, allow_404_body, allow_403_body,
             allow_422_body):
    """Apply erp_client._request's status rules to a (status, body) answer."""
    if status == 401:
        raise erp_client.ErpApiUnauthorized("erp-api returned 401")
    allowed = (200 <= status < 300
               or (allow_business_error_body and status == 400)
               or (allow_404_body and status == 404)
               or (allow_403_body and status == 403)
               or (allow_422_body and status == 422))
    if not allowed:
        raise erp_client.ErpApiUnavailable(f"erp-api returned {status}", status_code=status, body=body)
    return {"http_status": status, "latency_ms": 1.0, "body": body}


async def fake_request(method: str, path: str, bearer_token: str, json_body: dict | None = None,
                       params: dict | None = None, company_id=None,
                       conversation_id: str | None = None,
                       allow_business_error_body: bool = False,
                       allow_404_body: bool = False,
                       allow_403_body: bool = False,
                       allow_422_body: bool = False,
                       timeout_seconds: float | None = None) -> dict:
    """Drop-in for services.erp_client._request. Never touches the network."""
    flags = (allow_business_error_body, allow_404_body, allow_403_body, allow_422_body)
    method = (method or "GET").upper()
    route, merged = _split_path(path, params)
    persona = persona_from_token(bearer_token)
    CALLS.append({"method": method, "path": route, "params": merged, "persona": persona})
    if persona is None:
        return _deliver(401, {"success": False, "message": "Unauthenticated."}, path, *flags)

    if method != "GET":
        WRITES.append({"method": method, "path": path, "json_body": json_body,
                       "params": params, "persona": persona})
        try:
            answer = _handle_write(persona, method, route, json_body)
        except _Reply as r:
            return _deliver(r.status, r.body, path, *flags)
        if answer is None:
            UNKNOWN_PATHS.append(f"{method} {path}")
            raise erp_client.ErpApiUnavailable(
                f"mock_erp: no handler for {method} {path} (write recorded, not sent)",
                status_code=404, body={"message": "Not Found"})
        return _deliver(answer[0], answer[1], path, *flags)

    handler = GET_ROUTES.get(route)
    if handler is None:
        UNKNOWN_PATHS.append(f"{method} {path}")
        raise erp_client.ErpApiUnavailable(f"mock_erp: no handler for {method} {path}",
                                           status_code=404, body={"message": "Not Found"})
    try:
        body = handler(persona, merged)
    except _Reply as r:
        return _deliver(r.status, r.body, path, *flags)
    return _deliver(200, body, path, *flags)


def install(target=None):
    """Patch erp_client._request in place (or via a pytest monkeypatch)."""
    if target is not None:
        target.setattr(erp_client, "_request", fake_request)
    else:
        erp_client._request = fake_request


_TODAY_MODULES = (
    "services.attendance", "services.leave_action_service", "services.my_regularisation_view",
    "services.punch_details", "services.classify_node", "services.hr_graph",
    "services.individual_report", "services.shift_query", "services.date_resolver",
    "services.leave_approval", "services.regularisation_approval",
)
# Both names, wherever either exists: leave_action_service binds
# `_today_in_app_timezone = _today` at import, so pinning `_today` alone left
# the alias - which resolves "tomorrow" - on the real clock. Unnoticed until
# the first run on a day other than TODAY (29 Oct: "tomorrow" became 30 Oct).
_TODAY_HELPER_NAMES = ("_today", "_today_in_app_timezone")


def pin_today(target=None):
    """Pin the app's own 'today' helpers to TODAY (2026-10-28). Code that
    calls datetime.now() directly is not covered - run on/around that date
    or accept the drift. Pass a pytest monkeypatch as `target` to undo on
    teardown."""
    import importlib
    for mod_name in _TODAY_MODULES:
        try:
            mod = importlib.import_module(mod_name)
        except Exception:
            continue
        for attr in _TODAY_HELPER_NAMES:
            if callable(getattr(mod, attr, None)):
                fn = (lambda: TODAY)
                if target is not None:
                    target.setattr(mod, attr, fn)
                else:
                    setattr(mod, attr, fn)


def reset():
    WRITES.clear()
    UNKNOWN_PATHS.clear()
    CALLS.clear()


# ════════════════════════════════════════════════════════════════════════════
# Ground truth for graders
# ════════════════════════════════════════════════════════════════════════════

def _facts_for(persona: str) -> dict:
    p = PERSONAS[persona]
    uid = p["user_id"]
    oct_status = {}
    d = date(2026, 10, 1)
    while d <= date(2026, 10, 31):
        st = _status_on(uid, d)
        oct_status[d.isoformat()] = st if st else ("Not Recorded" if d <= TODAY else "Upcoming")
        d += timedelta(days=1)
    shift = _shift_for(uid)
    own = _own_leaves(persona)
    facts = {
        "name": p["name"], "emp_no": p["emp_no"], "employee_id": uid,
        "designation": p["designation"], "is_manager": p["is_manager"],
        "reporting_manager": p["manager_name"],
        "leave_balance": {LEAVE_TYPE_NAMES[s]: dict(v) for s, v in BALANCES[persona].items()},
        "leave_balance_by_slug": {s: dict(v) for s, v in BALANCES[persona].items()},
        "holidays": [{"name": n, "date": d} for n, d in HOLIDAYS],
        "holiday_count_2026": len(HOLIDAYS),
        "holidays_upcoming": sum(1 for _, d in HOLIDAYS if d > TODAY.isoformat()),
        "upcoming_holidays": [{"name": n, "date": d} for n, d in HOLIDAYS if d > TODAY.isoformat()],
        "next_holiday": next({"name": n, "date": d} for n, d in HOLIDAYS if d > TODAY.isoformat()),
        "shift": {"name": shift["shift_name"], "start": shift["start_time"][:5],
                  "end": shift["end_time"][:5], "weekly_off": list(shift["week_off_day"])},
        "attendance": oct_status,
        "attendance_notable": {k: v for k, v in oct_status.items()
                               if v not in ("Present", "Off", "Upcoming")},
        "my_leaves": [{"id": r["id"], "ref": f"LR-{r['id']}", "type": r["leave_type"],
                       "from": r["from_date"], "to": r["to_date"], "status": r["status_name"],
                       "days": r["total_days"]} for r in _sorted_desc(own)],
        "my_pending_leaves": [f"LR-{r['id']}" for r in own if r["status_name"] == "pending"],
        "my_regularizations": [{"id": r["regularization_id"], "ref": f"REG-{r['regularization_id']}",
                                "date": r["apply_date"], "status": r["status_name"]}
                               for r in REGULARIZATIONS if r["employee_id"] == uid],
        "regularization_policy": {"max_per_payroll_cycle": REGULARIZATION_MAX_PER_CYCLE,
                                  "allowed_back_days": REGULARIZATION_ALLOWED_DAYS,
                                  "payroll_cycle": dict(PAYROLL_CYCLE)},
        # Pending+Approved regularizations dated inside each payroll cycle.
        "regularization_quota_used": {
            "2026-09-21..2026-10-20": sum(1 for r in REGULARIZATIONS if r["employee_id"] == uid
                                          and r["status_name"] in ("pending", "approved")
                                          and "2026-09-21" <= r["apply_date"] <= "2026-10-20"),
            "2026-10-21..2026-11-20": sum(1 for r in REGULARIZATIONS if r["employee_id"] == uid
                                          and r["status_name"] in ("pending", "approved")
                                          and "2026-10-21" <= r["apply_date"] <= "2026-11-20"),
        },
        "today": TODAY.isoformat(),
    }
    if persona == "manager":
        facts["team_members"] = [m["employee_name"] for m in TEAM]
        facts["team_size"] = len(TEAM)
        facts["team_pending_leaves"] = [
            {"id": r["id"], "employee": r["employee_name"], "type": r["leave_type"],
             "from": r["from_date"], "to": r["to_date"], "days": r["total_days"]}
            for r in _team_leaves() if r["status_name"] == "pending"]
        facts["team_pending_regularizations"] = [
            {"id": r["regularization_id"], "employee": r["employee_name"], "date": r["apply_date"]}
            for r in REGULARIZATIONS if r["employee_id"] in _TEAM_BY_ID and r["status_name"] == "pending"]
        facts["team_attendance_today"] = {m["employee_name"]: _status_on(m["employee_id"], TODAY)
                                          for m in TEAM}
    return facts


FACTS: dict = {
    "today": TODAY.isoformat(),
    "holidays": [{"name": n, "date": d} for n, d in HOLIDAYS],
    "holiday_count_2026": len(HOLIDAYS),
    "holidays_upcoming": sum(1 for _, d in HOLIDAYS if d > TODAY.isoformat()),
    "employee": _facts_for("employee"),
    "manager": _facts_for("manager"),
}
