"""P0 (Oct 25): "What is Ashwagandha?" was answered, then "What are its
benefits?" was refused as outside HR scope.

Product rule: HelixAI answers general questions; only the blacklist
(moderation, the custom guardrail, coding) restricts it. Three faults
combined to break that on a follow-up:

  1. _HR_CONTEXT_SIGNALS was matched as substrings, so "hr" inside
     "cHRonic"/"sHRub"/"tHRee" made any general answer look like an HR
     conversation.
  2. The short-fragment override then saw "benefits" (an HR word) in the
     follow-up and relabelled the classifier's correct non_hr to follow_up,
     routing it to hr_response_node.
  3. HR_SYSTEM_PROMPT told that node to decline anything non-HR.

Each is pinned separately below, so a regression in any one shows up even
while the other two still hide it.
"""

from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.classify_node as classify_node_mod
import services.hr_graph as hr_graph
from services.ai_service import HR_SYSTEM_PROMPT


ASHWAGANDHA = [
    {"role": "user", "content": "What is Ashwagandha?"},
    {"role": "assistant", "content": (
        "Ashwagandha (Withania somnifera) is an evergreen shrub used in Ayurvedic "
        "medicine as an adaptogen; it may help reduce chronic stress.")},
]
LEAVE_BALANCE = [
    {"role": "user", "content": "what is my leave balance"},
    {"role": "assistant", "content": "You have 14 Casual Leave day(s) remaining out of 24."},
]
PARIS = [
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "Paris."},
]


def _state(query, context, last_intent):
    return {
        "query": query, "context": context, "last_intent": last_intent,
        "bearer_token": "t", "company_id": "3735",
        "conversation_id": "conv-1", "usage_events": [],
    }


@contextmanager
def _classifier_says(label):
    clf = AsyncMock(return_value=(label, None, False))
    mod = AsyncMock(return_value={"flagged": False})
    slot_store = MagicMock(get_slots=MagicMock(return_value=None))
    with patch.multiple(classify_node_mod, classify_intent_structured=clf,
                        _check_moderation=mod, leave_slot_service=slot_store):
        yield


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)


# ── fault 1: whole-word HR signals ───────────────────────────────────────────

@pytest.mark.parametrize("text", [
    "it may help reduce chronic stress",
    "an evergreen shrub",
    "it grows through three seasons",
    "Paris has a population of about 2 million",
])
def test_general_text_is_not_hr_context(text):
    assert not classify_node_mod._context_has_hr_signal([{"role": "assistant", "content": text}])


@pytest.mark.parametrize("text", [
    "You have 14 Casual Leave day(s) remaining",
    "You have 3 leaves left",
    "Please check with HR",
    "No punch records found for 2026-08-26.",
    "You punched in at 9:02",
    "The WFH policy says",
])
def test_hr_text_is_still_hr_context(text):
    assert classify_node_mod._context_has_hr_signal([{"role": "assistant", "content": text}])


# ── fault 2: the short-fragment override ─────────────────────────────────────

@pytest.mark.parametrize("query,context", [
    ("What are its benefits?", ASHWAGANDHA),
    # HR earlier in the conversation, but the LAST turn was general.
    ("What are its benefits?", LEAVE_BALANCE + ASHWAGANDHA),
    ("and its population?", LEAVE_BALANCE + PARIS),
    ("what about the side effects?", LEAVE_BALANCE + ASHWAGANDHA),
])
async def test_follow_up_to_a_general_answer_stays_general(query, context):
    with _classifier_says("non_hr"):
        result = await hr_graph.classify_node(_state(query, context, "non_hr"), FakeWriter())

    assert result["intent"] == "non_hr"
    assert result["is_hr"] is False
    assert hr_graph._route_after_classify(result) == "non_hr_node"


async def test_follow_up_to_general_chat_stays_general():
    with _classifier_says("non_hr"):
        result = await hr_graph.classify_node(
            _state("What are its benefits?", LEAVE_BALANCE + ASHWAGANDHA, "general_chat"),
            FakeWriter())

    assert hr_graph._route_after_classify(result) == "non_hr_node"


async def test_hr_follow_up_after_an_hr_turn_is_still_rescued():
    """The override's real job is unchanged: a short HR continuation the
    classifier called non_hr, right after an HR answer, stays HR."""
    with _classifier_says("non_hr"):
        result = await hr_graph.classify_node(
            _state("what about benefits?", LEAVE_BALANCE, "leave_balance"), FakeWriter())

    assert result["intent"] == "follow_up"
    assert hr_graph._route_after_classify(result) == "hr_response_node"


# ── fault 3: the HR responder never declines a general question ─────────────

@pytest.mark.parametrize("phrase", [
    "outside my HR expertise",
    "outside HR scope",
    "You answer ONLY HR",
    "I can only assist with HR",
    "do not answer the off-topic question",
    "built exclusively for HR",
])
def test_hr_prompt_has_no_scope_refusal(phrase):
    assert phrase.lower() not in HR_SYSTEM_PROMPT.lower()


def test_hr_prompt_tells_the_model_to_answer_general_questions():
    assert "You may answer general questions" in HR_SYSTEM_PROMPT
    assert "Never refuse a question for being outside HR" in HR_SYSTEM_PROMPT
