"""Two ways "Show my team's leave requests" died in QA.

The reported turn came back as `{"intent": "general", "blocked": true}` with
no answer at all. Two independent defects stacked up behind it:

1. SMART PUNCTUATION. Every keyword and regex in nlp_service is written with
   a straight ASCII apostrophe ("my team's leave"), but phones, Word and most
   chat inputs autocorrect that to U+2019. The curly form matched none of the
   ~40 apostrophe patterns, so the query fell through to the generic keyword
   scorer and picked up HRMS_TEAM_MEMBERS_QUERY (0.6) from its "show my team"
   prefix - the roster, not the leave queue. classify_node's own `ql` fast
   paths had the same gap.

2. A HARD FAILURE ON AN UNREACHABLE CLASSIFIER. classify_intent_structured
   reports `classification_failed` when the LLM is rate-limited, times out or
   returns nothing usable. classify_node treated that as "the user was
   unclear" and ended the turn - discarding the confident deterministic label
   it already had. The QA run hit an OpenAI 429 and got a refusal for a query
   the keyword classifier had understood perfectly.

These are separate: fixing the apostrophe alone still left the turn dying
whenever the LLM was unavailable, and fixing the fallback alone still routed
the phone-typed query to the roster.
"""

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
from services.nlp_service import fast_classify, fold_smart_punctuation


CURLY = "’"   # ' - what a phone actually sends
STRAIGHT = "'"     # what every keyword list is written with


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

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

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


def _state(query, context=None, **extra):
    state = {
        "query": query,
        "context": context if context is not None else [],
        "bearer_token": "t", "company_id": "3735",
        "conversation_id": "conv-1", "usage_events": [],
        "is_manager": None, "intent": "general",
    }
    state.update(extra)
    return state


@contextmanager
def _mocks(returned_intent="general_hr", classification_failed=False, flagged=False,
           categories=None):
    """classify_node's two concurrent LLM calls. `classification_failed` is
    the third element of classify_intent_structured's tuple - what it returns
    when the LLM could not be reached."""
    clf = AsyncMock(return_value=(returned_intent, None, classification_failed))
    mod = AsyncMock(return_value={"flagged": flagged, "categories": categories or []})
    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 {"classify_intent_structured": clf, "_check_moderation": mod}


# =============================================================================
# 1 - A curly apostrophe must classify exactly like a straight one
# =============================================================================

class TestSmartPunctuationIsFolded:

    # Each of these is a real phrase from nlp_service's keyword lists, spanning
    # several intents - the bug was never specific to team leave.
    APOSTROPHE_QUERIES = [
        "Show my team{}s leave requests",
        "my team{}s leave history",
        "my team{}s attendance",
        "my team{}s pending leave",
        "show me leaves I{}ve applied for",
        "my reportees{} pending leaves",
    ]

    @pytest.mark.parametrize("template", APOSTROPHE_QUERIES)
    def test_curly_and_straight_forms_classify_identically(self, template):
        curly = fast_classify(template.format(CURLY))
        straight = fast_classify(template.format(STRAIGHT))
        assert curly == straight, (
            "a query typed on a phone must classify as the same intent, at "
            "the same confidence, as one typed with an ASCII apostrophe")

    def test_the_reported_query_is_a_team_leave_query(self):
        """The exact QA query. It used to score HRMS_TEAM_MEMBERS_QUERY at
        0.6 - the team roster - instead of the leave queue."""
        intent, is_hr, confidence = fast_classify(
            "Show my team{}s leave requests".format(CURLY))

        assert intent == "HRMS_TEAM_LEAVE_QUERY"
        assert is_hr is True
        assert confidence == 1.0

    def test_a_genuine_roster_query_still_wins(self):
        """The fold must not drag every team question into team leave."""
        assert fast_classify("show my team members")[0] == "HRMS_TEAM_MEMBERS_QUERY"

    @pytest.mark.parametrize("raw,folded", [
        ("team’s", "team's"),
        ("team‘s", "team's"),
        ("“quoted”", '"quoted"'),
        ("a–b", "a-b"),
        ("a—b", "a-b"),
        ("a b", "a b"),
    ])
    def test_fold_maps_each_form_to_ascii(self, raw, folded):
        assert fold_smart_punctuation(raw) == folded

    def test_fold_tolerates_empty_input(self):
        assert fold_smart_punctuation("") == ""
        assert fold_smart_punctuation(None) == ""


class TestClassifyNodeFastPathsFoldToo:

    async def test_a_curly_team_attendance_query_skips_the_llm(self):
        """classify_node's own `ql` fast paths had the same gap: the curly
        form missed the deterministic match and paid for an LLM round-trip
        it did not need (and which could fail)."""
        writer = FakeWriter()
        with _mocks() as m:
            result = await hr_graph.classify_node(
                _state("what is my team{}s attendance today".format(CURLY)), writer)

        assert result["intent"] == "HRMS_TEAM_ATTENDANCE_QUERY"
        assert not m["classify_intent_structured"].called, \
            "the deterministic fast path should have answered this"


# =============================================================================
# 2 - An unreachable classifier must not sink a query we understood
# =============================================================================

class TestFallbackWhenTheClassifierIsUnavailable:

    async def test_a_confident_keyword_label_is_used_instead_of_failing(self):
        """The QA failure: OpenAI 429 -> classification_failed -> the whole
        turn was refused, despite fast_classify being certain."""
        writer = FakeWriter()
        with _mocks(classification_failed=True):
            result = await hr_graph.classify_node(
                _state("Show my team{}s leave requests".format(CURLY)), writer)

        assert result["intent"] == "HRMS_TEAM_LEAVE_QUERY"
        assert result["error"] is None
        assert result["is_hr"] is True
        assert writer.of_type("error") == [], "the turn must not be written off"
        assert writer.of_type("intent")[0]["intent"] == "HRMS_TEAM_LEAVE_QUERY"

    async def test_the_fallback_intent_routes_to_the_real_node(self):
        """Falling back is only worth anything if the router acts on it."""
        writer = FakeWriter()
        with _mocks(classification_failed=True):
            result = await hr_graph.classify_node(
                _state("Show my team{}s leave requests".format(CURLY)), writer)

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

    @pytest.mark.parametrize("query,expected", [
        ("what is my leave balance", "leave_balance"),
        ("cancel my leave", "cancel_leave"),
        ("am I eligible for sick leave", "leave_eligibility"),
    ])
    async def test_the_fallback_is_not_specific_to_team_leave(self, query, expected):
        writer = FakeWriter()
        with _mocks(classification_failed=True):
            result = await hr_graph.classify_node(_state(query), writer)

        assert result["intent"] == expected
        assert result["error"] is None

    async def test_an_unrecognisable_query_still_asks_for_a_rephrase(self):
        """The fallback only trusts a CONFIDENT HR label. Below that bar the
        honest answer is still "I'm not sure what you're asking" - a wrong
        guess would be worse than asking."""
        writer = FakeWriter()
        with _mocks(classification_failed=True):
            result = await hr_graph.classify_node(
                _state("qwertyuiop zxcvbnm"), writer)

        assert result["intent"] == "unclear"
        assert result["error"] == "unclear"
        assert len(writer.of_type("error")) == 1

    async def test_a_flagged_query_is_still_blocked(self):
        """Moderation is evaluated before the fallback, so an unreachable
        classifier can never be a way past the input guardrail.

        ACTIVE_LLM_PROVIDER is forced to openai because classify_node's
        _moderate() is a no-op on any other provider (conftest runs the suite
        as deepseek), and a guardrail assertion against a guardrail that
        never ran would prove nothing.

        The query must also be one with NO deterministic fast path. This
        originally used the team-leave question, which later gained one -
        and a fast path returns before the classifier and its moderation run
        at all, so the test silently stopped exercising the fallback it is
        named for. Gibberish reaches the classifier by construction.
        """
        writer = FakeWriter()
        with patch.object(classify_node_mod, "ACTIVE_LLM_PROVIDER", "openai"),                 _mocks(classification_failed=True, flagged=True, categories=["illicit"]):
            result = await hr_graph.classify_node(
                _state("qwertyuiop zxcvbnm"), writer)

        assert result["error"] == "flagged"
        assert result["is_hr"] is False
        assert writer.of_type("guardrail")[0]["status"] == "failed"
        assert writer.of_type("intent") == []


class TestHealthyClassifierIsUnaffected:

    async def test_the_llm_label_still_wins_when_the_call_succeeds(self):
        """The fallback must be reachable ONLY on failure - when the LLM
        answers, its label is still the one that routes, even where
        fast_classify would have said something else."""
        writer = FakeWriter()
        with _mocks(returned_intent="leave_status", classification_failed=False):
            result = await hr_graph.classify_node(
                _state("show me leaves I{}ve applied for".format(CURLY)), writer)

        assert result["intent"] == "leave_status"
        assert result["error"] is None
