"""Shape tests for the mid-flow regularisation guard.

These live here, not in hr_graph.py where they were written, because
classify_node.py needs them too and cannot import hr_graph — hr_graph
imports classify_node, so the dependency only runs one way. hr_graph
re-exports both functions, so `from services.hr_graph import
_looks_like_other_hr_topic` keeps working for existing callers and tests.

Nothing here touches state or the graph: they are pure string tests over
the user's message, used to decide whether a reply during a pending
regularisation entry is that entry's content or a genuine change of topic.
"""
import re

# erp-api's own refusal, verbatim, for GET /api/v1/ai/regularizations?type=all
# from a caller who is neither Manager nor HR. Every "let me see someone
# else's regularization requests" refusal uses it — the ownership guard, the
# approval node's own role gate, and erp-api's answer itself — so the user
# gets the same sentence whichever layer refuses first. Lives here because
# both ownership_guard and regularisation_approval import this module and
# neither can import the other.
TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE = (
    "Only Manager/HR users can view team regularization requests."
)

# Nobody - manager, HR or admin - applies for someone else's attendance: each
# employee raises their own regularization. Live, "i want to apply
# regularization for my team" opened the caller's OWN apply form ("which
# date(s) would you like to regularize?").
APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE = (
    "You can't apply regularization for another team member - each employee "
    "applies for their own attendance. You can apply regularization for yourself: "
    "tell me the date(s), e.g. \"apply regularization for 3 Oct\"."
)
APPLY_FOR_OTHERS_INTENT = "regularization_other_employee"

# ── "Yes, go on" at any point of the regularization flow ────────────────────
# One definition for every place the flow waits for a go-ahead: "Reply apply
# now" after the eligibility check, and "Shall I go ahead and submit this?"
# once the details are complete. Live, each point knew a different short list
# — "apply" was refused at the first ("Leave or Regularization?") and the
# second left "yes" to the LLM — so a plain go-ahead could stall either one.
#
# WHOLE-MESSAGE only, built from go-ahead words (typos with repeated letters
# tolerated: "yess", "okk"), optionally joined ("yes please go ahead", "ok
# submit it", "confirm & submit") and followed by it/this/now. A reply that
# says anything more ("yes but change the time to 6") is NOT this — it goes
# to the flow's own extraction, which can apply the change.
_AFFIRM_WORD = (
    r"(?:y+e+s+|y+e+a+h*|y+e+p+|ya+|y|o+k+(?:a+y+)?|k+|sure|fine|done|alright|all\s+right|"
    r"correct|right|perfect|great|good|proceed|go\s+ahead|go\s+on|go|continue|carry\s+on|"
    r"confirm(?:ed)?|approve[d]?|submit|send|apply|aply|appy|do\s+it|fix\s+it|"
    r"looks?\s+good|lgtm|sounds\s+good|let'?s\s+(?:go|do\s+it|proceed)|"
    r"confirm\s*(?:&|and)\s*submit)"
)
_AFFIRM_TAIL = r"(?:\s+(?:it|this|that|now|the\s+request|please|pls))*"
_AFFIRMATIVE_REPLY_RE = re.compile(
    rf"^\s*(?:please\s+|pls\s+)?{_AFFIRM_WORD}{_AFFIRM_TAIL}"
    rf"(?:\s*[,&]?\s*(?:and\s+)?{_AFFIRM_WORD}{_AFFIRM_TAIL}){{0,3}}\s*[.!]*\s*$",
    re.IGNORECASE,
)


def is_affirmative_reply(query: str) -> bool:
    """True for a reply that is nothing but a go-ahead: "yes", "yess",
    "proceed", "approve", "apply", "apply now", "ok submit it", "yes please
    go ahead", "confirm & submit", "fix it now", "looks good"."""
    return bool(_AFFIRMATIVE_REPLY_RE.match((query or "").replace("’", "'")))

# A time range ("9 to 6", "9am-6pm", "10 se 7 bje") mentioned while a
# regularisation entry's start/end time is still open — deliberately loose
# on separator (to/-/–/se) and AM/PM, matching the same shapes
# regularisation_node._build_prompt's own worked examples already handle on
# the extraction side (see its "10 se 7 bje" / "9 am end time 10 pm"
# examples). Used only as a SIGNAL that a message is regularisation-entry
# content, never to parse the times itself — regularisation_node's own LLM
# prompt does the actual extraction.
_REG_TIME_RANGE_RE = re.compile(
    r"\b\d{1,2}(:\d{2})?\s*(am|pm|bje)?\s*(to|-|–|se)\s*(time\s*)?"
    r"\d{1,2}(:\d{2})?\s*(am|pm|bje)?\b",
    re.IGNORECASE,
)

# Reason wording tight enough to require an actual punch/attendance anchor
# next to it, not just the bare word "reason" alone (which is far too
# generic on its own — "reason for salary deduction", "reason my leave was
# rejected" have nothing to do with regularisation). This is what lets a
# regularisation entry's own reason text ("17 sep, reason miss punch",
# "forgot to punch out") be recognized as regularisation-entry content
# REGARDLESS of which intent fast_classify happens to guess for it — see
# is_regularisation_shaped_reply below, which deliberately does not key off
# any specific interrupt_intent value (a previous version of this guard
# only covered interrupt_intent == "attendance", which missed the same
# false-positive shape whenever fast_classify's weak/bare-word fallback
# landed on some OTHER intent instead).
_REG_REASON_WORDING_RE = re.compile(
    r"\bmiss(ed)?\s*punch\b|\bforgot\s+to\s+punch\b|\bdidn'?t\s+punch\b|\bno\s+punch\b|"
    r"\bpunch\s+issue\b|\breason\b[\w\s]{0,20}?\bpunch\b|\bpunch\b[\w\s]{0,20}?\breason\b",
    re.IGNORECASE,
)

# Explicit "change/update/edit/correct/modify" language naming one of the
# entry's own fields — a correction to an entry that's already COMPLETE and
# awaiting confirmation ("change reason I was late", "update the end time to
# 7pm"). Neither has_date_expression, _REG_TIME_RANGE_RE, nor
# _REG_REASON_WORDING_RE (which requires "punch" right next to "reason")
# fires for a bare correction like this, so it satisfied none of
# is_regularisation_shaped_reply's checks below — the mid-flow router fell
# through to the LLM fallback, whose pending-flow hint for a COMPLETE entry
# explicitly steers the classifier AWAY from 'regularisation' for anything
# that isn't a bare confirm/cancel, misclassifying it as 'attendance_explain'
# purely because "reason"/"late" read like an attendance question (observed/
# reported live: "change reason I was late" sent right after "Shall I go
# ahead and submit this?").
_REG_ENTRY_CORRECTION_RE = re.compile(
    r"\b(change|update|edit|correct|modify)\b[\w\s]{0,15}?\b"
    r"(reason|date|time|start\s*time|end\s*time|in\s*time|out\s*time)\b",
    re.IGNORECASE,
)


def _looks_like_regularisation_entry_content(query: str, has_date_expression: bool) -> bool:
    """True when the message plausibly supplies content for a
    regularisation entry — a date, a time range, or reason wording tied to
    a punch — independent of whatever intent fast_classify happens to guess
    for it. Deliberately NOT gated on any particular interrupt_intent value:
    fast_classify's weak, last-resort fallback patterns (e.g. the bare
    single-word "attendance"/"punch"/"hours" catch-all — see
    nlp_service._ATTENDANCE_CHECK_ACTION_PATTERNS) can fire confidently for
    ANY message that happens to contain one of those words, not just
    "attendance" — so keying this off "did interrupt_intent come back
    attendance" only fixed the one false-positive shape that had already
    been observed, not the general class of bug.

    Combined with "not _looks_like_genuine_query(query)" by the caller —
    a real question ("why is my punch missing on the 17th") still gets
    through untouched."""
    return bool(
        has_date_expression
        or _REG_TIME_RANGE_RE.search(query)
        or _REG_REASON_WORDING_RE.search(query)
        or _REG_ENTRY_CORRECTION_RE.search(query)
    )


# Words that name a CLEARLY DIFFERENT HR topic — when one of these appears,
# a bare date alone must not be enough to swallow the message as
# regularisation-entry content. Confirmed live/reported: "attendance for 20
# aug" mid-regularisation-flow has_date_expression=True (the date alone),
# so it satisfied _looks_like_regularisation_entry_content above and got
# stuck in the regularisation flow instead of routing to the attendance
# intent fast_classify had already correctly identified it as — the
# employee's actual question was never answered.
#
# _REG_REASON_WORDING_RE is checked FIRST and always wins over this list —
# a reason that happens to mention one of these words in passing (e.g.
# "attendance mismatch, reason: system missed my punch") is still genuine
# regularisation content, not an interruption.
_OTHER_TOPIC_WORD_RE = re.compile(
    r"\b(attendance|leave|salary|payroll|policy|benefit|recruitment|"
    r"training|compliance|performance|onboarding|"
    r"shift\s*timing|shift\s*details|work(?:ing)?\s*hours|timesheet|"
    r"punch\s*details?|check\s*in\s*time|check\s*out\s*time)\b",
    re.IGNORECASE,
)


def _looks_like_other_hr_topic(query: str) -> bool:
    if _REG_REASON_WORDING_RE.search(query):
        return False
    return bool(_OTHER_TOPIC_WORD_RE.search(query))
