"""
Tests for classify_node's narrow override of OpenAI moderation's "violence"
false-positive on punch-details phrasing.

Confirmed live: OpenAI's moderation endpoint deterministically (not a flaky
borderline score — reproduced 3x identically) flags queries like "punch in
and punch out" as categories=["violence"], because "punch" is also a literal
hit/strike verb and the two-verb "punch in ... punch out" pattern reads like
an imperative to strike twice. That's core, expected phrasing for
punch_details queries (FR-03.2) — left unhandled, the moderation gate blocks
the request before punch_details_node (and erp-api) is ever reached.

The override in hr_graph.classify_node only fires when:
  1. "violence" is the SOLE flagged category (never alongside anything else)
  2. classify_intent_structured — a separate LLM call that ran in parallel
     and knows nothing about this override — independently classified the
     query as punch_details or attendance

Both conditions are tested here to confirm the override stays narrow: any
other flagged category, any other detected intent, or violence combined with
another category, must still block as normal.
"""
import pytest
from unittest.mock import AsyncMock

import services.hr_graph as hr_graph
import services.classify_node as classify_node_mod
from tests.test_leave_action import FakeWriter, FakeSlotStore, base_state


@pytest.fixture
def fake_slots(monkeypatch):
    store = FakeSlotStore()
    monkeypatch.setattr(classify_node_mod, "leave_slot_service", store)
    return store


def _mock_moderation(monkeypatch, flagged: bool, categories: list):
    # classify_node's _moderate() closure short-circuits to {} (never
    # calling _check_moderation at all) unless ACTIVE_LLM_PROVIDER ==
    # "openai" — pinned here so these tests are deterministic regardless of
    # the local .env, rather than silently no-op'ing on a non-openai setup.
    monkeypatch.setattr(classify_node_mod, "ACTIVE_LLM_PROVIDER", "openai")
    monkeypatch.setattr(
        classify_node_mod, "_check_moderation",
        AsyncMock(return_value={"flagged": flagged, "categories": categories}),
    )


def _mock_intent(monkeypatch, intent: str):
    async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
        return intent, None, False
    monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)


@pytest.mark.asyncio
class TestPunchWordingModerationOverride:
    async def test_violence_only_plus_punch_details_intent_is_overridden(self, fake_slots, monkeypatch):
        _mock_moderation(monkeypatch, flagged=True, categories=["violence"])
        _mock_intent(monkeypatch, "punch_details")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("punch in and punch out"), writer)

        assert result["error"] is None
        assert result["intent"] == "punch_details"
        assert result["is_hr"] is True
        assert writer.of_type("guardrail")[-1]["status"] == "passed"

    async def test_violence_only_plus_attendance_intent_is_overridden(self, fake_slots, monkeypatch):
        _mock_moderation(monkeypatch, flagged=True, categories=["violence"])
        _mock_intent(monkeypatch, "attendance")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what time do I punch in"), writer)

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

    async def test_violence_only_but_unrelated_intent_still_blocks(self, fake_slots, monkeypatch):
        """The override requires the REAL LLM classifier to independently
        agree this is a punch/attendance query — a violence flag on
        anything else must still block, exactly as before."""
        _mock_moderation(monkeypatch, flagged=True, categories=["violence"])
        _mock_intent(monkeypatch, "employee_management")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("some other query"), writer)

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

    async def test_violence_plus_another_category_still_blocks_even_for_punch_details(self, fake_slots, monkeypatch):
        """Violence must be the SOLE category — combined with anything else,
        this is no longer the narrow punch-wording false positive."""
        _mock_moderation(monkeypatch, flagged=True, categories=["violence", "harassment"])
        _mock_intent(monkeypatch, "punch_details")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("punch in and punch out"), writer)

        assert result["error"] == "flagged"
        assert writer.of_type("guardrail")[-1]["status"] == "failed"

    async def test_unrelated_category_for_punch_details_intent_still_blocks(self, fake_slots, monkeypatch):
        """A genuinely different flagged category (not violence) on a
        punch_details-classified query must still block — the override is
        specific to the violence/punch-wording collision, not a blanket
        pass for the intent."""
        _mock_moderation(monkeypatch, flagged=True, categories=["illicit"])
        _mock_intent(monkeypatch, "punch_details")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("punch in and punch out"), writer)

        assert result["error"] == "flagged"
        assert writer.of_type("guardrail")[-1]["status"] == "failed"

    async def test_not_flagged_at_all_is_unaffected(self, fake_slots, monkeypatch):
        _mock_moderation(monkeypatch, flagged=False, categories=[])
        _mock_intent(monkeypatch, "punch_details")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("what time did I check in today"), writer)

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


def _mock_classification_failure(monkeypatch):
    """classify_intent_structured's own fallback path: it could not label the
    query, so it returns its fallback with classification_failed=True."""
    async def _fake_classify(prompt, valid_labels, fallback_label="general_hr"):
        return fallback_label, None, True
    monkeypatch.setattr(classify_node_mod, "classify_intent_structured", _fake_classify)


@pytest.mark.asyncio
class TestRefusalIsDistinguishableFromIncomprehension:
    """The turn can end without an answer for two unrelated reasons, and they
    must never be recorded as the same thing:

      REFUSED      - we understood the message and declined it (a custom
                     guardrail hit, or moderation flagging it). Rephrasing
                     will not help; the user is asking for something we do
                     not do.
      NOT UNDERSTOOD - we could not label the message at all. Rephrasing is
                     exactly what will help.

    Both used to return intent="unknown", error="flagged", which made them
    indistinguishable in hr_query_log's intent column, in
    chat_service.get_last_intent, and in every log line and dashboard built
    over the pair — a rise in refusals and a rise in comprehension failures
    are different problems with different fixes. The SSE stream always told
    them apart (a "guardrail" event vs an "error" event); these assertions
    pin the same split on the recorded side.
    """

    async def test_moderation_refusal_records_flagged(self, fake_slots, monkeypatch):
        _mock_moderation(monkeypatch, flagged=True, categories=["illicit"])
        _mock_intent(monkeypatch, "general_hr")
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("some blocked message"), writer)

        assert (result["intent"], result["error"]) == ("unknown", "flagged")
        assert writer.of_type("guardrail")[-1]["status"] == "failed"

    async def test_incomprehension_records_unclear(self, fake_slots, monkeypatch):
        _mock_moderation(monkeypatch, flagged=False, categories=[])
        _mock_classification_failure(monkeypatch)
        writer = FakeWriter()

        result = await hr_graph.classify_node(base_state("asdf qwerty zxcv"), writer)

        assert (result["intent"], result["error"]) == ("unclear", "unclear")
        # An "error" event, never a "guardrail" one - nothing was refused.
        assert writer.of_type("error"), "expected an error event"
        assert not writer.of_type("guardrail")

    async def test_the_two_outcomes_never_collapse(self, fake_slots, monkeypatch):
        """The regression guard proper: whatever the two paths return, the
        (intent, error) pairs must differ. Fails the moment someone makes
        either path reuse the other's values."""
        _mock_moderation(monkeypatch, flagged=True, categories=["illicit"])
        _mock_intent(monkeypatch, "general_hr")
        refused = await hr_graph.classify_node(base_state("some blocked message"), FakeWriter())

        _mock_moderation(monkeypatch, flagged=False, categories=[])
        _mock_classification_failure(monkeypatch)
        unclear = await hr_graph.classify_node(base_state("asdf qwerty zxcv"), FakeWriter())

        assert (refused["intent"], refused["error"]) != (unclear["intent"], unclear["error"])
        # Both still end the turn: _route_after_classify returns END on ANY
        # truthy error, so splitting the values must not have made one falsy.
        assert refused["error"] and unclear["error"]
        assert hr_graph._route_after_classify(refused) == hr_graph.END
        assert hr_graph._route_after_classify(unclear) == hr_graph.END
