"""Config table + detect/resolve helpers for bare-verb clarification
(e.g. a lone 'apply' with no object)."""

import re
from typing import Optional

_BARE_VERB_CONFIGS = {
    "apply": {
        "pattern": re.compile(
            r"^\s*(i\s+(?:want|need)\s+to\s+|i'd\s+like\s+to\s+|can\s+i\s+)?"
            r"apply(\s+for)?\s*[.!?]?\s*$",
            re.IGNORECASE,
        ),
        # keyword -> resolved intent, checked against the user's follow-up reply
        "options": {
            "leave": "apply_leave",
            "regularis": "regularisation",   # matches regularise/regularize/regularisation
            "regulariz": "regularisation",
        },
        "prompt": "Could you clarify what would you like to apply for?",
        "choices": ["Leave", "Regularization"],
    },
    # Additional verbs are defined but NOT activated in classify_node yet —
    # see _ACTIVE_BARE_VERBS below. Enable by adding the key there once you
    # want it live.
    "cancel": {
        "pattern": re.compile(
            r"^\s*(i\s+(?:want|need)\s+to\s+)?cancel(\s+it)?\s*[.!?]?\s*$",
            re.IGNORECASE,
        ),
        "options": {"leave": "cancel_leave"},
        "prompt": "What would you like to cancel?",
        "choices": ["Leave request"],
    },
    "regularise": {
        "pattern": re.compile(
            r"^\s*(i\s+(?:want|need)\s+to\s+)?regulari[sz]e\s*[.!?]?\s*$",
            re.IGNORECASE,
        ),
        "options": {"attendance": "regularisation", "punch": "regularisation"},
        "prompt": "What attendance would you like to regularise?",
        "choices": ["Missed/incorrect punch"],
    },
    "check": {
        "pattern": re.compile(
            r"^\s*(i\s+(?:want|need)\s+to\s+)?check\s*[.!?]?\s*$",
            re.IGNORECASE,
        ),
        "options": {
            "balance": "leave_balance",
            "status": "leave_status",
            "attendance": "punch_details",
            "punch": "punch_details",
        },
        "prompt": "What would you like to check?",
        "choices": ["Leave balance", "Leave status", "Attendance / punch details"],
    },
}

# Only verbs listed here trigger the fast-path in classify_node.
# Extend as you validate each one.
# ── Bare TOPIC nouns ─────────────────────────────────────────────────────────
# A lone topic word is as contextless as a lone verb, and was being guessed at
# rather than asked about: "leave" on its own came back with the employee's
# leave BALANCE, when they might equally have meant apply, status, cancel or
# the policy. Same table, same machinery — the entries below are nouns rather
# than verbs, and nothing else about the mechanism changes.
#
# Every pattern is anchored ^...$ so only the bare word clarifies. "leave
# balance", "apply leave", "why was I marked absent" all carry enough to
# route on their own and never reach here.
#
# `options` order matters: first substring hit wins, so the specific readings
# come before the general one. "applied"/"application" must be checked before
# "appl", or "view my applied leaves" resolves to apply_leave.
_BARE_VERB_CONFIGS.update({
    "leave": {
        "pattern": re.compile(r"^\s*(my\s+|about\s+)?leaves?\s*[.!?]?\s*$", re.IGNORECASE),
        "options": {
            "cancel": "cancel_leave",
            "balance": "leave_balance", "remaining": "leave_balance",
            "quota": "leave_balance", "left": "leave_balance",
            "applied": "leave_status", "status": "leave_status",
            "pending": "leave_status", "view": "leave_status",
            "eligib": "leave_eligibility", "qualify": "leave_eligibility",
            "polic": "policy", "rule": "policy",
            "appl": "apply_leave", "new": "apply_leave", "take": "apply_leave",
        },
        "prompt": ("What would you like to do with leave — apply for one, check your "
                   "balance, see your applied leaves, cancel one, or read the leave policy?"),
        "choices": ["Apply for leave", "Leave balance", "My leave requests",
                    "Cancel a leave", "Leave policy"],
    },
    "attendance": {
        "pattern": re.compile(r"^\s*(my\s+|about\s+)?attendance\s*[.!?]?\s*$", re.IGNORECASE),
        "options": {
            "polic": "policy", "rule": "policy", "hour": "policy",
            "regularis": "regularisation", "regulariz": "regularisation",
            "punch": "punch_details", "check in": "punch_details",
            "check-in": "punch_details", "timing": "punch_details",
            "why": "attendance_explain", "explain": "attendance_explain",
            "record": "attendance", "my": "attendance", "summary": "attendance",
        },
        "prompt": ("What would you like about attendance — your own record, your punch "
                   "times, why a day was marked a certain way, raising a regularisation, "
                   "or the attendance policy?"),
        "choices": ["My attendance", "My punch times", "Why was I marked…",
                    "Raise a regularisation", "Attendance policy"],
    },
    "salary": {
        "pattern": re.compile(r"^\s*(my\s+|about\s+)?(salary|pay|payroll)\s*[.!?]?\s*$",
                              re.IGNORECASE),
        "options": {
            "polic": "policy", "rule": "policy", "structure": "policy",
            "slip": "payroll", "payslip": "payroll", "deduction": "payroll",
            "when": "payroll", "credit": "payroll",
            "range": "salary", "ctc": "salary", "increment": "salary", "hike": "salary",
        },
        "prompt": ("What would you like about pay — your payslip and deductions, when "
                   "salary is credited, or what the payroll and benefits policy says?"),
        "choices": ["My payslip", "When salary is credited", "Payroll policy"],
    },
    "regularisation": {
        # Not "my regularization(s)": that names the employee's own requests and
        # goes straight to the list (live, it got this menu instead).
        "pattern": re.compile(r"^\s*(about\s+)?regulari[sz]ations?\s*[.!?]?\s*$",
                              re.IGNORECASE),
        "options": {
            "polic": "policy", "rule": "policy", "limit": "policy",
            "my": "my_regularisation_view", "view": "my_regularisation_view",
            "status": "my_regularisation_view", "pending": "my_regularisation_view",
            "rais": "regularisation", "new": "regularisation",
            "appl": "regularisation", "submit": "regularisation",
        },
        "prompt": ("What would you like to do with regularisation — raise a new one, "
                   "see the ones you've already raised, or read the policy?"),
        "choices": ["Raise a regularisation", "My regularisations", "Regularisation policy"],
    },
    "shift": {
        "pattern": re.compile(r"^\s*(my\s+|about\s+)?shifts?\s*[.!?]?\s*$", re.IGNORECASE),
        "options": {
            "polic": "policy", "rule": "policy", "hour": "policy", "standard": "policy",
            "my": "shift_query", "assign": "shift_query", "timing": "shift_query",
        },
        "prompt": ("Did you want your own shift assignment and timings, or what the "
                   "policy says about working hours?"),
        "choices": ["My shift", "Working hours policy"],
    },
})

_ACTIVE_BARE_VERBS = {
    "apply", "cancel", "regularise", "check",
    # Topic nouns — see _BARE_VERB_CONFIGS.update() above.
    "leave", "attendance", "salary", "regularisation", "shift",
}


def detect_bare_verb_query(query: str) -> Optional[str]:
    """Returns the matched, ACTIVE verb key, or None."""
    stripped = query.strip()
    for verb in _ACTIVE_BARE_VERBS:
        if _BARE_VERB_CONFIGS[verb]["pattern"].match(stripped):
            return verb
    return None


def get_clarify_prompt(verb: str) -> str:
    return _BARE_VERB_CONFIGS[verb]["prompt"]


def get_clarify_choices(verb: str) -> list:
    return _BARE_VERB_CONFIGS[verb]["choices"]


def resolve_bare_verb_clarification(query: str, verb: str) -> Optional[str]:
    """Maps the user's reply to a resolved intent label, or None if unresolved."""
    q = query.lower()
    for keyword, intent in _BARE_VERB_CONFIGS[verb]["options"].items():
        if keyword in q:
            return intent
    return None