"""Builds the intent-classification prompt and its label set for
hr_graph.classify_node. Kept separate from hr_graph.py so that file stays
focused on graph wiring/routing — this module owns everything about WHAT
gets asked of the LLM classifier, not how its answer gets routed.

Note: the base prompt below intentionally does NOT include an output-format
instruction (e.g. "respond with JSON") — ai_service.classify_intent_structured
always appends its own json_instruction to whatever prompt it's given. Adding
one here too previously caused two copies of this file to drift and give the
model contradictory formatting instructions; don't reintroduce one.
"""

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

_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_intent_prompt(query: str, recent: list, has_hr_context: bool) -> 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"
        )

    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
  small_talk           — thanks, great job, you're helpful, bye
  capabilities_inquiry — what can you do, what do you help with, tell me about yourself
  conversation_meta    — my last query, what did I ask, show my history, summarize our chat

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, timesheet, late arrival, shift timing, WFH
  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
  experience           — experience requirements for a role being hired or evaluated
  general_hr           — HR industry trends/news, market insights, best practices,
                         HR department structure, HR metrics/KPIs, HR strategy —
                         anything HR-related that isn't tied to a specific operational task above

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:
- "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
- 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
- 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).

{followup_directive}{context_block}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).
# "follow_up" is deliberately excluded: it's never asked of the model, only
# applied as a programmatic override afterward (see hr_graph.classify_node).
_VALID_INTENT_LABELS = frozenset({
    "greeting", "small_talk", "capabilities_inquiry", "conversation_meta",
    "leave_balance", "apply_leave", "leave_status", "cancel_leave", "leave_policy",
    "leave_eligibility",
    "payroll", "salary", "recruitment", "benefits", "performance",
    "attendance", "employee_management", "onboarding", "training",
    "compliance", "job_description", "interview_questions", "skills",
    "experience", "general_hr", "non_hr",
})
