"""services/individual_report.py

Individual Report Status/Explanation (FR-07.3) - lets a MANAGER look up one
named report's leave request, or ask why that report's attendance was marked
a certain way, without leaving chat.

Two intents land here:
  manager_leave_request_lookup    "Show John Doe leave request"
  manager_attendance_explanation  "Why was he marked half-day?"

Strict scope boundary (per the story): viewing only. Nothing here approves,
rejects, overrides or edits anything, and nothing here produces a team-wide
summary - a team-wide pending list is team_leave_query_node's job
(FR-07.1), and approvals are a separate story entirely.

Permission model
----------------
Two gates, in this order, and they answer different questions:

1. Is the caller a manager at all? Cheap, local: the JWT's own role claim
   (dependencies.is_manager_role). Live erp-api tokens carry role_name, so
   a manager normally clears this gate with no network call. A token that
   does NOT say so is not a denial - it means "the token didn't say" - so
   it falls back to erp-api's authoritative is_manager flag, exactly as
   team_leave_query_node already does.

2. Is THIS employee inside the caller's scope? Not ours to answer. Both
   endpoints answer it two ways:
     - a 403 for an employee_id outside the team -> _deny(), AC4 verbatim.
     - search_matched=false for a NAME that matched nobody -> the caller's
       own team roster is offered as selection cards (product decision;
       see the search_matched branch for the disclosure analysis).
   Either way this module never learns whether the named person exists,
   only whether they are in this caller's team - erp-api answers gibberish,
   a typo and a real out-of-team employee identically (verified live).

AC4's denial copy is required verbatim, so DENIAL_MESSAGE is a constant and
is the ONLY thing sent on any denial path. erp-api's own message is never
forwarded: it could name the employee, or differ between "no such person"
and "not yours", either of which would leak exactly what AC4 forbids.

Backing endpoints
-----------------
LEAVE is LIVE: erp_client.get_team_pending_leaves narrowed by employee_id /
employee_name (GET /api/v1/ai/leave/pending/teams — the same endpoint
team_leave_query_node uses unnarrowed). Two consequences worth knowing:

  * It returns PENDING requests only. "Show John's leave request" cannot
    surface an already-approved or rejected one; the manager is told they
    have no PENDING requests, which is true but narrower than FR-07.3's
    "an individual report's request" reads.
  * There is no 403 on this path. A name matching nobody in the caller's
    team returns search_matched=false plus the full team roster, which is
    OFFERED to the manager as selection cards - see the search_matched
    check below for why that discloses no more than the denial did.

ATTENDANCE is LIVE too: erp_client.get_attendance_punch_details (GET
/api/v1/ai/attendance/punch-details?date=&employee_id=). The fixtures that
stood in for it are gone. Two properties of that endpoint shape this file:

  * It returns NO "employee" block, so the subject's name is carried from
    the candidate row that resolved the employee_id - see
    resolved_employee_row below. Without it every answer would open "This
    employee ...".
  * It reports the recorded status, its remark and the punch evidence, but
    NO policy rule and NO explanation factors (the fixtures invented both).
    So this is an attendance RECORD, shown in full; the renderer never
    manufactures a reason for the ruling.

  A day with nothing on file is a 200 with attendance null and punch_status
  "no_records" - a real answer, not a failure, and never AC4's denial.

AC2 Designation: erp-api's selection-card rows carry it as `designation`,
its leave rows as `employee_designation`. _normalise_employee collapses
both to `employee_designation` on every emitted row and _render_selection_
prompt prints it, so the SSE `employee_selection` cards, the done payload
and the plain-text list all carry Employee Name + ID + Designation. A row
that genuinely arrives without one simply omits the field (never "None").
"""
import difflib
import logging
import os
import re
from datetime import datetime
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

import services.access_notice as access_notice
import services.ai_service as ai_service
import services.erp_client as erp_client
import services.permission_service as permission_service
import services.leave_slot_service as leave_slot_service
import services.leave_action_service as leave_action_service
import services.date_resolver as date_resolver
import services.nlp_service as nlp_service

logger = logging.getLogger(__name__)

LEAVE_REQUEST_INTENT = "manager_leave_request_lookup"
ATTENDANCE_EXPLANATION_INTENT = "manager_attendance_explanation"

# Tri-state for the manager gate, carried on the graph state. A plain None
# cannot express "erp-api was unreachable" — it already means "the gate has
# not run", and collapsing the two would let an outage read as a clean
# not-a-manager (or, worse, silently skip the gate). A string keeps the
# state JSON-serialisable for LangGraph.
MANAGER_UNKNOWN = "unknown"

# AC4 - required verbatim. Do not reword, and do not append a reason,
# suggestion, or employee name to it.
DENIAL_MESSAGE = "I cannot retrieve attendance or leave information for this employee."

# Deliberately NOT the AC4 denial: this is "your role can't use this feature",
# not "that employee is off-limits to you", and conflating them would tell a
# non-manager that the named employee is out of their scope - a fact they
# have no business being told either way.
NOT_A_MANAGER_MESSAGE = (
    "Looking up an individual team member's leave request or attendance "
    "explanation is available to managers only - this isn't something I can "
    "pull up for your role."
)

_ERP_TIMEOUT_MESSAGE = "I couldn't reach the HR system in time - please try again in a moment."
_ERP_UNAVAILABLE_MESSAGE = "I'm unable to reach the HR system right now - please try again shortly."

# Ordinal replies to a selection prompt ("the second one", "2", "first").
# Split into two tiers because "the second one" contains BOTH an ordinal
# ("second") and a cardinal ("one"), and only the ordinal carries the
# meaning — scanning one flat dict makes the answer depend on dict order,
# which silently picked the wrong card.
_ORDINAL_WORDS = {
    "first": 0, "1st": 0,
    "second": 1, "2nd": 1,
    "third": 2, "3rd": 2,
    "fourth": 3, "4th": 3,
    "fifth": 4, "5th": 4,
    "sixth": 5, "6th": 5,
    "seventh": 6, "7th": 6,
    "eighth": 7, "8th": 7,
    "ninth": 8, "9th": 8,
    "tenth": 9, "10th": 9,
}
_CARDINAL_WORDS = {"one": 0, "two": 1, "three": 2, "four": 3, "five": 4,
                   "six": 5, "seven": 6, "eight": 7, "nine": 8, "ten": 9}


def _today_in_app_timezone():
    """AC3's "Today". Same configured-timezone notion of today the rest of
    the app uses (hr_graph._today_in_app_timezone, quota_service._get_timezone)
    rather than a server-local date.today() that could disagree with the
    company's actual day near midnight."""
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


# -- Rendering ---------------------------------------------------------------

def _normalise_employee(employee: dict) -> dict:
    """erp-api names the same employee two ways depending on the endpoint:
    /leave/pending/teams returns {name, emp_no}, while the attendance
    lookup returns {employee_id, employee_name, employee_number, ...}.
    Collapse both to the employee_* spelling so the SSE payload, the
    remembered pronoun subject, and the renderers all read one shape.

    Designation is the same story: a selection card carries it as
    `designation`, a leave row as `employee_designation` — surface the one
    `employee_designation` key so every emitted row (select_employee cards
    included) carries AC2's third field under a single name. Only added
    when erp-api actually sent a value; never written as an empty/"None"."""
    if not employee:
        return {}
    normalised = dict(employee)
    if not normalised.get("employee_name") and employee.get("name"):
        normalised["employee_name"] = employee["name"]
    if not normalised.get("employee_number") and employee.get("emp_no"):
        normalised["employee_number"] = employee["emp_no"]
    if not normalised.get("employee_designation"):
        designation = _designation_of(employee)
        if designation:
            normalised["employee_designation"] = designation
    return normalised


def _designation_of(row: dict) -> Optional[str]:
    """erp-api spells this two ways: leave rows carry employee_designation,
    while a selection card would carry designation. Read both so the field
    renders wherever it turns up, and neither spelling has to be guessed at
    a call site."""
    if not row:
        return None
    value = row.get("employee_designation") or row.get("designation")
    return str(value).strip() or None if value else None


def _remembered_leave(leave: dict, fallback_employee_id=None) -> dict:
    """The subset of a pending-leave row that a later action needs to
    identify and describe it (FR-07.4's confirmation card). Explicitly a
    projection, not the raw row: what is remembered between turns should be
    the smallest thing that still names one request unambiguously."""
    return {
        "id": leave.get("id"),
        "employee_id": leave.get("employee_id") or fallback_employee_id,
        "employee_name": leave.get("employee_name"),
        "employee_number": leave.get("employee_number"),
        "employee_designation": _designation_of(leave),
        "leave_type": leave.get("leave_type"),
        "session_type": leave.get("session_type"),
        "from_date": leave.get("from_date"),
        "to_date": leave.get("to_date"),
        "leave_count": leave.get("leave_count"),
        "reason": leave.get("reason"),
        "applied_date": leave.get("applied_date"),
    }


def _bare_name_target(query: str) -> Optional[str]:
    """The message read as nothing but a person's name, or None.

    The same test classify_node routes a bare-name continuation on, reused
    here rather than restated, so the two can never disagree about what
    counts as a name - "yes", a bare date, a request number and an HR topic
    word ("payroll") are all excluded there and stay excluded here.

    Imported at call time, not at module load: classify_node imports THIS
    module, so the reverse import has to stay out of the import graph. Same
    reason, same shape, as leave_approval._looks_like_a_target_reply.
    """
    text = (query or "").strip()
    if not text:
        return None
    from services.classify_node import _is_bare_person_fragment
    return text if _is_bare_person_fragment(text, False) else None


#: The done intent of the "did you mean this person?" question (UAT UV-04).
GUESSED_NAME_CHECK_INTENT = "guessed_name_check"


def _ask_which_meaning(word: str, employee: dict, finish) -> dict:
    """"Search for Phil salt's employee details, or general details about
    salt?" - asked instead of opening a team member's record on a one-word
    guess. The two replies are read back by classify_node
    (guessed_name_choice)."""
    name = employee.get("employee_name") or employee.get("name") or "that team member"
    options = [employee_details_option(name), general_details_option(word), "Something else"]
    message = (f"Did you mean **{name}** from your team, or would you like to know what "
               f"\"{word}\" means? Or is it something else?")
    return finish(message, finish_intent=GUESSED_NAME_CHECK_INTENT,
                  extra_data={"options": options})


def employee_details_option(name: str) -> str:
    return f"Search {name}'s employee details"


def general_details_option(word: str) -> str:
    return f"General details about {word}"


_EMPLOYEE_DETAILS_RE = re.compile(r"^\s*search\s+(.+?)'s\s+employee\s+details\W*$", re.IGNORECASE)
_GENERAL_DETAILS_RE = re.compile(r"^\s*general\s+details\s+about\s+(.+?)\W*$", re.IGNORECASE)


def guessed_name_choice(query: str):
    """("employee", name) / ("general", word) for a reply to that question
    (button or typed), else None."""
    m = _EMPLOYEE_DETAILS_RE.match(query or "")
    if m:
        return "employee", m.group(1).strip()
    m = _GENERAL_DETAILS_RE.match(query or "")
    if m:
        return "general", m.group(1).strip()
    return None


def _render_one_leave(leave: dict, with_employee: bool = False) -> str:
    """One pending request as an indented block. Every field is rendered
    only if erp-api actually returned it — nothing is inferred."""
    from_date = leave.get("from_date")
    to_date = leave.get("to_date")
    span = ""
    if from_date and to_date:
        span = from_date if from_date == to_date else f"{from_date} to {to_date}"
    elif from_date:
        span = from_date

    headline_bits = [b for b in (leave.get("leave_type"), span) if b]
    if with_employee and leave.get("employee_name"):
        who = f"**{leave['employee_name']}**"
        role = _designation_of(leave)
        if role:
            who += f" ({role})"
        headline_bits.insert(0, who)
    lines = ["- " + " - ".join(headline_bits) if headline_bits else "- Leave request"]

    detail = []
    count = leave.get("leave_count")
    if count:
        detail.append(f"{count} day(s)")
    session_type = leave.get("session_type")
    if session_type:
        detail.append(session_type)
    status_name = leave.get("status_name")
    if status_name:
        detail.append(f"status: {status_name}")
    if detail:
        lines.append(f"  {', '.join(detail)}")

    reason = leave.get("reason")
    if reason:
        lines.append(f"  Reason: {reason}")
    applied_date = leave.get("applied_date")
    if applied_date:
        lines.append(f"  Applied on: {applied_date}")
    return "\n".join(lines)


def _render_leave_requests(employee_label: str, leaves: list,
                           per_row_employee: bool = False,
                           type_label: Optional[str] = None) -> str:
    """erp-api's /leave/pending/teams returns a LIST - all of one named
    employee's pending requests, or the whole team's when unnarrowed - so
    the reply is a list too. Sorted by start date so the soonest request
    reads first; erp-api's own order is by id (creation order), which is
    not what a manager scanning "what's waiting on me" wants.

    per_row_employee prefixes each row with whose request it is. Required
    for the team-wide answer, where rows span several people and an
    unlabelled list would read as though they were all one person's."""
    ordered = sorted(leaves, key=lambda lv: lv.get("from_date") or "")
    count = len(ordered)
    # A person's name is bolded because it is the subject of the answer. The
    # team-wide header is not: there the bolded names are the per-row ones,
    # and bolding "Your team" too would compete with them.
    subject = employee_label if per_row_employee else f"**{employee_label}**"
    # erp-api now returns employee_designation on each row. For a single
    # subject it belongs once, next to the name; for a team-wide list the
    # rows carry their own (see _render_one_leave).
    if not per_row_employee:
        role = _designation_of(ordered[0]) if ordered else None
        if role:
            subject = f"{subject} ({role})"
    # A narrowed answer says what it was narrowed TO: "5 pending casual leave
    # requests", not "5 pending leave requests" for a person who has seven.
    kind = f"{type_label} request" if type_label else "leave request"
    header = (f"{subject} has {count} pending {kind}"
              f"{'s' if count != 1 else ''}:")
    return "\n".join(
        [header] + [_render_one_leave(lv, with_employee=per_row_employee) for lv in ordered]
    )


def _punch_clock(stamp: Optional[str]) -> str:
    """"2026-08-11 09:00:00" -> "09:00". The date is already stated in the
    headline, so repeating it on every punch line is noise; anything that
    doesn't split as expected is passed through untouched rather than
    reformatted into something that might be wrong."""
    if not stamp:
        return "-"
    parts = str(stamp).split(" ")
    clock = parts[1] if len(parts) == 2 else str(stamp)
    return clock[:5] if len(clock) >= 5 and clock[2] == ":" else clock


# How far back a stated attendance date may plausibly reach. Anything older
# is treated as an extraction artefact rather than a real request - the
# failure this guards is the LLM answering "july 13" with 2023-07-13 while
# today is 2026-09-01, which reads as a valid date and silently reports on
# the wrong day three years back.
_MAX_ATTENDANCE_LOOKBACK_DAYS = 550


def _resolve_attendance_date(query: str, llm_date: Optional[str], today) -> str:
    """AC3's date, resolved deterministically wherever possible.

    Precedence, and why:
      1. An outright-stated calendar date ("13 July", "2026-07-13"), parsed
         by date_resolver. The LLM gets the YEAR wrong on these - verified:
         "july 13" came back 2023-07-13 with today at 2026-09-01 - so its
         answer is not trusted when the text states the date plainly.
      2. A relative phrase ("yesterday", "last Monday"), past-tolerant.
         Same deterministic tier team_attendance_summary_node already uses.
      3. The extraction LLM's date, but only if plausible: not in the
         future (an attendance record cannot exist for a day that has not
         happened) and not absurdly far back.
      4. Today.
    """
    explicit = date_resolver.resolve_explicit_calendar_date(query, today)
    if explicit:
        if llm_date and llm_date != explicit:
            logger.info("[IndividualReport] date %r stated in query - using it over extracted %r",
                        explicit, llm_date)
        return explicit

    # A named weekday, read backwards. Must come BEFORE the general relative
    # resolver, which is forward-only: on a Wednesday it reads "this Monday"
    # as next week's, and its allow_past flag cannot help because that answer
    # is in the future, so the guard never fires.
    weekday = date_resolver.resolve_past_weekday_phrase(query, today)
    if weekday and weekday.get("from_date"):
        return weekday["from_date"]

    relative = date_resolver.resolve_relative_date_phrase(query, today, allow_past=True)
    if relative and relative.get("from_date"):
        return relative["from_date"]

    if llm_date:
        try:
            parsed = datetime.strptime(llm_date, "%Y-%m-%d").date()
        except ValueError:
            logger.warning("[IndividualReport] unparseable extracted date %r - using today", llm_date)
            return today.isoformat()
        if parsed > today:
            logger.info("[IndividualReport] extracted date %r is in the future - using today", llm_date)
        elif (today - parsed).days > _MAX_ATTENDANCE_LOOKBACK_DAYS:
            logger.warning("[IndividualReport] extracted date %r is %d days back - "
                           "treating as an extraction error and using today",
                           llm_date, (today - parsed).days)
        else:
            return llm_date

    return today.isoformat()


async def _fetch_status_record(bearer_token, company_id, conversation_id,
                               employee_id, on_date: str) -> Optional[dict]:
    """The one {date, day, status} row for `on_date`, or None when it can't
    be had. Never raises and never denies: the caller has already cleared
    erp-api's scope check on punch-details, so anything that goes wrong here
    costs the status word, not the answer."""
    if not on_date:
        return None
    try:
        result = await erp_client.get_attendance_status_range(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            from_date=on_date, to_date=on_date, employee_id=employee_id,
        )
    except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable) as e:
        logger.warning("[IndividualReport] status lookup unavailable (%s) - "
                       "rendering the punch record without it", type(e).__name__)
        return None

    body = result.get("body") or {}
    if result.get("http_status") == 403 or not body.get("success", True):
        logger.info("[IndividualReport] status lookup returned %s - continuing without it",
                    result.get("http_status"))
        return None

    records = (body.get("data") or {}).get("records") or []
    for record in records:
        if record.get("date") == on_date:
            return record
    # A single-day query answers with exactly one row; take it even if the
    # echoed date is formatted differently than what was asked for.
    return records[0] if len(records) == 1 else None


def _normalise_status(status: Optional[str]) -> str:
    """Fold a status to a comparable form: "Half Day", "half-day" and
    "half day" are the same claim."""
    if not status:
        return ""
    return re.sub(r"[\s_-]+", " ", str(status).strip().lower())


def _status_contradicts(asserted: Optional[str], actual: Optional[str]) -> bool:
    """True when the manager's question assumed one status and the record
    shows another. Only ever True when BOTH are known - an unknown actual
    status is a gap in the record, not a contradiction of the question."""
    a, b = _normalise_status(asserted), _normalise_status(actual)
    if not a or not b:
        return False
    return a != b and a not in b and b not in a


def _lead_in(subject: str, asserted: Optional[str], actual: Optional[str], when: str) -> str:
    """Opening sentence of an attendance answer.

    A manager who asks "why was X marked half-day" when the record says
    something else has a false premise, and answering "X was marked Not
    Recorded" reads as though it answered the question asked. Saying the
    record disagrees is the honest lead, and it is usually the actual
    answer they needed."""
    if _status_contradicts(asserted, actual):
        return (f"**{subject}** wasn't marked {_normalise_status(asserted)} on {when} - "
                f"the record shows **{actual}**.")
    return f"**{subject}** was marked **{actual}** on {when}."


def _subject_label(employee: dict) -> str:
    """How to name the subject in a sentence. punch-details returns no
    employee block, so a lookup made by explicit employee_id has no name
    anywhere in the exchange - falling through to "This employee" there
    reads like the node lost track of who was asked about, when in fact the
    manager named them by id. Echo the identifier they used instead."""
    name = employee.get("employee_name")
    if name:
        return name
    number = employee.get("employee_number")
    if number:
        return f"Employee {number}"
    employee_id = employee.get("employee_id")
    if employee_id:
        return f"Employee {employee_id}"
    return "This employee"


def _render_attendance_explanation(employee: dict, data: dict, resolved_date: str,
                                   status_record: Optional[dict] = None,
                                   asserted_status: Optional[str] = None) -> str:
    """AC3 - renders what /ai/attendance/punch-details recorded for one
    employee on one day: the recorded status and its remark, the applicable
    shift, every punch pair, and the logged hours.

    What this deliberately does NOT do is explain the ruling. The endpoint
    returns no policy rule and no explanation factors (the fixtures it
    replaced invented both), so there is nothing to attribute a reason to.
    Stating the recorded status alongside the punch evidence lets a manager
    see WHY for themselves; manufacturing a rule here would be the node
    asserting company policy it has never been told.

    status_record is the {date, day, status} row from /ai/attendance/query.
    It supplies the only human-readable status in the system, so it leads
    the answer when present; punch-details' code and remark then follow as
    supporting detail rather than standing in for the status.

    Every field is rendered only when erp-api actually returned it."""
    name = _subject_label(employee)
    attendance = data.get("attendance") or {}

    # attendance.attendance is a short code ("SHL", "O", "P"); the remark is
    # the human-readable half. Neither is mapped to a friendlier vocabulary
    # here - no code table has been published, and guessing one would put
    # invented words on an official record.
    code = attendance.get("attendance")
    remark = attendance.get("attendance_remark")

    status = (status_record or {}).get("status")
    day = (status_record or {}).get("day")
    when = f"{day}, {resolved_date}" if day else resolved_date

    if status:
        lines = [_lead_in(name, asserted_status, status, when)]
        # The internal code/remark is corroborating detail once the status
        # word is known - shown, but no longer standing in for it.
        if remark and code:
            lines.append(f"- Recorded as: {remark} ({code})")
        elif remark or code:
            lines.append(f"- Recorded as: {remark or code}")
    elif remark and code:
        lines = [f"**{name}**'s attendance on {when} is recorded as **{remark}** ({code})."]
    elif remark or code:
        lines = [f"**{name}**'s attendance on {when} is recorded as **{remark or code}**."]
    else:
        lines = [f"**{name}** has no attendance status recorded for {when}."]

    shift = data.get("shift") or {}
    shift_name = shift.get("name")
    start_time = shift.get("start_time")
    end_time = shift.get("end_time")
    if shift_name and start_time and end_time:
        lines.append(f"- Shift: {shift_name} ({start_time}-{end_time})")
    elif shift_name:
        lines.append(f"- Shift: {shift_name}")

    punches = data.get("punches") or []
    if punches:
        lines.append(f"- Punches ({data.get('punch_count', len(punches))}):")
        for punch in punches:
            entry = (f"    {punch.get('punch_number')}. "
                     f"in {_punch_clock(punch.get('check_in'))}, "
                     f"out {_punch_clock(punch.get('check_out'))}")
            if not punch.get("complete"):
                missing = punch.get("missing")
                entry += f"  (incomplete - missing {missing.replace('_', ' ')})" if missing else "  (incomplete)"
            lines.append(entry)
    else:
        lines.append("- Punches: none recorded")

    work_hours = data.get("work_hours") or {}
    if work_hours.get("available") and work_hours.get("value"):
        lines.append(f"- Hours logged: {work_hours['value']}")
    elif work_hours.get("reason"):
        lines.append(f"- Hours logged: not available ({work_hours['reason']})")

    # An incomplete punch set is the single most common reason a day looks
    # wrong to the employee, so it is called out rather than left for the
    # manager to spot by scanning the pairs above.
    punch_status = data.get("punch_status")
    if punch_status and punch_status != "complete":
        lines.append(f"- Punch record is **{punch_status.replace('_', ' ')}**.")
    if attendance.get("is_regularized"):
        lines.append("- This day has been regularized.")
    reason = attendance.get("reason")
    if reason:
        lines.append(f"- Reason on record: {reason}")

    # The shift window can start on the previous calendar day for a night
    # shift, in which case erp-api reports which day the punches belong to.
    logical = data.get("logical_shift_date")
    if logical and logical != resolved_date:
        lines.append(f"- These punches belong to the shift day {logical}.")

    return "\n".join(lines)


# Returned as state["route_to"] when a GUESS that the message named an
# employee is disproved by the directory. hr_graph._route_after_individual
# _report reads it and hands the turn back to the non-HR lane instead of
# ending it here. A sentinel rather than a node name so this module does not
# have to know what the graph calls that lane.
GUESSED_SUBJECT_NOT_AN_EMPLOYEE = "guessed_subject_not_an_employee"


def _render_selection_prompt(candidates: list, unmatched_term: bool = False) -> str:
    """AC2 - each option must carry Employee Name, Employee ID and
    Designation. The structured cards ride the SSE `employee_selection`
    event for the UI to render as chips; this text is the accessible
    equivalent for a plain-text client, carrying the same fields.

    Designation is read via _designation_of (erp-api spells it `designation`
    on these rows, `employee_designation` on leave rows); callers pass rows
    already run through _normalise_employee, so the structured payload
    carries it as `employee_designation`. A row without one omits it here
    rather than printing "None".
    """
    lines = [
        # Two different situations, two different lead-ins. "More than one
        # matches" would be a lie when nothing matched at all, and the
        # unmatched wording mirrors what /leave/pending/teams itself says.
        "No employee matched that name. Please select an employee from your team:"
        if unmatched_term else
        "More than one team member matches that name. Which one did you mean?"
    ]
    for idx, candidate in enumerate(candidates, start=1):
        parts = [f"ID: {candidate.get('employee_number') or candidate.get('employee_id')}"]
        designation = _designation_of(candidate)
        if designation:
            parts.append(str(designation))
        lines.append(f"{idx}. {candidate.get('employee_name')} ({', '.join(parts)})")
    return "\n".join(lines)


# -- Selection matching ------------------------------------------------------

def _match_selection(query: str, candidates: list):
    """Resolve a reply to AC2's selection prompt against the cards that were
    offered. Returns the chosen candidate or None.

    Only ever matches within `candidates` - a reply naming somebody who was
    not offered is not a selection, and falls through to a fresh lookup so
    that person gets their own permission check rather than inheriting this
    prompt's.
    """
    text = query.strip().lower()
    if not text or not candidates:
        return None

    for candidate in candidates:
        number = str(candidate.get("employee_number") or "").lower()
        if number and number in text:
            return candidate
        if str(candidate.get("employee_id")) == text:
            return candidate

    # Full name, then a distinguishing name part. A part shared by several
    # candidates ("john" when both are Johns) resolves nothing - that is the
    # ambiguity we are trying to clear, not a tiebreak to guess at.
    name_matches = [
        c for c in candidates
        if (c.get("employee_name") or "").lower() in text
    ]
    if len(name_matches) == 1:
        return name_matches[0]

    token_matches = []
    for candidate in candidates:
        parts = [p for p in re.split(r"\s+", (candidate.get("employee_name") or "").lower()) if p]
        if any(re.search(r"\b" + re.escape(part) + r"\b", text) for part in parts):
            token_matches.append(candidate)
    if len(token_matches) == 1:
        return token_matches[0]

    # Bare ordinal ("2", "the second one"). Checked last so a name always
    # wins over a stray digit elsewhere in the sentence. Ordinals outrank
    # cardinals so "the second one" resolves on "second", not "one"; within
    # a tier the longest match wins, keeping the result independent of dict
    # iteration order.
    for table in (_ORDINAL_WORDS, _CARDINAL_WORDS):
        hits = [
            (word, index) for word, index in table.items()
            if re.search(r"\b" + re.escape(word) + r"\b", text)
        ]
        if not hits:
            continue
        word, index = max(hits, key=lambda hit: len(hit[0]))
        if index < len(candidates):
            return candidates[index]
        # An explicit position that does not exist on this shortlist. Return
        # nothing so the cards are re-offered. Filtering out-of-range words
        # BEFORE picking (the previous behaviour) let "the fifth one" fall
        # through to the cardinal "one" and silently answer about employee
        # #1 — the wrong person, with no sign anything had gone wrong.
        logger.info("[IndividualReport] selection word %r is position %d of %d - re-offering",
                    word, index + 1, len(candidates))
        return None

    if text.isdigit():
        index = int(text) - 1
        if 0 <= index < len(candidates):
            return candidates[index]

    return None


def _resolve_from_roster(term: str, employees: list) -> list:
    """Narrow the caller's own team roster by a search term erp-api could
    not match itself.

    erp-api's ?employee_name= search matches the NAME field only, so an
    employee NUMBER ("geo6") comes back search_matched=false even when that
    person is on the team - the roster it attaches on a no-match contains
    them, listed under employee_name "A Emp". Without this, "leave request
    of geo6" is denied for a report the manager plainly owns.

    Scope-bounded by construction: the roster IS the caller's permitted set,
    so this can only ever resolve to somebody already inside scope. A term
    matching nobody in it still falls through to AC4's denial, so an
    out-of-scope name behaves exactly as before.
    """
    if not term or not employees:
        return []
    needle = term.strip().lower()
    if not needle:
        return []

    # employee_number is an exact identifier, matched exactly and never as a
    # substring - otherwise "geo1" would also pull in "geo11" and turn a
    # precise reference into an ambiguous one.
    exact_number = [
        e for e in employees
        if str(e.get("employee_number") or "").strip().lower() == needle
    ]
    if exact_number:
        return exact_number

    # Fall back to a name match in case erp-api's own search is stricter
    # An EXACT full name wins outright, before anything wider is tried.
    #
    # On a roster holding both "Ayush" and "Ayush Chandra", typing "Ayush"
    # used to fall to the substring tier below and come back with all three
    # Ayushes - so the manager was asked to choose between people, one of
    # whom they had just named in full. A name that IS somebody's whole name
    # is not ambiguous, whoever else happens to contain it.
    #
    # Only when exactly one person matches: two colleagues genuinely sharing
    # a full name ARE ambiguous, and still get the selection card.
    exact_name = [
        e for e in employees
        if _squash_name(e.get("employee_name")) == _squash_name(needle)
    ]
    if len(exact_name) == 1:
        return exact_name

    # Fall back to a name match in case erp-api's own search is stricter
    # than ours (e.g. it anchors, and the manager typed a middle word).
    contains = [
        e for e in employees
        if needle in str(e.get("employee_name") or "").strip().lower()
    ]
    if contains:
        return contains

    return _nearest_roster_matches(needle, employees)


def _squash_name(value: str) -> str:
    """A name with every space, dot and hyphen removed - "A Khan Test" ->
    "akhantest". Spacing is the most common thing a manager gets wrong and
    the least meaningful difference between two spellings of one name."""
    return re.sub(r"[^a-z0-9]", "", str(value or "").lower())


#: How alike two names have to read before one is offered for the other.
#:
#: Measured against a real roster rather than guessed: genuine misspellings
#: score 0.75-0.94 ("kahn" 0.75, "ayus jio" 0.93, "chandr" 0.92), while the
#: closest WRONG person tops out at 0.67 ("akhna" against "A Khan Test" is
#: 0.67; "chandr" against it, 0.60). 0.72 sits in the empty gap between those
#: two bands.
#:
#: Deliberately on the strict side of that gap, because a term this tier
#: cannot place no longer dead-ends: the caller is shown their team to pick
#: from. Guessing wrong costs more than asking.
_NAME_SIMILARITY = 0.72


def _nearest_roster_matches(needle: str, employees: list) -> list:
    """The roster entries whose name is near enough to `needle` to be what
    the manager meant. Empty when nothing is close.

    Live report: "approve akhan" for an employee called "A Khan Test" was
    refused with "Pending leave request was not found in your team." erp-api
    matches the name field only and exactly, and the substring tier above
    cannot help either, because "akhan" is not a substring of "a khan test" -
    the space is in the way.

    Three tiers, widest evidence first, each returning EVERY row it matched
    rather than a best guess: two plausible people is a question for the
    manager (the selection card), never a coin toss.
    """
    # A term carrying a digit is an IDENTIFIER, not a name, and identifiers
    # resolve exactly or not at all - the same rule the employee_number tier
    # above states ("geo1" must not pull in "geo11"). Without this, "geo99"
    # scored 0.75 against the name token "Geo" and was offered as "B Geo":
    # a code for a person who does not exist, answered with a different
    # person who does.
    if any(character.isdigit() for character in needle):
        # ...with one exception: a whole NAME with digits stuck on the end.
        # "rudraveer1111" is Rudraveer with noise after it, and refusing it
        # sent the turn to the chat model, which answered about Rudraveer
        # anyway - correctly, but with no intent and no card behind it.
        #
        # Only an EXACT full-name match counts here, never a token or a
        # similarity score. That is what keeps the identifier rule intact:
        # "geo99" reduces to "geo", which is a token of "B Geo" but not that
        # person's whole name, so it still resolves to nobody.
        stem = _squash_name(re.sub(r"\d+$", "", needle))
        if len(stem) >= 4:
            exact = [e for e in employees
                     if _squash_name(e.get("employee_name")) == stem]
            if len(exact) == 1:
                return exact
        return []

    squashed = _squash_name(needle)
    if len(squashed) < 3:
        # Two characters match far too much to be evidence of anything.
        return []

    # 1. Spacing/punctuation only - "akhan" -> "akhantest", "ayushjio" ->
    #    "ayushjio". This is the reported case and by far the most common.
    squeezed = [e for e in employees
                if squashed in _squash_name(e.get("employee_name"))]
    if squeezed:
        return squeezed

    # 2. Every word typed is the start of a word in the name, in any order -
    #    "a kh" for "A Khan Test", "test a" for the same.
    typed = [t for t in re.split(r"\s+", needle.strip()) if t]
    if typed:
        prefixed = []
        for employee in employees:
            parts = [p for p in re.split(r"\s+", str(employee.get("employee_name") or "").lower()) if p]
            if all(any(part.startswith(word) for part in parts) for word in typed):
                prefixed.append(employee)
        if prefixed:
            return prefixed

    # 3. Misspellings - a transposition or a dropped letter. Compared on the
    #    squashed forms so spacing cannot dominate the score, against the
    #    whole name and against each of its words ("akhna" should reach
    #    "Khan" without having to resemble "A Khan Test" in full).
    near = []
    for employee in employees:
        name = str(employee.get("employee_name") or "")
        forms = [_squash_name(name)]
        forms += [_squash_name(p) for p in re.split(r"\s+", name) if p]
        if any(form and difflib.SequenceMatcher(None, squashed, form).ratio() >= _NAME_SIMILARITY
               for form in forms):
            near.append(employee)
    return near


def _normalise_name_for_match(value: str) -> str:
    """Casefolded, punctuation-stripped, whitespace-collapsed - so "Ayush
    Jio", "ayush  jio" and "Ayush-Jio" all compare equal."""
    text = (value or "").lower().replace("’", "'").replace("‘", "'")
    text = re.sub(r"[^a-z0-9]+", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def _shares_a_name_word(term: str, candidates: list) -> bool:
    """True when some offered employee's name or number shares a word (or a
    4+ letter start of one) with what was typed - a real partial match, not
    erp-api's fuzzy similarity.

    Four letters, not three: HA-932 D-02, a manager's "meh" is the start of
    "Mehta" and was answered with Rahul Mehta's leave card. A guess that
    short is not evidence of anyone; the whole word still matches ("raj")."""
    words = [w for w in re.split(r"[\s,]+", (term or "").lower()) if len(w) >= 2]
    for c in candidates:
        tokens = re.split(r"\s+", f"{c.get('employee_name') or ''} {c.get('employee_number') or ''}".lower())
        for w in words:
            for t in tokens:
                if t and (t == w or (len(w) >= 4 and (t.startswith(w) or w.startswith(t)) and len(t) >= 4)):
                    return True
    return False


def _exact_name_matches(term: str, candidates: list) -> list:
    """The candidates whose full name IS `term`, not merely contains it.

    erp-api's ?employee_name= search matches on any name token, so searching
    "ayush jio" comes back with Ayush Chandra alongside Ayush Jio and the
    manager is asked to disambiguate a name they typed in full. An exact
    full-name match is not ambiguous, so it is resolved rather than offered.

    Returns every exact match, not the first: two people genuinely called
    "Ayush Jio" ARE ambiguous, and the caller keeps the selection card for
    that case rather than silently getting whichever row sorted first.

    The employee NUMBER is checked the same way for the same reason - it is
    an exact identifier, and a manager who typed one has already been as
    specific as it is possible to be.
    """
    needle = _normalise_name_for_match(term)
    if not needle or not candidates:
        return []

    by_number = [
        c for c in candidates
        if _normalise_name_for_match(str(c.get("employee_number") or "")) == needle
    ]
    if by_number:
        return by_number

    return [
        c for c in candidates
        if _normalise_name_for_match(c.get("employee_name")) == needle
    ]


#: "all", "everyone", "show all of them" - the whole list rather than one of
#: it. Anchored, so "all" buried in a longer sentence is left to the normal
#: classifier rather than hijacking the turn.
_ASKS_FOR_ALL = re.compile(
    r"^(?:please\s+|can\s+you\s+|could\s+you\s+)?(?:show\s+|list\s+|give\s+me\s+|see\s+)?"
    r"(?:me\s+)?(?:all|everyone|everybody|every\s*one|all\s+of\s+them|"
    r"all\s+(?:the\s+)?(?:employees|members|team\s+members|of\s+them))"
    r"\s*[.!]?$",
    re.IGNORECASE)

#: Where "all" goes, by what was being asked when the list was offered.
_TEAM_VIEW_FOR_SELECTION = {
    LEAVE_REQUEST_INTENT: "HRMS_TEAM_LEAVE_QUERY",
    ATTENDANCE_EXPLANATION_INTENT: "HRMS_TEAM_ATTENDANCE_QUERY",
}


def resolve_pending_selection_intent(company_id, conversation_id: str, query: str):
    """The intent to route this turn to when `query` is a reply picking one
    of the employee cards this conversation is waiting on — otherwise None.

    classify_node's single entry point into this feature's state, so the
    state read and the matching rule stay owned here rather than being
    reassembled at the call site.

    Returns None (fall through to normal classification) both when nothing
    is pending AND when a reply doesn't match any offered card: a manager
    who changes the subject instead of picking must be answered normally,
    and a reply naming someone who was never offered must get their own
    permission check rather than inherit this prompt's.
    """
    state = leave_slot_service.get_report_state(company_id, conversation_id) or {}
    if state.get("step") != "awaiting_employee_selection":
        return None

    # "all" / "everyone" - not a pick from the list, but a perfectly clear
    # answer to it: show me all of them. It routes to the TEAM view of
    # whatever was being asked, which is the only place that answers for
    # more than one person.
    #
    # Reported: with the roster on screen the manager typed "all" and got a
    # grey bubble reading "You have 2 pending leave request(s): 1. Rudraveer
    # ... 2. Rudraveer ..." - written by the chat model, with no intent and
    # no card, and phrased as though those requests were the manager's own.
    # The reply matched no candidate, so the turn fell through to general
    # classification.
    if _ASKS_FOR_ALL.match((query or "").strip()):
        pending_intent = state.get("intent") or LEAVE_REQUEST_INTENT
        # The shortlist is answered and must not capture the next turn: this
        # turn is leaving the feature that armed it. Cleared here because
        # the node it routes to (team_leave_query_node) owns no report state
        # and has no reason to know this one exists.
        leave_slot_service.clear_report_state(company_id, conversation_id)
        return _TEAM_VIEW_FOR_SELECTION.get(pending_intent, "HRMS_TEAM_LEAVE_QUERY")

    if not _match_selection(query, state.get("candidates") or []):
        return None
    return state.get("intent") or LEAVE_REQUEST_INTENT


# -- Node --------------------------------------------------------------------

async def individual_report_node(state: dict, writer: StreamWriter) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    query = state.get("query", "")
    intent = state.get("intent") or LEAVE_REQUEST_INTENT
    usage_events = list(state.get("usage_events", []))

    def _finish(message: str, finish_intent: str = None, extra_data: dict = None) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({"type": "done", "intent": finish_intent or intent, "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    def _deny() -> dict:
        """Every out-of-scope / unknown-employee exit goes through here so
        the exact AC4 string is the only thing that can be emitted, and so
        no pending selection is left behind to be answered later."""
        leave_slot_service.clear_report_state(company_id, conversation_id)
        return _finish(DENIAL_MESSAGE, finish_intent="individual_report_denied")

    # classify_node GUESSED that a manager's / HR user's bare 1-4 word message
    # was an employee's name ("photosynthesis", "profit vs revenue"). When the
    # lookup then fails to find that person - no match, a 403, a failed body,
    # erp-api unreachable - the guess is withdrawn and the turn handed back to
    # the general lane, instead of answering a general question with "I
    # cannot retrieve attendance or leave information for this employee" or
    # "I'm unable to reach the HR system". Only with general chat on, and only
    # for the unprompted guess: a reply to "which employee?" still gets the
    # picker / denial (report_subject_was_guessed is never set for it).
    # Product decision (Oct 15): a guessed "name" that matches no employee goes
    # to the web-search answer whether or not general chat is on - "Calgary
    # Alberta Canada", "Delhi", a country, a topic. Live, these got the "No
    # matching employee" picker with the whole team listed. The lookup still
    # runs first, so a real report called Victoria or Austin is found as before.
    # (This replaces the earlier "nothing changes while general chat is off"
    # rule for the unprompted guess.)
    guess_can_be_withdrawn = bool(state.get("report_subject_was_guessed"))

    def _hand_back(why: str) -> dict:
        logger.info("[IndividualReport] guessed subject %r - %s - withdrawing the "
                    "guess and handing the turn back", query[:80], why)
        leave_slot_service.clear_report_state(company_id, conversation_id)
        # Correct the intent on the wire. classify_node announced
        # manager_leave_request_lookup before this node ran, and main.py takes
        # the intent it LOGS from that event. No done event: the turn has not
        # been answered yet - whatever claims it next writes it.
        writer({"type": "intent", "intent": "non_hr", "is_hr": False,
                "is_database_related": False,
                "has_date_expression": state.get("has_date_expression", False)})
        return {"usage_events": usage_events,
                "intent": "non_hr", "is_hr": False,
                "route_to": GUESSED_SUBJECT_NOT_AN_EMPLOYEE}

    # -- Gate 1: is the caller a manager? ------------------------------------
    # Normally already decided by hr_graph.manager_gate_node, which runs
    # ahead of intent classification and leaves a tri-state on the state:
    # True (manager), False (erp-api said no), None (couldn't be determined).
    #
    # The fallback below is not dead code: this node stays callable on its
    # own (tests, and any future caller that reaches it without the gate
    # node), and a permission gate that silently passes when its input is
    # missing is the wrong failure mode. When the gate HAS run, resolved is
    # not None and no second round trip is made.
    resolved = state.get("is_manager")
    context_data = None
    if resolved is None and not state.get("is_manager_jwt"):
        try:
            context_result = await erp_client.get_leave_context(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
            )
        except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
            # What failed is the question "who is asking?", not this feature.
            # Reporting it as "I'm unable to reach the HR system right now"
            # describes an outage of the lookup and invites a retry, when the
            # JWT can often answer the role question with no network at all —
            # so it is asked first, and only a genuinely undecidable role ends
            # the turn, with the wording that says what actually happened.
            if permission_service.may_view_team(state) is True:
                logger.info("[IndividualReport] role lookup failed, allowed on the JWT role claim")
                resolved = True
            else:
                return _finish("I couldn't verify your access in time - please try again in a moment.")
        else:
            context_data = context_result["body"].get("data", {})
            resolved = context_data.get("is_manager", False)
            logger.info("[IndividualReport] JWT role not manager | erp is_manager=%s", resolved)
    elif resolved is None:
        resolved = True
        logger.info("[IndividualReport] manager confirmed from JWT role claim")

    # A manager is not the only caller who may see a team member's record —
    # an HR user and an admin may too, and the rule for all three lives in
    # services/permission_service. Applied as a WIDENING on top of whatever
    # the is_manager resolution above produced: it can only turn a refusal
    # into an allow, never the reverse, so the manager path is untouched.
    if resolved is not True:
        access = permission_service.may_view_team(state, context_data=context_data)
        if access is True:
            resolved = True
            logger.info("[IndividualReport] allowed as an HR/admin caller")
        elif access == permission_service.ACCESS_UNKNOWN:
            resolved = MANAGER_UNKNOWN

    if resolved == MANAGER_UNKNOWN:
        # The gate ran but erp-api was unreachable, so nobody knows whether
        # this caller may look at another employee's record. Refusing to
        # guess is the only safe answer, and it is NOT the AC4 denial: that
        # would assert something about this employee's scope on the basis of
        # an outage.
        logger.info("[IndividualReport] manager status unknown (erp-api unreachable) - refusing")
        return _finish("I couldn't verify your access in time - please try again in a moment.")

    if not resolved:
        leave_slot_service.clear_report_state(company_id, conversation_id)
        return _finish(NOT_A_MANAGER_MESSAGE, finish_intent=access_notice.RESTRICTED_INTENT,
                       extra_data=access_notice.refuse(writer, "employee_records", NOT_A_MANAGER_MESSAGE,
                                                       other_employee=True))

    # -- Resolve the target employee ----------------------------------------
    report_state = leave_slot_service.get_report_state(company_id, conversation_id) or {}
    pending_candidates = [_normalise_employee(c) for c in (report_state.get("candidates") or [])]
    awaiting_selection = report_state.get("step") == "awaiting_employee_selection"

    employee_id = None
    employee_name = None
    attendance_date = None
    # The status the manager asserted ("half day", "absent"). Used to tell
    # them when the record disagrees with the premise of their question.
    asserted_status = None
    # Set only when the LEAVE route is asked with nobody named - erp-api
    # answers that unnarrowed, with the caller's whole team.
    team_wide = False
    # The name of whoever the lookup resolves to, when erp-api's own answer
    # won't say. /ai/attendance/punch-details returns NO "employee" block at
    # all, so on that path the only place the subject's name exists is the
    # candidate row that produced the employee_id (or the card the manager
    # picked). Without carrying it, every attendance answer would open
    # "This employee ..." instead of naming the person asked about.
    resolved_employee_row = None

    selected = _match_selection(query, pending_candidates) if awaiting_selection else None
    if selected is not None:
        # AC2 - the lookup runs only now that the manager has identified the
        # intended employee. The original question's intent and date are
        # replayed from the state saved when the cards were shown, so
        # answering "John Doe" doesn't lose what was being asked about him.
        employee_id = selected.get("employee_id")
        resolved_employee_row = selected
        intent = report_state.get("intent") or intent
        attendance_date = report_state.get("attendance_date")
        asserted_status = report_state.get("asserted_status")
        logger.info("[IndividualReport] selection resolved to employee_id=%s", employee_id)
    else:
        today = _today_in_app_timezone()
        fields, extraction_usage = await ai_service.extract_individual_report_fields(query, today)
        if extraction_usage:
            usage_events.append({"source": "individual_report_extraction", "usage": extraction_usage})

        employee_id = fields.get("employee_id")
        employee_name = fields.get("employee_name")
        attendance_date = fields.get("attendance_date")
        asserted_status = fields.get("attendance_status")

        if not employee_id and not employee_name and not awaiting_selection:
            # A bare fragment ("abc testing") the extraction call above did
            # not recognize as a name. That call judges "does this look like
            # a name" the way an LLM reads free text, which is
            # capitalization-sensitive in practice: the SAME employee typed
            # as "ABC Testing" extracts fine, typed as "abc testing" comes
            # back employee_name=null and used to fall straight through to
            # the pronoun/team-wide handling below - silently answering with
            # the whole team instead of the one person actually named.
            #
            # classify_node's own _is_bare_person_fragment is a stricter,
            # deterministic, case-INsensitive gate that already decides
            # whether a fragment is nothing BUT a name (1-4 name-shaped
            # tokens, no filler/command words, not confidently another
            # intent) one node earlier, for the identical continuation
            # shape ("Show Ayush Jio leave request" -> "Ayush Jio"). A
            # fragment that already passed that gate to get this query
            # routed here at all is trustworthy as a name here too, rather
            # than re-asking a second, less reliable judge of the same
            # question. Skipped while a selection card is pending - AC2's
            # own re-prompt-on-no-match already owns that shape.
            from services.classify_node import _is_bare_person_fragment
            has_date_expr = date_resolver.mentions_date_expression(query)
            if _is_bare_person_fragment(query, has_date_expr):
                employee_name = query.strip()
                logger.info("[IndividualReport] bare fragment %r trusted as employee_name "
                            "(extraction returned none)", employee_name)

        if not employee_id and not employee_name:
            # "Why was he marked half-day?" - resolve the pronoun against the
            # subject already established in this conversation.
            last_employee = report_state.get("last_employee") or {}
            # A bare LEAVE TYPE carries the subject the same way a pronoun
            # does. After "show A Khan Test leave requests", "casual leave"
            # means HIS casual leave - it names a filter, not a person, so
            # without this it read as naming nobody and the turn was denied
            # for a report the manager was already looking at.
            narrows_the_last_subject = bool(
                leave_action_service._extract_leave_type_filters(query or ""))
            if (fields.get("uses_pronoun") or narrows_the_last_subject) \
                    and last_employee.get("employee_id"):
                employee_id = last_employee["employee_id"]
                # The remembered subject carries the name too. On the
                # attendance path that is the ONLY place it exists (punch
                # details returns no employee block and a pronoun supplies
                # no candidate row), so without this "why was HE marked
                # half-day?" answers about "Employee 3735" one turn after
                # naming them.
                resolved_employee_row = last_employee
                logger.info("[IndividualReport] pronoun resolved to last subject employee_id=%s", employee_id)
            else:
                if awaiting_selection:
                    # A reply that named nobody on the offered list - re-show
                    # the same cards rather than guessing (AC2). Once: a
                    # second miss means the manager has moved on, and the
                    # picker lets go. HA-932 D-01: re-shown every turn, it
                    # answered "Diwali", "budget", "Python"... 37 messages.
                    if guess_can_be_withdrawn or report_state.get("reoffered"):
                        return _hand_back("second reply that picks nobody")
                    leave_slot_service.set_report_state(company_id, conversation_id,
                                                        {**report_state, "reoffered": True})
                    writer({"type": "employee_selection",
                            "data": {"action_required": "select_employee",
                                     "employees": pending_candidates}})
                    return _finish(_render_selection_prompt(pending_candidates),
                                   extra_data={"action_required": "select_employee",
                                               "employees": pending_candidates})
                bare_name = _bare_name_target(query)
                if bare_name is not None:
                    # The whole message IS the name, and the extractor came
                    # back with nothing for it.
                    #
                    # Live bug: after a team pending-leave card the manager
                    # typed "abc testing" and was shown the WHOLE team's
                    # pending requests again. classify_node's bare-name fast
                    # path had routed the turn correctly - the name was lost
                    # here, one step later. The extractor is an LLM prompt
                    # that sees the message WITHOUT the card it continues, so
                    # a two-word fragment with no verb and no question is
                    # exactly its weakest input, and its failure mode is an
                    # empty field set. Falling through to team_wide then
                    # answers a question the manager did not ask, and it
                    # looks intermittent because the extractor is not
                    # deterministic - the same name works one turn and not
                    # the next.
                    #
                    # So: don't ask the model what it already said. The
                    # continuation is deterministic (_is_bare_person_fragment
                    # is what classify_node routed on), and a term matching
                    # nobody still lands on the roster cards below rather
                    # than a dead end.
                    employee_name = bare_name
                    logger.info("[IndividualReport] extraction returned no employee for the "
                                "bare name %r - taking the message as the name", bare_name)
                elif intent != LEAVE_REQUEST_INTENT:
                    # The ATTENDANCE route has no team-wide shape - punch
                    # details are for one employee on one day - so it asks.
                    return _finish(
                        "Which team member would you like me to look this up for? "
                        "Please give me their name or employee ID."
                    )
                else:
                    # The LEAVE endpoint answers "show me the leave requests"
                    # as asked when nobody is named: unnarrowed, it returns
                    # the caller's whole team. Asking "which team member?"
                    # would make the manager answer a question they never
                    # needed to.
                    team_wide = True
                    logger.info("[IndividualReport] no employee named - answering team-wide")

    is_attendance = intent == ATTENDANCE_EXPLANATION_INTENT
    # AC3 - an attendance explanation with no date stated defaults to Today.
    resolved_date = None
    if is_attendance:
        resolved_date = _resolve_attendance_date(query, attendance_date,
                                                 _today_in_app_timezone())

        # An attendance record cannot exist for a day that has not happened,
        # so asking why someone WAS marked something on a future date is
        # incoherent - erp-api answers "Upcoming" with an empty record, which
        # reads like a real answer to the question asked. Say so instead.
        #
        # This also backstops the whole date tier: a future date on a
        # past-tense question is a mis-resolution whatever produced it, so
        # this catches the next "this Monday"-shaped bug on its own rather
        # than rendering a hollow record.
        if resolved_date > _today_in_app_timezone().isoformat():
            logger.info("[IndividualReport] resolved date %s is in the future - refusing",
                        resolved_date)
            return _finish(
                f"{resolved_date} hasn't happened yet, so there's no attendance "
                f"recorded for it. Ask me about a day that has already passed.",
                extra_data={"date": resolved_date, "is_future": True},
            )

    # -- Fetch ---------------------------------------------------------------
    fetching = {"type": "fetching_individual_report",
                "message": ("Checking that team member's attendance record..." if is_attendance
                            else "Checking that team member's leave request...")}
    if guess_can_be_withdrawn:
        # Held back until the guess is kept: "tough" from a manager showed
        # "Checking that team member's leave request..." and then a
        # conversational reply. A withdrawn guess never shows it (_hand_back's
        # intent correction is not something the user sees); a kept one sends
        # it just ahead of its first event, as before.
        send = writer

        def writer(event):
            nonlocal fetching
            if fetching and event.get("type") != "intent":
                send(fetching)
                fetching = None
            send(event)
    else:
        writer(fetching)

    async def _call_erp(target_id, target_name):
        """(result, error_response). error_response is an already-finished
        _finish(...) value on a transport failure; otherwise it is None."""
        try:
            if is_attendance:
                return await erp_client.get_attendance_punch_details(
                    bearer_token, company_id=company_id, conversation_id=conversation_id,
                    employee_id=target_id, employee_name=target_name,
                    attendance_date=resolved_date,
                ), None
            return await erp_client.get_team_pending_leaves(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
                employee_id=target_id, employee_name=target_name,
            ), None
        except erp_client.ErpApiTimeout:
            return None, _finish(_ERP_TIMEOUT_MESSAGE)
        except erp_client.ErpApiUnavailable:
            return None, _finish(_ERP_UNAVAILABLE_MESSAGE)

    if guess_can_be_withdrawn:
        # Checked BEFORE calling, so a failed lookup never writes its own
        # "unable to reach the HR system" done event first.
        try:
            if is_attendance:
                result = await erp_client.get_attendance_punch_details(
                    bearer_token, company_id=company_id, conversation_id=conversation_id,
                    employee_id=employee_id, employee_name=employee_name,
                    attendance_date=resolved_date)
            else:
                result = await erp_client.get_team_pending_leaves(
                    bearer_token, company_id=company_id, conversation_id=conversation_id,
                    employee_id=employee_id, employee_name=employee_name)
        except (erp_client.ErpApiTimeout, erp_client.ErpApiUnavailable):
            return _hand_back("erp-api unreachable")
    else:
        result, error_response = await _call_erp(employee_id, employee_name)
        if error_response is not None:
            return error_response

    # -- Gate 2: erp-api's per-employee scope decision ----------------------
    if result.get("http_status") == 403:
        if guess_can_be_withdrawn:
            return _hand_back("erp-api 403")
        logger.info("[IndividualReport] denied by erp-api scope check")
        return _deny()

    body = result.get("body") or {}
    data = body.get("data") or {}

    if data.get("action_required") == "search_employee":
        # erp-api rejected the SEARCH TERM itself - e.g. "employee_name=a"
        # comes back success=false / "Please enter at least 2 characters of
        # the employee name." This is a validation error about what was
        # typed, NOT a scope decision about a named person, so it carries no
        # AC4 disclosure risk and erp-api's own message is surfaced verbatim.
        # Without this branch the body falls through every guard below (data
        # is a non-empty dict, action_required != "select_employee", leaves
        # is absent) and renders the misleading "That team member has no
        # pending leave requests."
        if guess_can_be_withdrawn:
            return _hand_back("erp-api rejected the search term")
        logger.info("[IndividualReport] erp-api rejected the search term - re-asking")
        return _finish(
            body.get("message")
            or "Please give me the team member's full name or employee ID.",
            finish_intent="individual_report_needs_employee",
        )

    if not body.get("success", True) and not data:
        # A non-403 business failure with nothing to show. Treated as a
        # denial rather than surfaced verbatim: erp-api's message on this
        # path is not guaranteed to be free of the details AC4 forbids.
        if guess_can_be_withdrawn:
            return _hand_back("non-success body")
        logger.info("[IndividualReport] non-success body with no data - denying")
        return _deny()

    if data.get("action_required") == "select_employee":
        # Normalise every card to the one shape the SSE payload and renderers
        # expect — this is where employee_designation gets surfaced under a
        # single key whichever spelling erp-api used on the row.
        candidates = [_normalise_employee(c) for c in (data.get("employees") or [])]

        # AC4 on the leave path. /leave/pending/teams has no 403 for an
        # unknown name: a name matching nobody in the caller's team comes
        # back search_matched=false WITH the full team roster attached,
        # erp-api's way of saying "pick from your team". Surfacing that
        # roster would answer a question about a named employee with a
        # different answer depending on whether they exist in scope, which
        # is exactly what AC4 forbids — so a searched-but-unmatched name is
        # a denial, indistinguishable from an out-of-scope one.
        # True when erp-api could not match the term at all, so `candidates`
        # is the caller's whole team rather than a shortlist for the name.
        unmatched_term = False

        if data.get("search_matched") is False:
            # First try the term against the roster erp-api just handed
            # back — its own search covers the name field only, so an
            # employee NUMBER ("geo6") lands here even for a real report.
            # Narrowing the caller's own roster cannot widen scope; see
            # _resolve_from_roster.
            from_roster = _resolve_from_roster(employee_name, candidates)
            if from_roster:
                logger.info("[IndividualReport] resolved %r from team roster (%d match(es))",
                            employee_name, len(from_roster))
                candidates = from_roster
            else:
                # PRODUCT DECISION (overrides AC4's exact-denial wording on
                # this path, at the product owner's direction): a term that
                # matches nobody gets the team roster to pick from, mirroring
                # what /leave/pending/teams itself returns, instead of
                # DENIAL_MESSAGE.
                #
                # What this does and does not give away: erp-api answers
                # identically for gibberish ("asdf"), a typo ("mani") and a
                # real employee outside the team ("Rahul Verma") - all three
                # are search_matched=false with the same roster (verified
                # live). So this reveals no more about the named person than
                # the denial did; both disclose the same single bit, "not in
                # your team". It does NOT confirm whether they exist in the
                # system, nor anything about their records.
                #
                # The roster itself is the caller's own direct reports, which
                # they are already entitled to see (team_leave_query_node
                # shows the same people).
                #
                # AC4's denial is still live everywhere else: a 403 on either
                # endpoint, and any non-success body with no data.
                unmatched_term = True
                logger.info("[IndividualReport] %r matched nobody - offering the team roster",
                            employee_name)
                # Not a person at all ("leave status of Superman", UV-22,
                # 29 Oct): no roster of 18 real people for a fictional name.
                if nlp_service.names_a_non_person(employee_name):
                    leave_slot_service.clear_report_state(company_id, conversation_id)
                    return _finish(f"{employee_name.strip()} isn't an employee here, so there's "
                                   f"no leave or attendance record to show. I can look up anyone on "
                                   f"your team - just tell me their name.")

        if not candidates:
            return _deny()

        # A GUESSED term that erp-api's fuzzy search tied to people who share
        # no word with it ("dsdsfdsfsd" -> "More than one team member matches")
        # matched nobody: the turn goes to web search, not a picker of strangers.
        if (guess_can_be_withdrawn and not unmatched_term
                and not _shares_a_name_word(employee_name, candidates)):
            return _hand_back("search matched only by fuzzy similarity")

        # An exactly-typed name is not a question. erp-api's search matches
        # any name token, so "ayush jio" returns Ayush Chandra too and the
        # manager is handed a "which one did you mean?" card naming the very
        # person they spelled out in full. Narrow to the exact match first;
        # anything still ambiguous after this (two real namesakes, a partial
        # name, a typo) falls through to the card exactly as before.
        if not unmatched_term and len(candidates) > 1:
            exact = _exact_name_matches(employee_name, candidates)
            if len(exact) == 1:
                logger.info("[IndividualReport] %r is an exact match for "
                            "employee_id=%s - skipping the selection card",
                            employee_name, exact[0].get("employee_id"))
                candidates = exact

        # A name search that unambiguously hit ONE person still comes back
        # as the "select one" shape rather than the record — same erp-api
        # behaviour shift_query.py already handles on /shift-details.
        # Re-fetch by the resolved id instead of bouncing a one-item menu
        # back at the manager.
        # A one-person shortlist is resolved straight through, but only when
        # the term actually matched them. An unmatched term on a one-person
        # team still has to be OFFERED - auto-fetching would answer about
        # somebody the manager never named.
        if (len(candidates) == 1 and not unmatched_term and guess_can_be_withdrawn
                and len((query or "").split()) == 1):
            # UAT UV-04 (PR-165..167): "salt", "auto", "demo" alone - one word,
            # nothing asked before it - matched a team member ("Phil salt")
            # and their leave card came up. A single word is as likely a
            # topic as a surname, so ask before showing anyone's record.
            fetching = None  # nothing is being checked yet
            return _ask_which_meaning(query.strip(" ?.!"), candidates[0], _finish)
        if len(candidates) == 1 and not unmatched_term:
            resolved_employee_row = candidates[0]
            resolved_id = candidates[0].get("employee_id")
            logger.info("[IndividualReport] single name match - re-fetching by employee_id=%s", resolved_id)
            result, error_response = await _call_erp(resolved_id, None)
            if error_response is not None:
                return error_response
            if result.get("http_status") == 403:
                return _deny()
            body = result.get("body") or {}
            data = body.get("data") or {}
            if data.get("action_required") == "select_employee":
                # Re-fetch by id came back as another menu — erp-api can't
                # resolve it, so there is nothing to show for this person.
                return _deny()
        elif unmatched_term and guess_can_be_withdrawn:
            # The directory found nobody by that name. It cannot tell a topic
            # from a real name outside this manager's team (both come back
            # search_matched=false with the roster, and AC4 forbids saying
            # which), so a non-report's name now gets a general answer rather
            # than the roster - the trade made for general chat, behind its
            # flag. Never applied while a selection card is open: there the
            # bare reply really is an answer to "which person?".
            return _hand_back("matched nobody")
        else:
            stored = leave_slot_service.set_report_state(company_id, conversation_id, {
                "step": "awaiting_employee_selection",
                "intent": intent,
                "attendance_date": resolved_date,
                "asserted_status": asserted_status,
                "candidates": candidates,
                "last_employee": report_state.get("last_employee"),
                # A picker raised in reply to a picker is its re-offer.
                "reoffered": awaiting_selection,
            })
            writer({"type": "employee_selection",
                    "data": {"action_required": "select_employee",
                             "search_matched": not unmatched_term,
                             "employees": candidates}})
            message = _render_selection_prompt(candidates, unmatched_term=unmatched_term)
            if not stored:
                # The selection cards are on screen but the follow-up has
                # nowhere to resolve against - say so rather than let the
                # next turn fail silently or, worse, re-run as a fresh
                # ambiguous lookup.
                message += ("\n\nPlease include their full name or employee ID in your reply - "
                            "I can't hold the shortlist right now.")
            return _finish(message, extra_data={"action_required": "select_employee",
                                                "search_matched": not unmatched_term,
                                                "employees": candidates})

    employee = _normalise_employee(data.get("employee") or {})
    # Fill in from the row that resolved the lookup when erp-api's response
    # carries no employee of its own (always the case on punch-details).
    if resolved_employee_row:
        for key in ("employee_id", "employee_name", "employee_number", "employee_designation"):
            if not employee.get(key) and resolved_employee_row.get(key):
                employee[key] = resolved_employee_row[key]

    # /leave/pending/teams' employee sibling is {name, emp_no} — no id at
    # all — so the subject a pronoun follow-up resolves against has to come
    # from the id we actually queried with, or from the leave rows (which
    # do carry employee_id). Without this, "why was HE marked half-day?"
    # after a leave lookup had nothing to resolve to.
    leave_rows = data.get("leaves") or []
    resolved_employee_id = (
        employee.get("employee_id")
        or employee_id
        or (leave_rows[0].get("employee_id") if leave_rows else None)
    )
    if resolved_employee_id and not employee.get("employee_id"):
        employee["employee_id"] = resolved_employee_id
    # /leave/pending/teams' employee block has no designation; the rows do.
    if not _designation_of(employee) and leave_rows:
        role = _designation_of(leave_rows[0])
        if role:
            employee["employee_designation"] = role

    # Selection satisfied (or never needed): remember the subject so a
    # pronoun follow-up resolves, and drop the pending-selection step.
    #
    # The leave rows themselves are remembered too (FR-07.4). This module
    # still approves nothing - viewing remains its whole scope - but "approve
    # it" is a follow-up to THIS answer, and the word "it" names no request.
    # Something has to hold what was just shown, and the alternative is
    # leave_approval.py re-deriving it from the chat transcript, which is how
    # the wrong request gets approved. Trimmed to the fields a confirmation
    # card renders, and capped, because this is a Redis value on every
    # lookup, not a cache of the response.
    remembered_requests = [_remembered_leave(lv, resolved_employee_id) for lv in leave_rows[:10]]
    if team_wide:
        # A team list has no single subject. Remembering one would make
        # whoever happens to sort first the answer to the next "why was HE
        # marked...?" - so the subject slot is left empty rather than written
        # wrong. The rows themselves are still remembered: "approve it" after
        # a team list is ambiguous, and leave_approval.py disambiguates a
        # remembered list rather than picking from it.
        leave_slot_service.set_report_state(company_id, conversation_id, {
            "step": "resolved",
            "last_leave_requests": remembered_requests,
        })
    else:
        leave_slot_service.set_report_state(company_id, conversation_id, {
            "step": "resolved",
            "last_employee": {
                "employee_id": resolved_employee_id,
                "employee_name": (employee.get("employee_name")
                                  or (leave_rows[0].get("employee_name") if leave_rows else None)),
            },
            "last_leave_requests": remembered_requests,
        })

    if is_attendance:
        # punch-details answers with the day's whole record at the top level
        # (shift / attendance / punches / work_hours), and echoes the date it
        # actually used as requested_date.
        record_date = data.get("requested_date") or resolved_date
        subject = _subject_label(employee)

        # Second call, by the id already resolved above: /ai/attendance/query
        # is the only place the human-readable STATUS lives ("Present",
        # "Absent", "Off", "Not Recorded"). punch-details names it as an
        # internal code plus a remark, and answering "why was X marked
        # absent" with "recorded as O" answers a different question.
        #
        # Deliberately best-effort: the scope check has already passed on
        # punch-details, so a failure here means the evidence is available
        # but the label is not - degrade to the punch record rather than
        # losing the whole answer to a second endpoint's bad day.
        status_record = await _fetch_status_record(
            bearer_token, company_id, conversation_id, resolved_employee_id, record_date)

        # A day with no punches comes back 200 with attendance null and
        # punch_status "no_records" - a real answer, not a failure, and never
        # AC4's denial. It is NOT the same as "no status": a day can be
        # marked Absent or Off with nothing punched, so the status word is
        # reported when there is one and only the punch evidence is
        # described as missing.
        if not data.get("attendance") and not (data.get("punches") or []):
            day = (status_record or {}).get("day")
            when = f"{day}, {record_date}" if day else record_date
            status = (status_record or {}).get("status")
            if status:
                message = _lead_in(subject, asserted_status, status, when).rstrip(".")                     + ", with no punches recorded."
            else:
                message = f"There's no attendance recorded for {subject} on {when}."
            return _finish(
                message,
                extra_data={"employee": employee, "date": record_date,
                            "status": status, "day": day,
                            "attendance": None, "punches": [],
                            "shift": data.get("shift"),
                            "punch_status": data.get("punch_status")},
            )

        event_data = {
            "employee": employee, "date": record_date,
            "status": (status_record or {}).get("status"),
            "asserted_status": asserted_status,
            "day": (status_record or {}).get("day"),
            "attendance": data.get("attendance"),
            "shift": data.get("shift"),
            "punches": data.get("punches") or [],
            "punch_status": data.get("punch_status"),
            "punch_count": data.get("punch_count"),
            "work_hours": data.get("work_hours"),
            "logical_shift_date": data.get("logical_shift_date"),
        }
        writer({"type": "individual_attendance_explanation", "data": event_data})
        message = _render_attendance_explanation(employee, data, record_date,
                                                 status_record=status_record,
                                                 asserted_status=asserted_status)
        return _finish(message, extra_data=event_data)

    leaves = data.get("leaves") or []
    # erp-api's own employee sibling is absent on some shapes; the rows
    # themselves always carry the name, so fall back to that before the
    # generic label.
    employee_label = (employee.get("employee_name")
                      or (leaves[0].get("employee_name") if leaves else None)
                      or "That team member")

    if team_wide:
        # Rows span several people, so each line has to say whose it is and
        # the header names the team, not a person.
        employee_label = "Your team"

    # A leave TYPE named in the question narrows the answer to it. "show
    # casual leave request of geo3" used to return every pending request the
    # person had — short, earned, casual alike — so the reply never reflected
    # what was asked. erp-api's endpoint has no type parameter, so this is
    # applied to the rows it returned: matched on leave_type_slug, the same
    # closed vocabulary leave_balance filters by, so "casual" means the same
    # thing on both routes.
    type_filters = leave_action_service._extract_leave_type_filters(query)
    type_label = None
    #: Everything this employee has pending, before the type filter narrows
    #: it. Kept because a filter that matches nothing still has something
    #: useful to say - see the not-found branch below.
    all_leaves = list(leaves)
    if type_filters:
        wanted = set(type_filters)
        leaves = [lv for lv in leaves if (lv.get("leave_type_slug") or "") in wanted]
        words = [leave_action_service._SLUG_TO_LEAVE_TYPE_WORD.get(slug, slug.replace("_", " "))
                 for slug in type_filters]
        # "sick" -> "sick leave", but "short leave" stays "short leave".
        words = [w if "leave" in w else f"{w} leave" for w in words]
        type_label = " or ".join(words)

    # ONE payload, ONE event, whether or not there are rows to show.
    #
    # The empty case used to return prose with no `individual_leave_request`
    # event at all, and a payload missing `total_pending_leaves` that the
    # populated case carried. So the same question about the same person came
    # back as a titled "Leave Request - <name>" card one turn and a bare chat
    # bubble the next (QA screenshot), and any renderer keying off
    # `total_pending_leaves` saw two different shapes for one card.
    #
    # An empty result is still an answer ABOUT that employee - it belongs in
    # the same card, showing its empty state. The wording stays in
    # `done`'s `data.answer`, which is what the card body renders in both
    # cases. Deliberately unlike team_leave_query_node, whose AC#6 requires
    # the bare line and NO card for an empty team queue; this card is
    # per-employee and the Figma shows it with an empty state.
    # A TYPE that this employee has nothing of, while they DO have other
    # requests pending. Answered with what they actually have rather than a
    # flat "no short leave requests", and the card shows those rows instead
    # of an empty shell.
    #
    # Reported: a manager looking at Rudraveer's Casual and Sick requests
    # typed "short leave" and got a blank grey box - the card rendered from
    # `leaves: []` with nothing in it, and the sentence underneath said only
    # that he had none. Neither told the manager what he DID have, or that
    # another team member might.
    if type_filters and not leaves and all_leaves:
        available = sorted({(lv.get("leave_type") or "Leave") for lv in all_leaves})
        listed = ", ".join(available[:-1]) + f" or {available[-1]}" \
            if len(available) > 1 else available[0]
        event_data = {"employee": employee, "leaves": all_leaves,
                      "team_wide": team_wide,
                      "total_pending_leaves": data.get("total_pending_leaves",
                                                       len(all_leaves)),
                      "leave_type_filter": type_filters or None,
                      "requested_leave_type_unavailable": type_label}
        writer({"type": "individual_leave_request", "data": event_data})
        return _finish(
            f"{employee_label} doesn't have a pending {type_label} request - "
            f"what's pending for them is {listed}. You can pick one of those, "
            f"or tell me another team member to check for {type_label}.",
            extra_data=event_data,
        )

    total = (len(leaves) if type_filters
             else data.get("total_pending_leaves", len(leaves)))
    event_data = {"employee": employee, "leaves": leaves, "team_wide": team_wide,
                  "total_pending_leaves": total,
                  "leave_type_filter": type_filters or None}
    writer({"type": "individual_leave_request", "data": event_data})

    if not leaves:
        what = f"pending {type_label} requests" if type_label else "pending leave requests"
        return _finish(f"{employee_label} has no {what}.", extra_data=event_data)

    message = _render_leave_requests(employee_label, leaves, per_row_employee=team_wide,
                                     type_label=type_label)
    return _finish(message, extra_data=event_data)


# -- Graph nodes -------------------------------------------------------------
# Two distinct graph routes, one shared pipeline. The split is real at the
# routing layer (the graph names a node per sub-intent, so the path a query
# takes is visible in the graph rather than hidden in a branch), while the
# manager gate, target resolution, AC2 selection flow and AC4 denial stay in
# ONE body — duplicating them per node is how a permission rule ends up
# enforced on one path and quietly missing on the other.
#
# Each wrapper pins the intent for its route, so a node can never be reached
# and then act on the other kind of question.

async def leave_request_node(state: dict, writer: StreamWriter) -> dict:
    """Route for manager_leave_request_lookup - a named report's pending
    leave requests."""
    return await individual_report_node({**state, "intent": LEAVE_REQUEST_INTENT}, writer)


async def attendance_explanation_node(state: dict, writer: StreamWriter) -> dict:
    """Route for manager_attendance_explanation - why a named report's
    attendance was recorded as it was on a given date."""
    return await individual_report_node({**state, "intent": ATTENDANCE_EXPLANATION_INTENT}, writer)
