import asyncio
import logging
import re
from typing import Optional

from langgraph.types import StreamWriter

from schema.agent import HRState
from services.nlp_service import check_custom_guardrail, fast_classify, _looks_like_genuine_query
from services.regularisation_node import REGULARIZATION_CONFIG
from services.ai_service import (
    _check_moderation,
    classify_intent_structured,
    ACTIVE_LLM_PROVIDER,
)
import services.leave_slot_service as leave_slot_service
import services.leave_history_clarify_state as leave_history_clarify_state
import services.leave_cancel_state as leave_cancel_state
import services.leave_disambiguation_state as leave_disambiguation_state
import services.leave_type_clarify_state as leave_type_clarify_state
from services.leave_action_service import (
    _looks_like_leave_policy_question,
    _resolve_leave_history_clarification,
    _rewrite_query_for_history_clarify_resolution,
    _is_single_day,
    _SESSION_TYPE_REQUIRED_LEAVE_TYPES,
    _extract_leave_type_filters,
    _SLUG_TO_LEAVE_TYPE_WORD,
    _extract_request_id,
    _is_declining_or_cancelling,
)
from services import slot_store
import services.date_resolver as date_resolver

logger = logging.getLogger(__name__)


# Deterministic confirm/proceed detector for the mid-flow regularisation
# check in classify_node (below) — mirrors leave_action_service.py's
# _CANCEL_LEAVE_CONFIRM_PATTERNS. Needed so a bare "confirm"/"yes"/"go
# ahead" reliably keeps routing into regularisation_node without paying for
# a full LLM classification call, even though it never hits fast_classify's
# keyword lists (which have no generic confirm/proceed entry at all).
_REG_MID_FLOW_CONTINUATION_RE = re.compile(
    r"\b(confirm|proceed|submit)\b|\bgo\s+ahead\b|^\s*(yes|yeah|yep|sure|ok(?:ay)?)\b",
    re.IGNORECASE,
)


# Reply-resolution for the "would you like your balance, eligibility, to
# apply, or your application status for <type> leave?" clarifying question
# (see leave_type_clarify_state.py and Fast-path 0.4 below). Checked in a
# fixed priority order, same philosophy as _resolve_leave_history_clarification
# in leave_action_service.py.
_LEAVE_TYPE_CLARIFY_BALANCE_WORDS = ("balance", "remaining", "left", "quota")
_LEAVE_TYPE_CLARIFY_ELIGIBILITY_WORDS = ("eligib", "qualify", "entitle")
_LEAVE_TYPE_CLARIFY_APPLY_WORDS = ("apply", "book", "request", "take", "submit")
_LEAVE_TYPE_CLARIFY_STATUS_WORDS = ("status", "applied", "history", "pending", "approved", "rejected")


def _resolve_leave_type_clarification(query: str) -> Optional[str]:
    """Returns 'leave_balance', 'leave_eligibility', 'apply_leave',
    'leave_status', or None (unrecognized reply)."""
    text = query.lower()
    if any(w in text for w in _LEAVE_TYPE_CLARIFY_BALANCE_WORDS):
        return "leave_balance"
    if any(w in text for w in _LEAVE_TYPE_CLARIFY_ELIGIBILITY_WORDS):
        return "leave_eligibility"
    if any(w in text for w in _LEAVE_TYPE_CLARIFY_APPLY_WORDS):
        return "apply_leave"
    if any(w in text for w in _LEAVE_TYPE_CLARIFY_STATUS_WORDS):
        return "leave_status"
    return None


def _rewrite_query_for_leave_type_clarify_resolution(resolved: str, type_word: str) -> str:
    if resolved == "leave_balance":
        return f"{type_word} leave balance"
    if resolved == "leave_eligibility":
        return f"am I eligible for {type_word} leave"
    if resolved == "apply_leave":
        return f"apply for {type_word} leave"
    return f"{type_word} leave status"


# ── Shared intent helpers ─────────────────────────────────────────────────────
_HR_CONTEXT_SIGNALS = {
    "salary", "leave", "payroll", "recruitment", "hiring", "benefits",
    "performance", "attendance", "onboarding", "training", "compliance",
    "hr", "employee", "appraisal", "compensation", "interview",
    "job", "skills", "experience", "developer", "manager", "role",
    "kpi", "pip", "bonus", "increment", "allowance", "insurance",
    "termination", "grievance", "induction", "timesheet", "shift","regularisation"
}

_NON_HR_TRIGGERS = {"weather", "sport", "recipe", "cook", "game", "movie", "music", "news"}


def _context_has_hr_signal(recent: list) -> bool:
    text = " ".join(m.get("content", "") for m in recent).lower()
    return any(signal in text for signal in _HR_CONTEXT_SIGNALS)


def _build_regularisation_pending_hint(entries: list, has_free_text_pending: bool) -> str:
    """Tells the intent classifier about an in-progress regularisation
    request so it can tell a genuine continuation apart from a fresh,
    unrelated query — used only as the fallback once fast_classify and the
    deterministic checks in classify_node's mid-flow regularisation block
    (see 'existing_regularization_slots') can't confidently decide either
    way.

    The two states need OPPOSITE framing, not just different wording:
    - Still missing a field: the classifier needs ENCOURAGEMENT to read a
      bare "10am to 7pm" or "forgot to punch out" as 'regularisation' — on
      its own that fragment carries no keyword at all.
    - Already complete, awaiting confirmation: by the time this hint is
      built, the deterministic confirm/cancel check already ran and MISSED
      (see the mid-flow block) — so encouraging 'regularisation' here would
      just make the classifier repeat that miss. What it actually needs is
      the OPPOSITE nudge: this request is disambiguated background state,
      not a reason to bias classification of the current message. Without
      this explicit override, the generic "short follow-up of an earlier
      HR question -> matching intent" instruction elsewhere in the prompt
      (plus the review card still sitting in recent conversation context)
      pulls the model back toward 'regularisation' anyway whenever the new
      message is topically close — confirmed live: "why was I marked
      absent on the 18th", asked right after the regularisation review
      card for the 18th, kept getting classified as 'regularisation'
      instead of 'attendance_explain' purely because it named the same
      date, corrupting the still-pending entry's prefilled times in the
      process (see slot_flow.py's merge behavior)."""
    dates = ", ".join(e.get("date") for e in entries if e.get("date")) or "an unspecified date"
    if has_free_text_pending:
        return (
            "IMPORTANT — PENDING FLOW: The user has an UNFINISHED attendance regularisation "
            f"request in progress for {dates}, still missing a time or a reason. If the current "
            "query supplies a date, time, or reason — or otherwise continues answering that "
            "request — classify it as 'regularisation'. Only classify it as something else if "
            "it is clearly a new, unrelated question or request.\n\n"
        )
    return (
        "IMPORTANT — PENDING FLOW: The user has a COMPLETE attendance regularisation request "
        f"for {dates} sitting unconfirmed in the background. It was already checked for an "
        "explicit confirm ('yes'/'submit'/'go ahead') or cancel ('no'/'cancel'/'never mind') "
        "reply and this message is NEITHER — so do NOT classify it as 'regularisation' just "
        "because it mentions the same date or general attendance topic, and IGNORE the "
        "'short follow-up' guidance elsewhere for this message. Classify it strictly by what "
        "the user is actually asking. Example: a question about WHY a day was marked a "
        "certain way is 'attendance_explain', not 'regularisation', even for the exact same "
        "date as the pending request.\n\n"
    )


def _build_intent_prompt(
    query: str, recent: list, has_hr_context: bool,
    awaited_slot_description: Optional[str] = None,
    pending_flow_hint: str = "",
    awaited_context_label: str = "an in-progress leave application",
    awaited_target_intent: str = "apply_leave",
) -> str:
    context_block = ""
    if recent:
        lines = [
            f"{m.get('role', 'user').upper()}: {m.get('content', '')[:200]}"
            for m in recent
        ]
        context_block = (
            "Recent conversation (read this to understand follow-up queries — "
            "do NOT classify these lines, classify only the Current Query below):\n"
            + "\n".join(lines)
            + "\n\n"
        )

    followup_directive = ""
    if has_hr_context:
        followup_directive = (
            "NOTE: The conversation above is HR-related. "
            "If the current query is a SHORT follow-up or refinement of an earlier HR question "
            "(e.g. adding a country, date, or clarification), classify it as the matching HR intent. "
            "But if the current query is a NEW, clearly off-topic question — classify it as non_hr regardless of prior context.\n\n"
        )

    # Without this, a bare, context-free reply mid-flow (e.g. "vocation" as
    # an answer to "what's the reason for this leave request?") reads to a
    # general-purpose classifier as an off-topic word and comes back
    # non_hr — silently discarding the whole in-progress application. Telling
    # it exactly what question it's judging the reply against fixes the
    # blind guess without weakening genuine-interruption detection: a real
    # topic switch ("generate a jd for ai engineer") still doesn't look like
    # a plausible answer to "what dates would you like," so the "unmistakably
    # a new question" escape hatch still lets it through.
    awaited_directive = ""
    if awaited_slot_description:
        awaited_directive = (
            f"CRITICAL CONTEXT: The user has {awaited_context_label}. "
            f"The assistant's last message was asking them for: {awaited_slot_description}. "
            "If the CURRENT USER QUERY could plausibly be answering that — even "
            "a single word, a date, or an odd/unclear reply — classify it as "
            f"{awaited_target_intent}. Only classify it as something else if it is "
            "unmistakably a new question or a different HR topic.\n\n"
        )

    return f"""You are a strict intent classifier for Helix AI — an HR-only assistant.

Classify the CURRENT USER QUERY into exactly one label.

Conversational intents (always HR-side — never non_hr):
  greeting             — hi, hello, hey, good morning, how are you, how's it going
  small_talk           — thanks, great job, you're helpful, bye
  capabilities_inquiry — what can you do, what do you help with, tell me about yourself,
                         are you a bot/AI/real person, what's your name
  conversation_meta    — about THIS CHAT itself: my last query, what did I ask, summarize
                         our conversation. NEVER their own HR records — "show my leave
                         application history" is leave_status (their leave records), not
                         conversation_meta, even though it contains the word "history".

HR domain intents (must relate directly to managing employees or workplace policies):
  leave_balance        — asking about THEIR OWN remaining/available leave days (e.g.
                         "what's my leave balance", "how many sick leaves do I have left")
  apply_leave          — wanting to APPLY FOR / BOOK / REQUEST leave for themselves
                         (e.g. "I want to apply for leave", "book a casual leave tomorrow")
  leave_status         — checking the STATUS/OUTCOME of a leave request they already
                         submitted, INCLUDING pending, approved, cancelled, or rejected ones
                         (e.g. "is my leave approved", "status of my leave request", "do I have
                         any pending leave requests", "show me my pending leaves", "view pending
                         leave request", "show my cancelled leaves", "show my cancel leave",
                         "what leaves have I cancelled") — this is a VIEWING/LISTING request
                         about the STATE of already-submitted request(s), never an instruction
                         to act on one. NOT a question about remaining/available day counts
                         (that's leave_balance).
  cancel_leave         — wanting to CANCEL/WITHDRAW a leave request they already submitted, i.e.
                         an ACTION to perform NOW (e.g. "cancel my leave", "withdraw my pending
                         request", "cancel LR-2041", "please cancel it"). The word "cancel"
                         alone does NOT mean this intent — "show me my CANCELLED leaves" is
                         asking to VIEW past cancellations (leave_status), not to cancel
                         anything; only an imperative asking the assistant to actually perform
                         the cancellation belongs here.
  leave_eligibility    — asking whether THEY THEMSELVES QUALIFY for a leave type under
                         company policy (e.g. "am I eligible for casual leave",
                         "do I qualify for earned leave", "can I take sick leave")
  leave_policy         — general leave TYPES, RULES, or POLICY questions not about their
                         own balance, eligibility, or applying (e.g. "what is the maternity
                         leave policy", FMLA, PTO rules, approval process in general)
  payroll              — payroll processing, pay slip, deductions, salary disbursement
  salary               — salary range, CTC, compensation, increment, bonus, pay raise
  recruitment          — hiring process, job posting, candidate screening, offer letter
  benefits             — health insurance, provident fund, gratuity, perks, allowances
  performance          — KPI, appraisal, performance review, PIP, rating, 360 feedback
  attendance           — attendance tracking ,show my attandance for a date
  punch_details        — asking for THEIR OWN punch/check-in/check-out times, shift timing, or
                         worked hours for a specific day (e.g. "what time did I check in today",
                         "my shift timing", "how many hours did I work yesterday", "punch details
                         for 21 July")
  attendance_explain   — asking WHY their attendance on a specific day was marked a certain
                         way (Present, Half Day, Late, Absent, Missing Punch) — wants the
                         reasoning/explanation for a classification, not just a status lookup
                         (e.g. "why was I marked late today", "explain my attendance for Monday",
                         "why does it show missing punch")
  regularisation       — wanting to SUBMIT/APPLY a regularisation request for a missed or
                         incorrect punch (e.g. "regularise my attendance for yesterday",
                         "apply for attendance regularization", "missed punch regularisation")
  employee_management  — termination, disciplinary action, grievance, conflict, exit process
  onboarding           — new hire formalities, induction, probation, day one checklist
  training             — training programs, L&D, upskilling, development plans
  compliance           — labor law, employment contract, statutory compliance, HR audit
  job_description      — writing JDs, role profiles, responsibilities for a position
  interview_questions  — interview question sets, screening assessments for hiring
  skills               — skills required for a specific HR-managed role or team
  leave_status         — checking the STATUS/OUTCOME/HISTORY of leave request(s) they
                         already submitted (e.g. "is my leave approved", "status of my
                         leave request", "show my leave application history")
  leave_policy         — general leave TYPES, RULES, or POLICY questions not about their
                         own balance or applying, including how a leave type's accrual/
                         entitlement works (e.g. "what is the maternity leave policy",
                         "how does compensatory off accrual work", FMLA, PTO rules, approval
                         process in general). Never work-from-home, attendance, or absence
                         rules — those are attendance, even when the query says "...policy".
  payroll              — payroll processing, pay slip, deductions, salary disbursement,
                         professional tax deduction, and the SETTLEMENT CALCULATION/AMOUNT
                         of a full and final settlement (the offboarding STEPS around it are
                         employee_management; the number-crunching itself is payroll)
  salary               — salary range, CTC, compensation, increment, bonus, pay raise
  recruitment          — the hiring PROCESS/STRATEGY/LOGISTICS: current job openings,
                         candidate sourcing (incl. passive candidates), screening approach,
                         resume red flags, background checks, time-to-hire (a
                         recruitment-specific metric, not a general_hr one), counter-offer
                         handling, candidate rejection communication, applicant tracking.
                         NOT the specific interview questions/rounds/panel to use (that's
                         interview_questions) and NOT writing a JD, job posting, or offer
                         letter (that's job_description, and ONLY those three document
                         types — an experience/relieving letter is employee_management, a
                         rejection email is recruitment, not job_description).
  benefits             — health insurance, provident fund, gratuity, perks, allowances,
                         reimbursement claims (e.g. medical expense reimbursement)
  performance          — KPI, appraisal, performance review (mid-year/annual), PIP, rating,
                         self-assessment forms, OKRs, constructive feedback approach,
                         promotion process, 360/peer feedback
  attendance           — attendance tracking, working hours/office hours, timesheet, late
                         arrival, shift timing/changes, WFH and work-from-home policy,
                         unauthorized absence, missed-punch regularization, overtime
                         approval process
  employee_management  — termination, resignation and its notice period, disciplinary action,
                         show-cause notices, grievance, conflict, harassment complaint
                         escalation, layoff/retrenchment process, exit process,
                         experience/relieving letters
  onboarding           — new hire formalities, induction, probation (including how
                         probation confirmation should be communicated), day one checklist,
                         feedback collected FROM NEW HIRES about their own first days/weeks
                         (NOT the same as measuring a training program's effectiveness).
  training             — training programs, certifications to sponsor, L&D, upskilling,
                         development plans, leadership development, mentorship programs,
                         training budget (a training-specific cost, not a general_hr one),
                         measuring a TRAINING PROGRAM's effectiveness, learning platforms,
                         the skill-gap ANALYSIS PROCESS for a team
  compliance           — labor law, employment contract, statutory compliance, HR audit,
                         records required for a statutory audit, documenting workplace
                         safety incidents
  job_description      — writing JDs, role profiles, responsibilities for a position,
                         writing an attractive job posting, what an offer letter should
                         include
  interview_questions  — WHAT QUESTIONS to ask a candidate (technical, behavioral, or about
                         a specific skill), how many interview rounds, interview panel
                         structure, interview guides/scorecards, culture-fit questions
  skills               — WHAT SKILLS are required for a specific HR-managed role or team
                         (not what questions to ask about those skills — that's
                         interview_questions), skill-gap identification for a role
  experience           — experience requirements for a role being hired or evaluated
  general_hr           — HR industry trends/news, market insights, HR department structure,
                         HR metrics/KPIs, HR strategy, HR software/tools — genuinely
                         topic-agnostic questions with NO specific operational anchor. A
                         "how should we..." / "what's a good process for..." / "how do we
                         measure..." question that NAMES a specific topic already covered
                         above (a performance review, a recruitment/screening step, a
                         training program, an interview panel) belongs to THAT intent, not
                         here — general_hr is the fallback ONLY when no specific intent above
                         fits at all.

Non-HR — use when the query is NOT about managing employees, workplace, or HR processes:
  non_hr               — general knowledge, science, cooking, weather, sports, coding tutorials,
                         "how to become X", career advice for personal growth, software development,
                         math, politics, geography, entertainment, anything unrelated to running HR

HARD RULES:
- Output ONLY a JSON object of the exact shape {{"intent": "<label>"}} — no explanation,
  no markdown fences, no other text.
- "How to become a software developer" → non_hr (personal career advice, not HR management)
- Skills/competencies/qualifications/tools required for ANY job role or team
  (e.g. "skills for a QA automation engineer", "what skills does a developer need",
  "key skills for an AI engineer") → skills, even if worded like a job-seeker question —
  do NOT classify these as non_hr. Only "how do I become X" (no role skills asked) is non_hr.
- Experience/seniority required for ANY role (e.g. "experience needed for a data analyst",
  "years of experience for a senior QA") → experience.
- "What skills should I look for when hiring a developer" → skills
- "Write python code / give me code" → non_hr (coding request)
- "Latest HR hiring trends" → general_hr
- "What are the current recruitment market trends" → general_hr
- "How should we structure our HR department" → general_hr
- "What HR metrics or KPIs should we track" → general_hr
- A bare "check my leave" / "check my leaves" (no status word like
  pending/approved/rejected, no date) → leave_balance, matching this app's own
  established convention for that exact ambiguous phrase — not leave_status.
- Metric/benchmark/budget questions naming a specific function's own activity stay
  with that function, never general_hr: "time-to-hire benchmark" → recruitment;
  "training budget per employee" → training; "a fair process for promotion
  decisions" → performance; "documenting workplace safety incidents" → compliance.
- "How should probation confirmation be communicated" → onboarding (probation is
  explicitly an onboarding topic even when the question is about internal
  communication process, not employee_management).
- "What are the job openings currently" → recruitment (not non_hr).
- "What's a good candidate rejection email template" → recruitment, NOT
  job_description — job_description is ONLY a JD, role profile, job posting, or
  offer letter; any other hiring communication (rejection emails) is recruitment.
- "What should an experience letter include" → employee_management, NOT
  job_description — an experience/relieving letter is issued when someone LEAVES,
  unlike an offer letter issued when hiring them.
- "How many working hours per day" / "what are our office hours" → attendance, not
  non_hr — a plain workplace-logistics question is still HR even with no HR jargon.
- "What labor law changes affect our leave policy this year" → compliance, not
  leave_policy — a question about LAW/REGULATORY CHANGES is compliance even when it
  names leave as the affected area; leave_policy is for the leave RULES themselves.
- "How does compensatory off accrual work" → leave_policy, NOT compliance — accrual
  RULES for a leave type are leave_policy; compliance is about labor LAW obligations,
  not how a specific leave type's balance is earned.
- "What's included in the full and final settlement" → payroll, NOT
  employee_management or compliance — the settlement's CONTENTS/CALCULATION is
  payroll's domain even though it happens during offboarding.
- Salary/compensation questions naming ANY job role, tech stack, or location
  (e.g. "AWS DevOps salary in Singapore", "latest salary for a Python developer")
  → salary, even if worded like a job-seeker question — do NOT classify these as non_hr.
  Only treat it as personal career advice (non_hr) when there's no salary/compensation
  figure being asked for (e.g. "how do I become an AWS DevOps engineer").
- "What is latest aws devops salary in Singapore" → salary
- "Salary range for python engineer according to India" → salary
- "Latest salary trends for backend developers in the US" → salary, NOT general_hr —
  the word "trends" alone doesn't mean general_hr when a role/tech/location is named;
  general_hr trends are broad HR-industry/strategy trends with no specific role.
- "How does an annual increment usually work" → salary (increment is a compensation
  topic even when phrased generally, not performance — performance covers the
  review/rating process, not the resulting pay change).
- Greetings and small_talk are NEVER non_hr.
- Do NOT classify as HR just because an HR word appears — judge the full intent.
- "What is my leave balance" / "how many leaves left" → leave_balance (personal, self).
- "I want to apply for leave" / "book leave for tomorrow" → apply_leave (personal, self, action).
- "Is my leave approved" / "status of my leave request" → leave_status (checking an existing request).
- "Do I have any pending leave requests" / "show me my pending leaves" / "view pending leave
  request" / "give my pending leaves" → leave_status, NEVER leave_balance — "pending" describes
  the STATE of an already-submitted request, not a count of days remaining.
- "Cancel my leave" / "withdraw my pending request" / "cancel LR-2041" / "please cancel it" →
  cancel_leave — an instruction to perform the cancellation.
- "Show my cancelled leaves" / "show my cancel leave" / "what leaves have I cancelled" /
  "give me my cancelled leave requests" → leave_status, NEVER cancel_leave — this is asking to
  VIEW/LIST requests that are already in the "cancelled" state, not an instruction to cancel
  anything. The literal word "cancel"/"cancelled" appearing in a "show me"/"what are"/"give me"
  framing is a STATUS FILTER (like "pending" or "approved"), not an action request — only a
  direct imperative ("cancel my leave") is the action intent.
- "What is the sick leave policy" / "how does FMLA work" → leave_policy (general, informational).
- "Am I eligible for casual leave" / "do I qualify for earned leave" → leave_eligibility.
- "Can I take maternity leave" / "am I allowed sick leave" → leave_eligibility. A question
  about whether they QUALIFY is never apply_leave — apply_leave needs a clear intent to
  actually book or submit ("apply for", "book", "request X from <date>").
- leave_eligibility vs leave_policy is personal vs general: "am I eligible for X" is about
  THIS employee (leave_eligibility); "what is the X policy" / "who is eligible for X" asks
  about the rule in general (leave_policy).
- leave_eligibility vs leave_balance is qualification vs quantity: "am I eligible for casual
  leave" (leave_eligibility) vs "how many casual leaves do I have left" (leave_balance).
- "What time did I check in today" / "my shift timing" / "how many hours did I work" → punch_details
  (personal, a specific day's punch/shift/work-hours record — NOT the broader attendance intent).
- "Why was I marked late" / "explain my attendance for Monday" → attendance_explain
  (wants the reasoning behind a classification, not a general attendance question).
- "Show my leave application history" / "show my previous leave applications" → leave_status,
  NEVER conversation_meta — this is about their leave records, not this chat's history.
- "What is the sick leave policy" / "how does FMLA work" → leave_policy (general, informational).
- "What is the work from home policy" / "what's considered an unauthorized absence" →
  attendance, NEVER leave_policy — WFH and absence rules are not a leave TYPE.
- A plain-language HR question with no obvious "HR" vocabulary is still HR, never non_hr:
  "how is professional tax deducted" → payroll; "how do I claim medical reimbursement" →
  benefits; "what records are needed for a statutory audit" → compliance; "what's a good
  format for a lunch-and-learn" / "what learning platforms work well for remote teams" →
  training; "how should a show-cause notice be worded" → employee_management.
- "What questions should I ask..." in a hiring/interview context → interview_questions, even
  when the questions are about a specific skill or technology (e.g. "what technical
  questions suit a React developer" → interview_questions, not skills).
- Writing/content questions about a hiring DOCUMENT (a JD, a job posting, an offer letter)
  → job_description, even though sourcing/screening/background-checks for the SAME hire
  is recruitment: "what should an offer letter include" / "how do we write an attractive
  job posting" → job_description. "how should we structure a technical interview panel" /
  "how many interview rounds should a senior role have" / "what questions reveal culture
  fit" → interview_questions, not recruitment.
- A "how should we structure/measure/run..." question naming a specific topic already listed
  above stays that intent, not general_hr: "what KPIs should a sales manager be rated on" →
  performance; "what's the best way to source passive candidates" → recruitment; "how do we
  identify skill gaps across the org" → training.

{awaited_directive}{followup_directive}{context_block}{pending_flow_hint}Current User Query: {query}"""


# Every label the prompt above can legally return — must stay in sync with it.
# Passed to classify_intent_structured() so a hallucinated/off-list value from
# the LLM never becomes state["intent"] silently (server-side enum validation
# on top of JSON-mode output — see ai_service.classify_intent_structured).
_VALID_INTENT_LABELS = frozenset({
    "greeting", "small_talk", "capabilities_inquiry", "conversation_meta",
    "leave_balance", "apply_leave", "leave_status", "cancel_leave",
    "leave_eligibility", "leave_policy",
    "payroll", "salary", "recruitment", "benefits", "performance",
    "attendance", "punch_details", "attendance_explain", "regularisation",
    "employee_management", "onboarding", "training",
    "compliance", "job_description", "interview_questions", "skills",
    "experience", "general_hr", "non_hr",
})


# ── Node 1+2: Moderation + Intent in parallel ────────────────────────────────
# Runs OpenAI moderation and intent classification concurrently with
# asyncio.gather, saving ~200-400ms compared to sequential execution.
_DATABASE_WIRED_INTENTS = frozenset({"leave_balance", "apply_leave", "leave_status"})
_DATABASE_CAPABLE_INTENTS = frozenset({"attendance", "payroll", "salary", "performance"})


def _is_database_related(intent: str) -> bool:
    return intent in _DATABASE_WIRED_INTENTS or intent in _DATABASE_CAPABLE_INTENTS


def _describe_awaited_leave_slot(slots: dict) -> Optional[str]:
    if slots.get("step") == "awaiting_confirmation":
        return "whether to CONFIRM submitting their leave request"
    if not slots.get("leave_type"):
        return "the TYPE of leave they want (e.g. casual, sick, earned)"
    if not slots.get("from_date") or not slots.get("to_date"):
        return "the DATES for their leave"
    if (slots.get("leave_type") in _SESSION_TYPE_REQUIRED_LEAVE_TYPES
            and _is_single_day(slots) and not slots.get("session_type_slug")):
        return "whether it's a FULL DAY or HALF DAY"
    if _is_single_day(slots) and slots.get("session_type_slug") == "half_day":
        return "whether it's the FIRST HALF or SECOND HALF of the day"
    if not slots.get("reason"):
        return "the REASON for their leave request"
    return "a detail of their in-progress leave application"


def _describe_awaited_cancel_step(cancel_state: dict) -> str:
    step = cancel_state.get("step")
    if step == "awaiting_selection":
        return "which of several matching leave requests they want to cancel"
    if step == "declined":
        return "whether they'd like to go ahead and cancel that same leave request after all"
    # awaiting_confirmation (the common case) and any other/unrecognized step.
    return "whether to CONFIRM cancelling this leave request"


async def classify_node(state: HRState, writer: StreamWriter) -> dict:
    query = state["query"].strip()
    recent = state.get("context", [])[-4:]
    has_hr_context = bool(recent) and _context_has_hr_signal(recent)
    has_non_hr_trigger = any(t in query.lower() for t in _NON_HR_TRIGGERS)
    pre_intent = state.get("intent", "general")
    usage_events = list(state.get("usage_events", []))
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    # Set only when the mid-flow regularisation block below falls through to
    # full classification (fast_classify + the deterministic checks couldn't
    # confidently decide) — informs the LLM prompt built further down so it
    # can recognize a genuine continuation (a bare "yes"/"10am to 7pm") that
    # carries no keyword of its own, instead of guessing blind.
    pending_regularisation_hint = ""
    has_date_expression = date_resolver.mentions_date_expression(query)

    custom_check = check_custom_guardrail(query)
    if custom_check["blocked"]:
        logger.warning("[Guardrail:Custom] BLOCKED | category=%s | query=%s",
                       custom_check["category"], query[:80])
        writer({
            "type": "guardrail", "stage": "input", "status": "failed",
            "categories": [custom_check["category"]],
            "message": "I'm not able to help with that. If you have an HR-related question — such as policies, payroll, leave, or recruitment — I'm happy to assist.",
        })
        return {"moderation": custom_check, "intent": "unknown", "is_hr": False, "error": "flagged",
                "is_database_related": False, "has_date_expression": has_date_expression,
                "usage_events": usage_events}

    # ── Fast-path 0.2: reply to a pending "which leave did you mean?" ───────
    # The previous turn asked the user to pick between multiple pending
    # requests (e.g. "is my leave approved" with 2+ candidates — see
    # leave_action_service's leave_status branch). A reply like "the casual
    # leave one" or "the 30th" has no "leave"/"pending"/"status" keyword and
    # won't classify as leave_status on its own — route straight back so
    # leave_action_service can resolve it against the stored candidates.
    if leave_disambiguation_state.get_candidates(
        state.get("company_id"), state.get("conversation_id", "")
    ):
        logger.info("[Graph] Reply to pending leave-disambiguation question — routing to leave_action_node")
        writer({"type": "intent", "intent": "leave_status", "is_hr": True})
        return {"moderation": {}, "intent": "leave_status", "is_hr": True, "error": None,
                "usage_events": usage_events}

    # ── Fast-path 0.3: reply to a pending "which leaves?" clarification ─────
    # The previous turn asked "are you asking about your leave balance, all
    # your applied leaves, or approved/cancelled/rejected ones?" (see
    # leave_action_service's leave_status branch) — interpret a short,
    # recognizable reply directly instead of re-running full classification.
    # The reply is rewritten into a natural-language query carrying the
    # resolved category, leave type, AND date range — each preferring what
    # THIS reply mentions, falling back to whatever was captured on the
    # ORIGINAL ambiguous turn (e.g. "sick" + "approved" + "last month" ->
    # "sick approved leaves from 2026-07-20 to 2026-08-20"), so
    # leave_action_node's existing extraction functions re-derive everything
    # with no new plumbing. An unrecognized reply
    # clears the state and falls through to normal classification rather
    # than getting stuck waiting for an answer that never comes in the
    # expected shape.
    pending_history_clarify = leave_history_clarify_state.get_state(
        state.get("company_id"), state.get("conversation_id", "")
    )
    if pending_history_clarify is not None:
        resolved = _resolve_leave_history_clarification(query)
        leave_history_clarify_state.clear_state(
            state.get("company_id"), state.get("conversation_id", "")
        )
        if resolved:
            rewritten_query = _rewrite_query_for_history_clarify_resolution(
                resolved, query, pending_history_clarify,
            )
            intent = "leave_balance" if resolved == "leave_balance" else "leave_status"
            logger.info(f"[Graph] 'Which leaves' clarification resolved -> {resolved} (query rewritten to {rewritten_query!r})")
            writer({"type": "intent", "intent": intent, "is_hr": True})
            return {"moderation": {}, "intent": intent, "is_hr": True, "error": None,
                    "usage_events": usage_events, "query": rewritten_query}

    # ── Fast-path 0.4: reply to a pending bare-leave-type clarification ─────
    # The previous turn saw a bare mention of a single supported leave type
    # ("sick leave", with no question wording — see the leave_policy check
    # near the end of this function) and asked "would you like your
    # balance/eligibility/apply/status for it?" instead of dumping a generic
    # LLM-written policy essay. Interpret a short, recognizable reply
    # directly. The type named in THIS reply wins over the one stored from
    # the original turn (mirrors Fast-path 0.3's preference order), so
    # "casual balance" after being asked about sick leave still answers
    # casual. An unrecognized reply clears the state and falls through to
    # normal classification rather than getting stuck.
    pending_leave_type_clarify = leave_type_clarify_state.get_state(
        state.get("company_id"), state.get("conversation_id", "")
    )
    if pending_leave_type_clarify is not None:
        resolved = _resolve_leave_type_clarification(query)
        leave_type_clarify_state.clear_state(
            state.get("company_id"), state.get("conversation_id", "")
        )
        if resolved:
            reply_leave_types = _extract_leave_type_filters(query)
            leave_type_slug = reply_leave_types[0] if reply_leave_types else pending_leave_type_clarify.get("leave_type_slug")
            type_word = _SLUG_TO_LEAVE_TYPE_WORD.get(leave_type_slug, "leave")
            rewritten_query = _rewrite_query_for_leave_type_clarify_resolution(resolved, type_word)
            logger.info(f"[Graph] Leave-type clarification resolved -> {resolved} (query rewritten to {rewritten_query!r})")
            writer({"type": "intent", "intent": resolved, "is_hr": True})
            return {"moderation": {}, "intent": resolved, "is_hr": True, "error": None,
                    "usage_events": usage_events, "query": rewritten_query}

    # ── Fast-path 0.5: mid-flow apply-leave conversation already in progress ─
    # A reply like "March 10 to March 12" or "yes, submit" won't keyword-match
    # any intent (fast_classify returns None) — must route straight to
    # leave_action_node without re-classifying, or the slot-filling flow
    # breaks on turn 2+.
    #
    # But a clear interruption onto a DIFFERENT topic — "how many types of
    # leave do I have", "what's my leave status", or a completely unrelated
    # question like "what is the salary range for AI engineer" — must NOT be
    # swallowed as if it were slot-filling input; that either re-asks the
    # same question forever or, worse, silently answers the wrong thing (a
    # live bug: a salary question got treated as slot input and produced a
    # leave confirmation prompt instead of an answer). Any CONFIDENT
    # fast_classify result other than apply_leave itself is treated as an
    # interruption and answered directly — EXCEPT a bare leave-type reply
    # like "casual leave" / "sick leave" — the single most common, correct
    # reply during slot collection — which collides with leave_policy's own
    # keyword list at full confidence. Blanket-excluding leave_policy avoided
    # that collision but introduced a different bug: a genuine question like
    # "what is the FMLA policy" asked mid-flow also classifies as
    # leave_policy, so it got silently absorbed into slot extraction too —
    # extraction finds no leave type in it, and the user's actual question
    # was never answered, just re-prompted for the missing slot forever.
    # _looks_like_leave_policy_question distinguishes the two: a real
    # question carries an interrogative/explanatory marker a bare slot
    # answer never does. leave_action_node answers genuine interruptions
    # without touching the in-progress slots, so the apply flow can resume
    # after.

    _MID_FLOW_NON_INTERRUPTING_INTENTS = {"apply_leave"}

    # ── CHANGED: check regularization slots FIRST, and treat it as the
    # more "current" flow — if it's pending, a stale leave slot from
    # earlier in the conversation must not be allowed to steal the turn.
    existing_regularization_slots = slot_store.get_slots("regularization", company_id, conversation_id)
    if existing_regularization_slots:
        entries = existing_regularization_slots.get("entries") or []

        has_free_text_pending = any(
            e.get(REGULARIZATION_CONFIG.entry_key) and any(
                f != REGULARIZATION_CONFIG.entry_key and not e.get(f)
                for f in REGULARIZATION_CONFIG.entry_fields
            )
            for e in entries
        )

        # fast_classify is cheap (regex/keyword only, no LLM call) — compute
        # it unconditionally, up front, rather than only running it once a
        # message already "looks like a genuine query" per
        # _looks_like_genuine_query's narrow leading-word test (show/check/
        # what/why/is/are/...). That gate used to run BEFORE fast_classify
        # ever saw the message, so plain new-topic phrasing with no leading
        # question word — e.g. "attendance last week" — never reached
        # fast_classify at all and was swallowed as if it were the pending
        # free-text answer, silently corrupting the in-progress entry (the
        # previously prefilled check-in/check-out times were visibly wiped
        # to empty on the resulting review card — confirmed live). Running
        # fast_classify first, and treating a confident result as decisive
        # regardless of what's still pending, closes that gap for every
        # phrasing instead of only the ones the marker regex recognizes.
        interrupt_intent, interrupt_is_hr, interrupt_confidence = fast_classify(query)

        _REG_MID_FLOW_NON_INTERRUPTING_INTENTS = {"regularisation"}
        is_bare_leave_type_reply = (
            interrupt_intent == "leave_policy" and not _looks_like_leave_policy_question(query)
        )
        is_confident_interruption = (
            interrupt_intent
            and interrupt_intent not in _REG_MID_FLOW_NON_INTERRUPTING_INTENTS
            and interrupt_confidence >= 0.5
            and not is_bare_leave_type_reply
        )

        if is_confident_interruption:
            logger.info(f"[Graph] Mid-flow interruption detected: {interrupt_intent} — answering without disturbing regularisation slots")
            writer({"type": "intent", "intent": interrupt_intent, "is_hr": interrupt_is_hr})
            return {"moderation": {}, "intent": interrupt_intent, "is_hr": interrupt_is_hr, "error": None,
                    "usage_events": usage_events}

        if has_free_text_pending:
            # fast_classify found nothing confident. A bare slot answer like
            # "10am to 7pm" or a real reason ("forgot to punch out") never
            # hits a keyword either, so the safe default is to treat it as
            # the pending answer — UNLESS the message itself reads like a
            # fresh question (_looks_like_genuine_query), in which case fall
            # through below rather than swallowing it.
            if not _looks_like_genuine_query(query):
                logger.info("[Graph] Mid-flow regularisation: free-text answer detected — skipping interrupt check")
                writer({"type": "intent", "intent": "regularisation", "is_hr": True})
                return {"moderation": {}, "intent": "regularisation", "is_hr": True, "error": None,
                        "usage_events": usage_events}
        else:
            # Nothing left pending — every entry is already complete
            # (awaiting confirmation, or left behind "_failed" after a
            # rejected submission — see slot_flow.py's failed-entry retry
            # comment, which never expires). With no field actually waiting
            # on an answer, the ONLY messages that should still route back
            # into regularisation_node are an explicit confirm/cancel;
            # anything else fast_classify didn't recognize is a fresh,
            # unrelated turn, not a continuation.
            if REGULARIZATION_CONFIG.is_explicit_cancel(query) or _REG_MID_FLOW_CONTINUATION_RE.search(query):
                logger.info("[Graph] Mid-flow regularisation slots found — routing to regularisation_node")
                writer({"type": "intent", "intent": "regularisation", "is_hr": True})
                return {"moderation": {}, "intent": "regularisation", "is_hr": True, "error": None,
                        "usage_events": usage_events}

        logger.info(
            "[Graph] Regularisation slots present but query doesn't look like a "
            "continuation — falling through to full classification (LLM-informed "
            "of the pending request) instead of assuming regularisation | query=%r",
            query[:80],
        )
        pending_regularisation_hint = _build_regularisation_pending_hint(entries, has_free_text_pending)


    existing_leave_slots = leave_slot_service.get_slots(company_id, conversation_id)
    if existing_leave_slots:
        interrupt_intent, interrupt_is_hr, interrupt_confidence = fast_classify(query)
        is_bare_leave_type_reply = (
            interrupt_intent == "leave_policy" and not _looks_like_leave_policy_question(query)
        )
        # "cancel" mid-apply-flow is ambiguous: it almost always means
        # "discard THIS in-progress application", not "look up a different,
        # already-submitted leave to cancel" — but fast_classify can't tell
        # the difference, it just sees the keyword "cancel" and confidently
        # returns cancel_leave. Live bug: mid-application "cancel"/"cancel
        # this" got treated as a confident interruption into the cancel_leave
        # flow (asking to pick a PENDING submitted leave to cancel) instead
        # of discarding the draft — and once there, a decline reply ("Keep
        # Request") could then get misread by the fallback classifier below
        # as an affirmative answer to the apply-flow's own stale "shall I
        # submit this?" prompt, silently submitting a leave nobody actually
        # confirmed. Only an EXPLICIT reference number ("cancel LR-2041") is
        # trusted to mean a different, already-submitted request; anything
        # else stays in the apply flow, where leave_action_service.py's own
        # discard check (checked before slot extraction even runs) handles
        # it deterministically, regardless of which slot is still missing.
        is_ambiguous_cancel_during_apply = (
            interrupt_intent == "cancel_leave" and not _extract_request_id(query)
        )
        # A BARE "cancel" (no "leave"/"request"/"application" object word)
        # never matches fast_classify's _CANCEL_LEAVE_PATTERNS in the first
        # place — those regexes require that object word within 20 chars —
        # so interrupt_intent comes back None here, and
        # is_ambiguous_cancel_during_apply above (which only fires when
        # fast_classify already said "cancel_leave") never engages either.
        # Live bug: a bare "cancel" reply to the awaiting_confirmation
        # prompt then fell through to the LLM fallback classifier below,
        # which — seeing only "cancel" with no other signal — guessed
        # cancel_leave and routed into leave_action_node's cancel-SEARCH
        # branch (fetch existing requests, ask which one) instead of ever
        # reaching leave_action_service.py's deterministic discard check
        # (_is_declining_or_cancelling, checked before slot extraction),
        # which does correctly match a bare \bcancel\b. Checked here so any
        # decline/cancel reply at the confirmation step — not just ones
        # fast_classify already recognized — stays in the apply flow.
        is_confirmation_decline = (
            existing_leave_slots.get("step") == "awaiting_confirmation"
            and _is_declining_or_cancelling(query)
        )
        is_awaiting_reason_only = bool(
            not existing_leave_slots.get("reason")
            and existing_leave_slots.get("leave_type")
            and existing_leave_slots.get("from_date")
            and existing_leave_slots.get("to_date")
            and existing_leave_slots.get("step") != "awaiting_confirmation"
        )
        is_confident_interruption = (
            interrupt_intent
            and interrupt_intent not in _MID_FLOW_NON_INTERRUPTING_INTENTS
            and interrupt_confidence >= 0.5
            and not is_bare_leave_type_reply
            and not is_ambiguous_cancel_during_apply
            and not is_confirmation_decline
        )
        if is_confident_interruption:
            logger.info(f"[Graph] Mid-flow interruption detected: {interrupt_intent} — answering without disturbing apply-leave slots")
            writer({
                "type": "intent", "intent": interrupt_intent, "is_hr": interrupt_is_hr,
                "is_database_related": _is_database_related(interrupt_intent),
                "has_date_expression": has_date_expression,
            })
            return {"moderation": {}, "intent": interrupt_intent, "is_hr": interrupt_is_hr, "error": None,
                    "is_database_related": _is_database_related(interrupt_intent),
                    "has_date_expression": has_date_expression, "usage_events": usage_events}

        is_confident_continuation = (
            interrupt_intent in _MID_FLOW_NON_INTERRUPTING_INTENTS
            or is_bare_leave_type_reply
            or is_awaiting_reason_only
            or is_ambiguous_cancel_during_apply
            or is_confirmation_decline
        )
        if not is_confident_continuation:
            awaited_slot = _describe_awaited_leave_slot(existing_leave_slots)
            intent_prompt = _build_intent_prompt(
                query, recent, has_hr_context, awaited_slot_description=awaited_slot,
            )
            try:
                detected, intent_usage, _classification_failed = await classify_intent_structured(intent_prompt, _VALID_INTENT_LABELS)
            except Exception as e:
                logger.exception(f"[Graph] Mid-flow fallback classification failed: {e}")
                detected, intent_usage = "apply_leave", None
            if intent_usage:
                usage_events.append({"source": "intent", "usage": intent_usage})

            is_bare_leave_type_reply_llm = (
                detected == "leave_policy" and not _looks_like_leave_policy_question(query)
            )
            if detected not in _MID_FLOW_NON_INTERRUPTING_INTENTS and not is_bare_leave_type_reply_llm:
                is_hr_detected = detected != "non_hr"
                if detected == "non_hr":
                    logger.warning(
                        "[Graph] Mid-flow leave conversation possibly derailed by fallback "
                        "classifier | awaited=%r query=%r detected=%s",
                        awaited_slot, query[:80], detected,
                    )
                logger.info(f"[Graph] Mid-flow interruption detected via fallback classification: {detected} — answering without disturbing apply-leave slots")
                writer({
                    "type": "intent", "intent": detected, "is_hr": is_hr_detected,
                    "is_database_related": _is_database_related(detected),
                    "has_date_expression": has_date_expression,
                })
                return {"moderation": {}, "intent": detected, "is_hr": is_hr_detected, "error": None,
                        "is_database_related": _is_database_related(detected),
                        "has_date_expression": has_date_expression, "usage_events": usage_events}


        logger.info("[Graph] Mid-flow apply-leave slots found — routing to leave_action_node")
        writer({
            "type": "intent", "intent": "apply_leave", "is_hr": True,
            "is_database_related": True, "has_date_expression": has_date_expression,
        })
        return {"moderation": {}, "intent": "apply_leave", "is_hr": True, "error": None,
                "is_database_related": True, "has_date_expression": has_date_expression,
                "usage_events": usage_events}

    # ── Fast-path 0.6: mid-flow cancel-leave conversation already in progress ─
    # A selection reply ("2", "LR-2041") or a confirmation reply ("yes",
    # "Confirm Cancellation") won't keyword-match cancel_leave on its own —
    # must route straight to leave_action_node, same reasoning as Fast-path
    # 0.5 for apply-leave. A confident fast_classify result for something
    # else is treated as an interruption and answered directly, leaving the
    # cancel state untouched so the flow can resume afterward (mirrors
    # apply-leave's resume_reminder pattern in leave_action_service.py).
    _CANCEL_MID_FLOW_NON_INTERRUPTING_INTENTS = {"cancel_leave"}
    existing_leave_cancel_state = leave_cancel_state.get_state(
        state.get("company_id"), state.get("conversation_id", "")
    )
    if existing_leave_cancel_state:
        # "awaiting_reason" is the one step where the employee's ENTIRE
        # reply IS the answer, free text with no keyword expected at all
        # (leave_action_service.py's reason-turn branch takes it verbatim —
        # "the employee's whole reply here IS the reason, no extraction
        # needed"). Live bug: a reason like "hello, forgot to inform" or a
        # bare "hi" hits fast_classify's single-keyword greeting match at
        # full confidence, so the interruption check below misread it as a
        # topic switch and answered with a greeting instead of accepting it
        # as the cancellation reason. Skip interruption detection entirely
        # at this step — a genuine change of heart ("never mind"/"keep it")
        # is still honored, just downstream by leave_action_service.py's own
        # _is_strong_cancel_decline check, not by fast_classify here.
        if existing_leave_cancel_state.get("step") != "awaiting_reason":
            interrupt_intent, interrupt_is_hr, interrupt_confidence = fast_classify(query)
            is_bare_leave_type_reply = (
                interrupt_intent == "leave_policy" and not _looks_like_leave_policy_question(query)
            )
            is_confident_interruption = (
                interrupt_intent
                and interrupt_intent not in _CANCEL_MID_FLOW_NON_INTERRUPTING_INTENTS
                and interrupt_confidence >= 0.5
                and not is_bare_leave_type_reply
            )
            if is_confident_interruption:
                logger.info(f"[Graph] Mid-flow interruption detected: {interrupt_intent} — answering without disturbing cancel-leave state")
                writer({"type": "intent", "intent": interrupt_intent, "is_hr": interrupt_is_hr})
                return {"moderation": {}, "intent": interrupt_intent, "is_hr": interrupt_is_hr, "error": None,
                        "usage_events": usage_events}

            # fast_classify's closed keyword lists miss plenty of genuinely
            # different questions ("check leave eligibility", "am I
            # eligible for casual leave" phrased more colloquially, etc.) —
            # live bug report: a user who changed their mind mid-cancel-
            # confirmation and asked something else entirely kept getting
            # the same "Sorry, I didn't catch that — would you like me to
            # go ahead and cancel...?" re-ask instead of an answer, because
            # nothing beyond fast_classify's own confident guess was ever
            # consulted here (unlike apply-leave's own mid-flow, Fast-path
            # 0.5 above, which always falls back to the real classifier).
            # A bare "yes"/"no"/"2"/"LR-2041" reply carries no keyword
            # either, so it MUST also go through this same fallback rather
            # than being assumed — exactly the same tradeoff
            # leave_action_service.py's apply-branch confirmation step
            # already makes (see _build_intent_prompt's awaited_directive
            # and _describe_awaited_leave_slot for the apply-side
            # precedent); the awaited-context prompt is what lets the model
            # correctly read a bare "yes" as continuing THIS flow instead
            # of guessing it's off-topic.
            awaited_cancel_step = _describe_awaited_cancel_step(existing_leave_cancel_state)
            intent_prompt = _build_intent_prompt(
                query, recent, has_hr_context,
                awaited_slot_description=awaited_cancel_step,
                awaited_context_label="a pending leave-cancellation request",
                awaited_target_intent="cancel_leave",
            )
            try:
                detected, intent_usage, _classification_failed = await classify_intent_structured(intent_prompt, _VALID_INTENT_LABELS)
            except Exception as e:
                logger.exception(f"[Graph] Mid-flow cancel-leave fallback classification failed: {e}")
                detected, intent_usage = "cancel_leave", None
            if intent_usage:
                usage_events.append({"source": "intent", "usage": intent_usage})

            is_bare_leave_type_reply_llm = (
                detected == "leave_policy" and not _looks_like_leave_policy_question(query)
            )
            if detected not in _CANCEL_MID_FLOW_NON_INTERRUPTING_INTENTS and not is_bare_leave_type_reply_llm:
                is_hr_detected = detected != "non_hr"
                logger.info(f"[Graph] Mid-flow interruption detected via fallback classification: {detected} — answering without disturbing cancel-leave state")
                writer({"type": "intent", "intent": detected, "is_hr": is_hr_detected})
                return {"moderation": {}, "intent": detected, "is_hr": is_hr_detected, "error": None,
                        "usage_events": usage_events}

        logger.info("[Graph] Mid-flow cancel-leave state found — routing to leave_action_node")
        writer({"type": "intent", "intent": "cancel_leave", "is_hr": True})
        return {"moderation": {}, "intent": "cancel_leave", "is_hr": True, "error": None,
                "usage_events": usage_events}

    # ── REMOVED: Fast-path 2 (short fragments ≤4 words → 'follow_up') ───────
    # It short-circuited to follow_up — which routes to generic chat — BEFORE
    # either classifier ran, on the assumption that "a wrong call here has low
    # consequence". Three live bugs disproved that:
    #
    #   "apply for tomorrow"        (3w) -> follow_up -> the LLM cheerfully drafted
    #                                      a leave-request email. Nothing was ever
    #                                      submitted to erp-api, but the user is
    #                                      told "sure, you can apply for tomorrow".
    #   "meri saari leaves dikhao"  (4w) -> follow_up -> generic chat. Every keyword
    #                                      list here is English-only, so Hinglish
    #                                      scores nothing and looked like a fragment.
    #   "meri leave balance batao"  (4w) -> follow_up EVEN THOUGH fast_classify
    #                                      returns leave_balance at confidence 1.0 —
    #                                      this path returned before consulting it.
    #
    # The saving was one classify call (~1.5k prompt tokens, ~200-400ms) on short
    # follow-ups. The cost was any short actionable query, in any language, being
    # answered by an ungrounded LLM instead of reaching the node that fetches real
    # data. Genuine continuations ("what about India?") classify correctly anyway —
    # followup_directive in the intent prompt already tells the model to read a
    # short refinement as the matching HR intent — so the shortcut was buying
    # latency, never correctness. Paraphrase and multilingual input are precisely
    # what the LLM classifier is for; blocking it to save 300ms is the wrong trade.
    #
    # MERGE NOTE (leaves_kumargirinath): that branch kept Fast-path 2 and added a
    # guard, `not (pre_intent and pre_intent != "general")`, so it stands down
    # whenever fast_classify already matched something specific. That fixes the
    # third bug above ("meri leave balance batao"), but not the second: every
    # keyword list feeding fast_classify is English-only, so Hinglish scores
    # nothing, pre_intent stays empty, the guard never fires, and the query still
    # lands in generic chat. Removal is kept for that reason. Fast-path 0.6 above
    # is unaffected — it keys off cancel state, not word count.

    # ── Moderation + structured intent classification, always ───────────────
    # fast_classify's ≥0.5-confidence result (pre_intent, computed in main.py
    # before the graph even runs) is no longer trusted as the final answer —
    # it used to skip this LLM call entirely ("Fast-path 1"), which is exactly
    # what let bugs like the "check my leave quota" misroute (fast_classify
    # confidently said apply_leave; nothing ever double-checked it) reach the
    # user. fast_classify's keyword/regex lists are closed by construction and
    # will always miss some real paraphrase — the fix isn't chasing every gap
    # with more regex, it's never letting the fast path decide alone. Every
    # remaining query is now confirmed by the real, structured, enum-validated
    # LLM classifier (classify_intent_structured), which also folds in what
    # used to be the separate check_hr_relevance gate (non_hr is just one of
    # its labels).

    async def _moderate():
        if ACTIVE_LLM_PROVIDER != "openai":
            return {}
        return await _check_moderation(query)

    intent_prompt = _build_intent_prompt(query, recent, has_hr_context, pending_flow_hint=pending_regularisation_hint)
    try:
        moderation_result, (detected, intent_usage, classification_failed) = await asyncio.gather(
            _moderate(),
            classify_intent_structured(intent_prompt, _VALID_INTENT_LABELS),
        )
    except Exception as e:
        logger.exception(f"[Graph] classify_node failed: {e}")
        writer({"type": "error", "message": "Sorry, I'm having trouble understanding that right now — could you try again in a moment?"})
        return {"moderation": {}, "intent": "unknown", "is_hr": False, "error": str(e),
                "is_database_related": False, "has_date_expression": has_date_expression,
                "usage_events": usage_events}

    if intent_usage:
        usage_events.append({"source": "intent", "usage": intent_usage})

    if moderation_result.get("flagged"):

        categories = moderation_result.get("categories", [])
        is_punch_wording_false_positive = (
            categories == ["violence"] and detected in ("punch_details", "attendance")
        )
        if not is_punch_wording_false_positive:
            logger.warning(f"[Guardrail:Input] BLOCKED | categories={categories}")
            writer({
                "type": "guardrail",
                "stage": "input",
                "status": "failed",
                "categories": categories,
                "message": "Sorry, I'm not able to help with that message — could you rephrase it?",
            })
            return {"moderation": moderation_result, "intent": "unknown", "is_hr": False, "error": "flagged",
                    "usage_events": usage_events}
        logger.info(
            "[Guardrail:Input] Overriding moderation 'violence' false-positive for %s query: %r",
            detected, query[:80],
        )

    # A genuine "couldn't classify this at all" (LLM call broke, or returned
    # something off the valid-label list) — as opposed to the LLM correctly
    # picking general_hr on its own merits, which still gets a real answer
    # below. Previously this silently fell through to general_hr/
    # hr_response_node with no acknowledgment that classification struggled
    # at all, so a genuinely unclear message could get answered as if it
    # were a normal broad HR question. Now it gets an honest, humanized nudge
    # to rephrase instead of a guessed answer. Checked after the moderation
    # block above so a genuinely flagged message still gets that response,
    # not this one.
    if classification_failed:
        logger.warning(f"[Graph] classification could not confidently label query: {query[:120]!r}")
        writer({
            "type": "error",
            "message": "Sorry, I'm not sure what you're asking — could you rephrase that, or tell me a "
                       "bit more about what you need (like leave, attendance, or payroll)?",
        })
        return {"moderation": moderation_result, "intent": "unknown", "is_hr": False, "error": "flagged",
                "is_database_related": False, "has_date_expression": has_date_expression,
                "usage_events": usage_events}

    if ACTIVE_LLM_PROVIDER == "openai":
        writer({"type": "guardrail", "stage": "input", "status": "passed"})


    is_short_fragment = len(query.split()) <= 5
    if detected == "non_hr" and has_hr_context and not has_non_hr_trigger and is_short_fragment:
        logger.warning("[Graph] LLM returned non_hr despite HR context — overriding to 'follow_up'")
        detected = "follow_up"

    is_hr = detected != "non_hr"

    # A bare mention of a single supported leave type ("sick leave", no
    # question wording — see _looks_like_leave_policy_question, same
    # deterministic check used for the mid-flow interruption cases above)
    # classifies as leave_policy, which has no dedicated node and used to
    # fall straight through to hr_response_node's free-form LLM answer — a
    # generic policy essay nobody asked for when what they almost always
    # want is their balance, eligibility, to apply, or their status. Ask
    # instead, and remember the type so Fast-path 0.4 (above) can resolve
    # the reply next turn. Left alone (falls through as before) when
    # _extract_leave_type_filters doesn't match exactly one of the platform's
    # actionable leave types — including a genuine question ("what is the
    # sick leave policy"), which _looks_like_leave_policy_question already
    # excludes, and multi-type or unsupported-type mentions ("maternity
    # leave", "sick and casual leave") this flow has nothing concrete to
    # offer for.
    if detected == "leave_policy" and not _looks_like_leave_policy_question(query):
        leave_type_filters = _extract_leave_type_filters(query)
        if len(leave_type_filters) == 1:
            leave_type_slug = leave_type_filters[0]
            type_word = _SLUG_TO_LEAVE_TYPE_WORD.get(leave_type_slug, "leave")
            leave_type_clarify_state.set_state(
                state.get("company_id"), state.get("conversation_id", ""),
                {"leave_type_slug": leave_type_slug},
            )
            message = (
                f"Would you like to know your {type_word} leave balance, check your "
                f"{type_word} leave eligibility, apply for {type_word} leave, or see "
                f"your {type_word} leave application status?"
            )
            logger.info(f"[Graph] Bare leave-type mention ({leave_type_slug}) — asking clarifying question")
            writer({
                "type": "done", "intent": "leave_policy", "is_hr": True,
                "data": {"answer": message}, "message": message,
                "usage_events": usage_events,
            })
            return {"moderation": moderation_result, "intent": "leave_type_clarify", "is_hr": True,
                    "error": None, "is_database_related": False,
                    "has_date_expression": has_date_expression, "usage_events": usage_events,
                    "response_text": message}

    if pre_intent and pre_intent != "general" and pre_intent != detected:
        logger.warning(
            "[Classify] fast_classify/LLM disagreement | fast_classify=%s llm=%s query=%r",
            pre_intent, detected, query[:120],
        )
        # leave_balance vs leave_status used to get an active clarifying
        # question here specifically for this disagreement pair — superseded
        # by leave_action_service's own unconditional "which leaves?" check
        # (Fast-path 0.3 above / the leave_status branch), which covers this
        # exact ambiguity plus the broader approved/cancelled/rejected/all
        # case, regardless of whether the classifier disagreed at all. Every
        # other disagreement pair stays silent (the LLM's answer wins) — see
        # leave_history_clarify_state.py.

    is_database_related = _is_database_related(detected)
    logger.info(f"[Graph] Intent={detected} | is_hr={is_hr} | is_database_related={is_database_related}")
    writer({
        "type": "intent", "intent": detected, "is_hr": is_hr,
        "is_database_related": is_database_related, "has_date_expression": has_date_expression,
    })
    return {"moderation": moderation_result, "intent": detected, "is_hr": is_hr, "error": None,
            "is_database_related": is_database_related, "has_date_expression": has_date_expression,
            "usage_events": usage_events}
