"""A guessed employee name that matches nobody is withdrawn, not dressed up
as a question.

The bug this closes, reported 2026-10-06 and predating the general-chat
ticket: a manager typing `profit vs revenue` -- or `photosynthesis`, or
`quantum computing` -- got "No employee matched that name. Please select an
employee from your team:" with their whole roster underneath.

Why it happens is worth keeping, because the obvious fixes are both wrong.
`classify_node` has a rung that reads a manager's bare 1-4 word message as a
person's name, which is right far more often than it is wrong: for a manager
"arshdeep" really does mean "show me Arshdeep's leave requests". It has to
guess BEFORE the classifier runs, and it cannot check the guess, because the
only thing that separates a name from a topic is the employee directory.

  * Not fixable by extending `_NOT_A_NAME`. That denylist is already ~100
    words and its own comments record it being extended after each leak --
    payroll, shl, "aply now", absent. profit/revenue is the next word nobody
    listed, and there is always a next word.
  * Not fixable by asking the classifier. Measured: it labels the REAL
    employees `abctest` and `a khan test` non_hr, exactly as it labels
    `photosynthesis`. Deferring to it would re-break the live bug the rung
    was built for.

So the guess stands, and the directory -- which the lookup consults anyway --
gets to overturn it.
"""
import pytest

import services.individual_report as individual_report
from services.individual_report import individual_report_node

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,
)

pytestmark = pytest.mark.asyncio


def _guessed(query, **kw):
    """The state classify_node produces for an UNPROMPTED guess, with the
    general-chat feature on - the withdrawal ships behind that flag."""
    s = base_state(query)
    s["report_subject_was_guessed"] = True
    s["general_chat_enabled"] = True
    s.update(kw)
    return s


# -- the guess is withdrawn --------------------------------------------------

async def test_a_guessed_name_that_matches_nobody_hands_the_turn_back(monkeypatch):
    mock_extraction(monkeypatch, employee_name="profit vs revenue")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    out = await individual_report_node(_guessed("profit vs revenue"), writer)

    assert out["route_to"] == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE
    assert out["is_hr"] is False


async def test_no_employee_picker_is_shown(monkeypatch):
    """The visible symptom. A general question must not be answered with a
    list of the manager's direct reports."""
    mock_extraction(monkeypatch, employee_name="photosynthesis")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    await individual_report_node(_guessed("photosynthesis"), writer)

    assert writer.of_type("employee_selection") == []


async def test_the_turn_is_not_answered_here(monkeypatch):
    """No `done` event: the turn is being handed on, not finished. Whatever
    claims it next writes the one done event, and two would put two answers
    on screen for one message."""
    mock_extraction(monkeypatch, employee_name="quantum computing")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    await individual_report_node(_guessed("quantum computing"), writer)

    assert writer.of_type("done") == []


async def test_the_intent_is_corrected_on_the_wire(monkeypatch):
    """classify_node already announced manager_leave_request_lookup, and
    main.py takes the intent it LOGS from that event. Without this
    correction the turn is recorded as an HRMS action while the employee
    received a non-HR answer, and FR-09's "general + hr_query + hrms_action
    == total messages" quietly stops adding up."""
    mock_extraction(monkeypatch, employee_name="profit vs revenue")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    await individual_report_node(_guessed("profit vs revenue"), writer)

    corrected = writer.of_type("intent")
    assert corrected, "the lane change was not announced"
    assert corrected[-1]["intent"] == "non_hr"
    assert corrected[-1]["is_hr"] is False


async def test_no_selection_state_is_left_behind(monkeypatch):
    """A stored shortlist outlives the turn. Left behind, the manager's next
    message would be read as a reply to a picker they never saw."""
    mock_extraction(monkeypatch, employee_name="profit vs revenue")
    patch_leave_api(monkeypatch, no_match_response())

    await individual_report_node(_guessed("profit vs revenue"), FakeWriter())

    assert not individual_report.leave_slot_service.get_report_state(7, "conv-1")


# -- what must NOT change ----------------------------------------------------

async def test_an_answered_picker_still_reshows_on_no_match(monkeypatch):
    """The other half, and the reason this is gated on a flag rather than
    applied to every unmatched name.

    When a previous turn ASKED "which person?", the bare reply really is a
    name and a no-match must re-show the picker -- that is the user answering
    a question, not us guessing. `report_subject_was_guessed` is absent here,
    exactly as classify_node leaves it on the continuation path.
    """
    mock_extraction(monkeypatch, employee_name="someone not here")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    out = await individual_report_node(base_state("someone not here"), writer)

    assert "route_to" not in out
    assert writer.of_type("employee_selection"), "the picker was lost"
    assert writer.done()


async def test_a_guess_that_MATCHES_is_answered_as_before(monkeypatch):
    """The guess is right far more often than it is wrong. A manager typing
    a real name must still get that person's lookup, flag or no flag."""
    mock_extraction(monkeypatch, employee_name="geo")
    patch_leave_api(monkeypatch,
                    name_match_response([TEAM_ROSTER[2], TEAM_ROSTER[4]]))
    writer = FakeWriter()

    out = await individual_report_node(_guessed("geo"), writer)

    assert "route_to" not in out
    assert writer.of_type("employee_selection"), "a real name lost its lookup"


async def test_the_flag_alone_changes_nothing_when_the_name_matches(monkeypatch):
    """Guarding against the flag leaking into the matched path: same inputs,
    with and without it, must produce the same events."""
    def _run(state):
        mock_extraction(monkeypatch, employee_name="geo")
        patch_leave_api(monkeypatch,
                        name_match_response([TEAM_ROSTER[2], TEAM_ROSTER[4]]))
        w = FakeWriter()
        return w, state

    w1, s1 = _run(_guessed("geo"))
    out1 = await individual_report_node(s1, w1)
    w2, s2 = _run(base_state("geo"))
    out2 = await individual_report_node(s2, w2)

    assert [e["type"] for e in w1.events] == [e["type"] for e in w2.events]
    assert ("route_to" in out1) == ("route_to" in out2)


# -- where the handed-back turn goes -----------------------------------------

def _routed(**kw):
    import services.hr_graph as hg
    st = {"query": "profit vs revenue", "company_id": "674",
          "conversation_id": None, "general_chat_enabled": False}
    st.update(kw)
    return hg._route_after_individual_report(st)


def test_a_normal_lookup_still_ends_the_turn():
    """This node had a plain edge to END for its whole life. Every path that
    is not a withdrawn guess must still reach it."""
    from langgraph.graph import END
    assert _routed() == END
    assert _routed(route_to=None) == END
    assert _routed(route_to="something_else") == END


def test_a_withdrawn_guess_goes_to_the_redirect_when_general_chat_is_off():
    import services.individual_report as ir
    assert _routed(route_to=ir.GUESSED_SUBJECT_NOT_AN_EMPLOYEE) == "non_hr_node"


def test_a_withdrawn_guess_goes_where_any_non_hr_turn_goes():
    """Routed through _general_chat_may_take_the_turn rather than straight at
    a node, so there is ONE answer to "may the general lane have this turn?":
    general chat when it is on, the redirect when it is off."""
    import services.individual_report as ir
    assert _routed(route_to=ir.GUESSED_SUBJECT_NOT_AN_EMPLOYEE,
                   general_chat_enabled=True) == "general_chat_node"
    assert _routed(route_to=ir.GUESSED_SUBJECT_NOT_AN_EMPLOYEE,
                   general_chat_enabled=False) == "non_hr_node"


def test_the_handoff_sentinel_is_not_a_node_name():
    """individual_report must not need to know what the graph calls the
    non-HR lane - it states what happened, the graph decides where that
    goes."""
    import services.individual_report as ir
    import services.hr_graph as hg
    assert ir.GUESSED_SUBJECT_NOT_AN_EMPLOYEE not in hg.hr_graph.nodes


def test_the_state_key_is_declared_or_langgraph_drops_it():
    """LangGraph silently drops keys that are not channels. Undeclared,
    `report_subject_was_guessed` reads back as None inside the node and the
    whole fix is a no-op with no error anywhere. This has cost this repo
    time twice already."""
    from schema.agent import HRState
    assert "report_subject_was_guessed" in HRState.__annotations__


# -- general chat off: the guess is withdrawn all the same (Oct 15) ---------------
#
# Product decision, replacing the earlier "nothing changes while general chat
# is off" rule for the unprompted guess: a guessed name that matches no
# employee goes to the web-search answer either way. Live, "Calgary Alberta
# Canada" got the "No matching employee" picker with 14 people on it.

@pytest.mark.parametrize("value", [None, False, 0, "", True])
async def test_withdrawn_whatever_general_chat_says(value, monkeypatch):
    mock_extraction(monkeypatch, employee_name="Calgary Alberta Canada")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    out = await individual_report_node(
        _guessed("Calgary Alberta Canada", general_chat_enabled=value), writer)

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


async def test_a_reply_to_which_employee_still_gets_the_picker(monkeypatch):
    """Only the unprompted guess is withdrawn: answering "which employee?"
    with a name that matches nobody still shows the team to pick from."""
    mock_extraction(monkeypatch, employee_name="profit vs revenue")
    patch_leave_api(monkeypatch, no_match_response())
    writer = FakeWriter()

    state = base_state("profit vs revenue")
    out = await individual_report_node(state, writer)

    assert "route_to" not in out
    assert writer.of_type("employee_selection")


@pytest.mark.parametrize("term,candidates,shares", [
    ("dsdsfdsfsd", [{"employee_name": "Dileep Anumula", "employee_number": "TUS2"}], False),
    ("calgary alberta canada", [{"employee_name": "Aa employee", "employee_number": "E1"}], False),
    ("dileep", [{"employee_name": "Dileep Anumula", "employee_number": "TUS2"}], True),
    ("anum", [{"employee_name": "Dileep Anumula", "employee_number": "TUS2"}], True),
    ("tus2", [{"employee_name": "Dileep Anumula", "employee_number": "TUS2"}], True),
])
def test_a_fuzzy_only_match_shares_no_name_word(term, candidates, shares):
    assert individual_report._shares_a_name_word(term, candidates) is shares


class TestARequestIsNeverAName:
    """Live: a manager's "Write a follow-up email" - four name-shaped words -
    was guessed to be an employee and answered "I'm unable to reach the HR
    system right now". A message that opens with an instruction verb or a
    question word is a request, never somebody's name."""

    @pytest.mark.parametrize("query", [
        "Write a follow-up email", "write an email", "draft a reply",
        "explain revenue", "summarize this", "translate this please",
        "what is photosynthesis", "how are you", "why", "can you help",
    ])
    def test_not_a_name(self, query):
        from services.classify_node import _is_bare_person_fragment
        assert _is_bare_person_fragment(query, False) is False

    @pytest.mark.parametrize("query", ["arshdeep", "Rahul Sharma", "a khan test", "geo3"])
    def test_real_names_still_are(self, query):
        from services.classify_node import _is_bare_person_fragment
        assert _is_bare_person_fragment(query, False) is True


class TestAFailedLookupOfAGuessAlsoHandsBack:
    """Live, a manager/HR user's "photosynthesis" or "Write a follow-up
    email" got "I cannot retrieve attendance or leave information for this
    employee" or "I'm unable to reach the HR system right now". Not only a
    no-match: ANY failure to find the guessed person withdraws the guess, so
    general chat works the same for every role."""

    @pytest.mark.parametrize("response", [
        {"http_status": 403, "body": {"success": False}},
        {"http_status": 200, "body": {"success": False, "data": {}}},
        {"http_status": 200, "body": {"success": False, "message": "Please enter at least 2 characters.",
                                      "data": {"action_required": "search_employee"}}},
    ])
    async def test_an_erp_refusal(self, monkeypatch, response):
        mock_extraction(monkeypatch, employee_name="photosynthesis")
        patch_leave_api(monkeypatch, response)
        writer = FakeWriter()
        out = await individual_report_node(_guessed("photosynthesis"), writer)
        assert out["route_to"] == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE
        assert writer.of_type("done") == []
        # Not even the status line: "tough" showed "Checking that team
        # member's leave request..." before a conversational reply.
        assert writer.of_type("fetching_individual_report") == []

    @pytest.mark.parametrize("exc", ["ErpApiTimeout", "ErpApiUnavailable"])
    async def test_erp_unreachable(self, monkeypatch, exc):
        import services.erp_client as erp_client
        mock_extraction(monkeypatch, employee_name="photosynthesis")

        async def _down(*a, **k):
            raise getattr(erp_client, exc)("down")

        monkeypatch.setattr(erp_client, "get_team_pending_leaves", _down)
        writer = FakeWriter()
        out = await individual_report_node(_guessed("photosynthesis"), writer)
        assert out["route_to"] == individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE
        assert writer.of_type("done") == []

    async def test_a_named_lookup_with_erp_down_still_says_so(self, monkeypatch):
        """Not a guess (the manager asked about someone): the outage message
        stays, nothing is handed to general chat."""
        import services.erp_client as erp_client
        mock_extraction(monkeypatch, employee_name="Arshdeep")

        async def _down(*a, **k):
            raise erp_client.ErpApiUnavailable("down")

        monkeypatch.setattr(erp_client, "get_team_pending_leaves", _down)
        writer = FakeWriter()
        state = _guessed("show Arshdeep leave requests", report_subject_was_guessed=False)
        out = await individual_report_node(state, writer)
        assert "route_to" not in out
        assert writer.of_type("done")[0]["data"]["answer"] == individual_report._ERP_UNAVAILABLE_MESSAGE

