"""HA-932 QA (Oct 23): the Manager name-lookup path still caught conversation.

  D-02  "meh"            -> Rahul Mehta's leave card ("meh" starts "Mehta")
  D-03  "wow" under the team's pending list -> "No matching employee" picker
  D-01  after "meh", "uh oh" opened the picker, and the picker then answered
        "Diwali", "budget", "Python"... - 37 of 163 messages in one chat
  D-08  "Kunal" found Kunal Employee; "Kunal Employee" got the greeting
"""
import pytest

import services.hr_graph as hr_graph
import services.individual_report as individual_report
from services.classify_node import _is_bare_person_fragment
from services.individual_report import individual_report_node

from tests.test_bare_name_continuation import _mocks, _state, LEAVE_LOOKUP
from tests.test_individual_report import (  # noqa: F401 -- fixtures
    FakeWriter, base_state, mock_extraction, no_match_response,
    name_match_response, patch_leave_api, TEAM_ROSTER, _fake_report_store,
    _default_extraction, _default_status_api,
)

pytestmark = pytest.mark.asyncio

RAHUL_MEHTA = {"employee_id": 4100, "employee_number": "EMP-41", "employee_name": "Rahul Mehta"}


class TestReactionsAreNotNames:

    @pytest.mark.parametrize("query", [
        "meh", "wow", "WOW", "Wow!!!", "wowww", "tough.", "seriously???", "uh oh",
        "fair enough", "that's crazy", "makes sense", "oh really", "interesting",
        "alright", "whatever", "haha", "hahaha", "omg", "phew", "accha", "theek hai",
        "kya baat hai", "arre yaar", "sach mein?", "mast", "haan", "nahi yaar",
        "prime minister", "Diwali", "budget", "I'm bored", "tough tough tough",
    ])
    def test_not_a_name(self, query):
        assert _is_bare_person_fragment(query, False) is False

    @pytest.mark.parametrize("query", [
        "Kunal", "Kunal Employee", "Kunal Emplyee", "Kunal Manager", "Rahul Mehta",
        "Hope", "Grace",
    ])
    def test_names_still_are(self, query):
        assert _is_bare_person_fragment(query, False) is True

    @pytest.mark.parametrize("query", ["employee", "manager", "reporting manager",
                                       "hr manager", "my manager"])
    def test_a_role_word_is_a_name_only_after_a_name(self, query):
        assert _is_bare_person_fragment(query, False) is False


class TestAThreeLetterStartIsNotAMatch:
    """D-02: erp-api matched "meh" to Rahul Mehta, and the guard that throws
    out fuzzy matches let a 3-letter prefix count as sharing a name word."""

    def test_meh_does_not_share_a_word_with_mehta(self):
        assert individual_report._shares_a_name_word("meh", [RAHUL_MEHTA]) is False

    @pytest.mark.parametrize("term", ["rahul", "mehta", "meht", "rahu"])
    def test_a_real_partial_name_still_does(self, term):
        assert individual_report._shares_a_name_word(term, [RAHUL_MEHTA]) is True

    async def test_a_guessed_meh_is_handed_back(self, monkeypatch):
        mock_extraction(monkeypatch, employee_name="meh")
        patch_leave_api(monkeypatch, name_match_response([RAHUL_MEHTA]))
        writer = FakeWriter()
        state = base_state("meh")
        state["report_subject_was_guessed"] = True

        out = await individual_report_node(state, writer)

        assert out["route_to"] == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE
        assert writer.of_type("done") == []


class TestAContinuationWithNoQuestionOpenIsAGuess:
    """D-03 / D-01: after a team list or a finished lookup, a bare word was
    taken as the answer to a "which person?" nobody asked, so a miss raised
    the picker instead of being handed back."""

    @pytest.mark.parametrize("last_intent", [LEAVE_LOOKUP, "HRMS_TEAM_LEAVE_QUERY"])
    async def test_after_an_answer_the_bare_name_is_a_guess(self, last_intent):
        with _mocks() as _:
            hr_graph.classify_node.__globals__  # noqa: B018 - same module either way
            import services.classify_node as cn
            cn.leave_slot_service.get_report_state.return_value = None
            result = await hr_graph.classify_node(
                _state("Hope", last_intent=last_intent), FakeWriter())

        assert result["intent"] == LEAVE_LOOKUP
        assert result["report_subject_was_guessed"] is True

    async def test_with_the_picker_open_it_is_an_answer(self):
        with _mocks():
            import services.classify_node as cn
            cn.leave_slot_service.get_report_state.return_value = {
                "step": "awaiting_employee_selection", "candidates": TEAM_ROSTER}
            result = await hr_graph.classify_node(_state("Hope"), FakeWriter())

        assert result["report_subject_was_guessed"] is False

    async def test_after_which_team_member_it_is_an_answer(self):
        state = _state("Hope", last_intent="manager_attendance_explanation")
        state["context"] = [
            {"role": "user", "content": "why was he absent"},
            {"role": "assistant", "content": "Which team member would you like me to look "
                                             "this up for? Please give me their name or employee ID."},
        ]
        with _mocks():
            import services.classify_node as cn
            cn.leave_slot_service.get_report_state.return_value = None
            result = await hr_graph.classify_node(state, FakeWriter())

        assert result["report_subject_was_guessed"] is False

    async def test_a_picker_already_reoffered_no_longer_asks(self):
        with _mocks():
            import services.classify_node as cn
            cn.leave_slot_service.get_report_state.return_value = {
                "step": "awaiting_employee_selection", "candidates": TEAM_ROSTER,
                "reoffered": True}
            result = await hr_graph.classify_node(_state("Hope"), FakeWriter())

        assert result["report_subject_was_guessed"] is True


class TestThePickerLetsGo:
    """D-01: re-shown on every reply that picked nobody, the picker held the
    chat. AC2's re-offer happens once; the second miss hands the turn back."""

    def _open_picker(self, store, **extra):
        store[("7", "conv-1")] = {"step": "awaiting_employee_selection",
                                  "intent": individual_report.LEAVE_REQUEST_INTENT,
                                  "candidates": TEAM_ROSTER, **extra}

    async def test_the_first_miss_reoffers(self, _fake_report_store):
        self._open_picker(_fake_report_store)
        writer = FakeWriter()

        out = await individual_report_node(base_state("that's crazy"), writer)

        assert "route_to" not in out
        assert writer.of_type("employee_selection")
        assert _fake_report_store[("7", "conv-1")]["reoffered"] is True

    async def test_the_second_miss_hands_back_and_clears(self, _fake_report_store):
        self._open_picker(_fake_report_store, reoffered=True)
        writer = FakeWriter()

        out = await individual_report_node(base_state("that's crazy"), writer)

        assert out["route_to"] == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE
        assert writer.of_type("employee_selection") == []
        assert ("7", "conv-1") not in _fake_report_store

    async def test_a_pick_still_works_after_the_reoffer(self, _fake_report_store, monkeypatch):
        self._open_picker(_fake_report_store, reoffered=True)
        patch_leave_api(monkeypatch, name_match_response([TEAM_ROSTER[3]]))
        writer = FakeWriter()

        out = await individual_report_node(base_state("Ayush Chandra"), writer)

        assert "route_to" not in out

    async def test_a_picker_raised_from_a_picker_is_its_reoffer(self, _fake_report_store,
                                                               monkeypatch):
        """Otherwise a reply the extractor reads as a name ("Diwali") raises a
        fresh picker, and the loop is back."""
        self._open_picker(_fake_report_store)
        mock_extraction(monkeypatch, employee_name="Diwali")
        patch_leave_api(monkeypatch, no_match_response())

        await individual_report_node(base_state("Diwali"), FakeWriter())

        assert _fake_report_store[("7", "conv-1")]["reoffered"] is True


class TestAWithdrawnGuessIsToldNobodyMatched:
    """Live re-test (erp-api14): under the team's pending list, "Kunal
    Employee" - not on that team - was handed back and the model invented two
    leave requests for him. The general lane is now told what the directory
    established."""

    @pytest.mark.parametrize("withdrawn", [True, False])
    async def test_the_note_rides_only_on_a_withdrawn_guess(self, monkeypatch, withdrawn):
        seen = {}

        async def _fake_stream(messages, **kw):
            seen["system"] = messages[0]["content"]
            yield {"type": "chunk", "content": "ok"}

        monkeypatch.setattr(hr_graph, "_call_llm_stream", _fake_stream)
        state = {"query": "Kunal Employee", "context": [], "intent": "non_hr",
                 "usage_events": []}
        if withdrawn:
            state["route_to"] = individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE

        await hr_graph.non_hr_node(state, FakeWriter())

        assert (hr_graph.WITHDRAWN_NAME_GUESS_NOTE in seen["system"]) is withdrawn
