"""services/team_leave_filter.py

Maps a manager's WORDING onto one of erp-api's four team-leave status
filters, and holds the copy that varies with the one chosen.

Background: GET /api/v1/ai/team/leaves takes a `type` parameter — all,
pending, approved or cancelled. team_leave_query_node originally hardcoded
`pending`, so "show me my team's approved leaves" fetched the pending list
and answered with the wrong rows under a "pending" heading. This module is
the piece that was missing.

Deterministic (keyword/regex, no LLM call) for the same reason the shift and
approval shortcuts in classify_node are: the vocabulary here is small,
closed, and unambiguous once negation is handled, and a manager who has to
re-ask because a status word was missed is a worse outcome than the ~350
tokens an adjudication call would cost. The intent itself is already
settled by the time this runs — this only narrows WHICH statuses to fetch.

The default is PENDING, not "all". Every existing caller and the whole
FR-07.1 acceptance suite depend on an unqualified "show my team's leave
requests" continuing to mean the pending queue, which is also the only
reading that matches what a manager is being asked to act on.
"""

import re

import services.access_notice as access_notice


PENDING = "pending"
APPROVED = "approved"
CANCELLED = "cancelled"
ALL = "all"

#: The resolver only ever returns one of these — matches
#: erp_client.TEAM_LEAVE_STATUS_FILTERS.
VALID_STATUSES = (ALL, PENDING, APPROVED, CANCELLED)

DEFAULT_STATUS = PENDING


# Phrases that CONTAIN an approval word but mean "not yet approved" — i.e.
# pending. Checked before anything else, because a plain "approved" scan
# would read every one of them as the approved filter and answer a question
# about the queue with a list of already-settled requests. This is the one
# real ambiguity in the vocabulary, so it gets the first and last word.
_PENDING_OVERRIDE_PATTERNS = (
    re.compile(r"\bpending\s+approval\b"),
    re.compile(r"\bapprovals?\s+pending\b"),
    re.compile(r"\bawaiting\s+(?:my\s+|the\s+)?approval\b"),
    re.compile(r"\b(?:for|need|needs|needing|require|requires|requiring)\s+(?:my\s+|the\s+)?approval\b"),
    re.compile(r"\bto\s+(?:be\s+)?approve[d]?\b"),
    re.compile(r"\byet\s+to\s+(?:be\s+)?approve[d]?\b"),
    re.compile(r"\bnot\s+(?:yet\s+)?approved\b"),
    re.compile(r"\bun-?approved\b"),
    re.compile(r"\bwaiting\s+(?:on|for)\s+(?:my\s+|the\s+)?approval\b"),
    re.compile(r"\bneed(?:s|ing)?\s+(?:my\s+)?(?:sign[- ]?off|action|decision)\b"),
)

_APPROVED_MARKERS = (
    "approved", "approve", "accepted", "granted", "sanctioned", "cleared",
    "okayed", "signed off", "sign-off",
)

_CANCELLED_MARKERS = (
    "cancelled", "canceled", "cancellation", "cancellations", "withdrawn",
    "withdrawal", "revoked", "rescinded", "retracted",
)

_PENDING_MARKERS = (
    "pending", "awaiting", "outstanding", "unapproved", "undecided",
    "not yet decided", "in review", "under review", "to review",
    "waiting", "open requests", "open leave",
)

# Only consulted when NO specific status was named — "all" alongside a status
# word ("all pending requests") is a quantifier, not a filter.
_ALL_MARKERS = (
    "all", "every", "entire", "complete", "full list", "any status",
    "all statuses", "regardless of status", "whole", "history", "everything",
)


def _normalize(query: str) -> str:
    """Lowercase, curly apostrophes folded, whitespace collapsed."""
    text = (query or "").lower().replace("’", "'").replace("‘", "'")
    return re.sub(r"\s+", " ", text).strip()


def resolve_team_leave_status(query: str) -> str:
    """Which status filter this query is asking for. Returns one of
    VALID_STATUSES; never raises.

    Resolution order, and why:

      1. A pending-override phrase ("awaiting approval", "yet to be
         approved") -> PENDING. First, so the approval words inside them
         can't be read as the approved filter.
      2. The specific status vocabularies. Exactly one matched -> that
         status. More than one ("approved and cancelled") -> ALL, since the
         endpoint has no multi-status filter and ALL is the only response
         that contains everything the manager named.
      3. An "all"-flavoured quantifier with no status named -> ALL.
      4. Nothing at all -> DEFAULT_STATUS (pending).
    """
    ql = _normalize(query)
    if not ql:
        return DEFAULT_STATUS

    if any(p.search(ql) for p in _PENDING_OVERRIDE_PATTERNS):
        return PENDING

    matched = set()
    if any(m in ql for m in _CANCELLED_MARKERS):
        matched.add(CANCELLED)
    if any(m in ql for m in _APPROVED_MARKERS):
        matched.add(APPROVED)
    if any(m in ql for m in _PENDING_MARKERS):
        matched.add(PENDING)

    if len(matched) == 1:
        return matched.pop()
    if len(matched) > 1:
        return ALL

    if any(m in ql for m in _ALL_MARKERS):
        return ALL

    return DEFAULT_STATUS


# ── Copy that varies with the resolved status ────────────────────────────────
# Kept beside the resolver so a new filter can never be added with its wording
# left behind in the node. The PENDING strings are verbatim what the FR-07.1
# acceptance suite asserts (notably AC#6's empty state) and must not drift.

def status_label(status: str) -> str:
    """The adjective for this filter, or "" for ALL — "leave requests" with
    no adjective is how you say "of any status" in a sentence."""
    return "" if status == ALL else status


def fetching_message(status: str) -> str:
    label = status_label(status)
    qualifier = f"{label} " if label else ""
    return f"Checking your team's {qualifier}leave requests..."


def empty_state_message(status: str) -> str:
    if status == PENDING:
        # AC#6 — exact required copy, verbatim.
        return "Great news! There are currently no pending leave requests for your team."
    if status == ALL:
        return "There are no leave requests on record for your team."
    return f"There are no {status_label(status)} leave requests for your team."


def summary_header(status: str) -> str:
    label = status_label(status)
    qualifier = f"{label} " if label else ""
    return f"Here are the top {qualifier}leave requests for your team:"


def more_available_note(status: str) -> str:
    label = status_label(status)
    qualifier = f"{label} " if label else ""
    return f"(more {qualifier}requests are available)"


def restricted_message(status: str) -> str:
    """HA-193 — the Figma's two-sentence refusal, not an apology.

    The first sentence is fixed and matches the team-attendance refusal
    word for word, because they render in the same "Not available" card and
    a caller who asks for both must not be told two different rules. Only
    the second sentence varies, so the offer still names the status the
    caller actually asked about ("your own approved leave requests") rather
    than silently redirecting them to the pending queue.
    """
    label = status_label(status)
    qualifier = f"{label} " if label else ""
    return access_notice.message(
        "Team leave summaries",
        f"check your own {qualifier}leave requests",
    )


def restricted_notice(status: str) -> dict:
    """The `access_notice` card payload for a refused team-leave query."""
    return access_notice.build("team_leave", restricted_message(status))
