"""Audit: a non-HR question must reach non_hr_node, the general-answer lane.

The file name predates the product decision of Oct 2026: HelixAI now ANSWERS
general questions (only the blacklist - moderation, the custom guardrail,
coding - restricts it), and non_hr_node is where they are answered, with web
search. The routing rule tested here is unchanged by that: a short non-HR
question must not be relabelled "follow_up" by classify_node's short-fragment
override, because that sends it to hr_response_node, the HR advisor, instead
of the general lane. Before the Oct 2026 fix that prompt also REFUSED non-HR
questions - which is how "what are its benefits?" after "what is
ashwagandha?" was declined as outside HR scope (see
test_general_followups_not_refused.py).

This file sweeps the non-HR surface at the length where the override applies,
which is the only length at which it can misroute.
"""

from contextlib import contextmanager

import pytest
from unittest.mock import patch, AsyncMock, MagicMock

import services.hr_graph as hr_graph
import services.classify_node as classify_node_mod


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

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


HR_CONTEXT = [
    {"role": "user", "content": "what is my leave balance"},
    {"role": "assistant", "content": "You have 14 Casual Leave day(s) remaining out of 24."},
]


def _state(query, context=None):
    return {
        "query": query,
        "context": context if context is not None else HR_CONTEXT,
        "bearer_token": "t", "company_id": "3735",
        "conversation_id": "conv-1", "usage_events": [],
    }


@contextmanager
def _classifier_says_non_hr():
    """The realistic shape of every case here: the classifier gets it RIGHT
    and says non_hr. What is under test is whether anything downstream then
    overrides that correct answer into something the chat model will answer."""
    clf = AsyncMock(return_value=("non_hr", 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


# Every one of these is five words or fewer - the band where the override
# fires. Longer non-HR questions were never at risk, and are covered at the
# bottom for completeness.
NON_HR_SHORT = [
    # calendar / clock - the reported leak
    "today date", "date today", "today's date", "what is the date",
    "current date", "what day is it", "current time", "what time is it",
    # general knowledge
    "capital of france", "who is einstein", "population of india",
    "how tall is everest", "who won the world cup",
    # maths
    "what is 2 plus 2", "square root of 144", "convert 10 km to miles",
    # language
    "translate hello to hindi", "spell accommodation",
    "meaning of serendipity",
    # tech
    # ("write a for loop" was here: code requests are blacklisted now and
    # refused before routing - see test_coding_blacklist.py.)
    "what is python", "explain recursion",
    # everyday / entertainment
    "weather today", "cricket score", "best pizza recipe",
    "recommend a movie", "tell me a joke", "latest news",
    "how to cook pasta", "who won the match",
    # health / finance, adjacent but not HR
    "cure for headache", "bitcoin price today", "stock market today",
]

NON_HR_LONGER = [
    "what is the capital city of australia and its population",
    "explain the difference between machine learning and deep learning",
    "what were the main causes of the second world war",
]


class TestShortNonHRIsNeverRelabelled:

    @pytest.mark.parametrize("query", NON_HR_SHORT)
    async def test_it_stays_non_hr(self, query):
        writer = FakeWriter()
        with _classifier_says_non_hr():
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] == "non_hr", (
            f"{query!r} was relabelled {result['intent']!r} - the override "
            f"rescued a correctly-classified non-HR question"
        )

    @pytest.mark.parametrize("query", NON_HR_SHORT)
    async def test_it_reaches_the_redirect_node(self, query):
        """non_hr_node is the general-answer lane. Landing on hr_response_node
        (the HR advisor) instead IS the bug."""
        writer = FakeWriter()
        with _classifier_says_non_hr():
            result = await hr_graph.classify_node(_state(query), writer)

        route = hr_graph._route_after_classify(result)
        assert route == "non_hr_node", f"{query!r} routed to {route}"
        assert route != "hr_response_node"

    @pytest.mark.parametrize("query", NON_HR_SHORT)
    async def test_is_hr_is_false(self, query):
        """The flag the fall-through route reads, and what the `done` event
        reports to the client."""
        writer = FakeWriter()
        with _classifier_says_non_hr():
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["is_hr"] is False


class TestLongerNonHRIsAlsoUntouched:

    @pytest.mark.parametrize("query", NON_HR_LONGER)
    async def test_it_stays_non_hr(self, query):
        writer = FakeWriter()
        with _classifier_says_non_hr():
            result = await hr_graph.classify_node(_state(query), writer)

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


class TestWithNoHRContextAtAll:
    """The override needs HR context to fire, so a fresh conversation was
    never at risk - pinned so a future widening cannot change that quietly."""

    @pytest.mark.parametrize("query", NON_HR_SHORT[:12])
    async def test_it_stays_non_hr(self, query):
        writer = FakeWriter()
        with _classifier_says_non_hr():
            result = await hr_graph.classify_node(_state(query, context=[]), writer)

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


class TestTheRedirectItselfAnswersNothing:
    """What the caller actually receives once it reaches non_hr_node's
    fallback - the deterministic path, which is what runs when the redirect
    LLM call fails."""

    @pytest.mark.parametrize("query", NON_HR_SHORT)
    def test_the_fallback_never_repeats_the_question(self, query):
        text = hr_graph._get_fallback_redirect(query, {}).lower()
        # It must not echo the asked-about subject back as if answering.
        for token in query.lower().split():
            if len(token) > 4:
                assert token not in text, (
                    f"the redirect for {query!r} contains {token!r}"
                )

    def test_the_fallback_names_only_real_capabilities(self):
        text = hr_graph._get_fallback_redirect("today date", {}).lower()
        for never in ("payroll", "recruitment", "hiring", "compliance",
                      "benefits enrolment", "employee relations"):
            assert never not in text, f"redirect still advertises {never!r}"
