"""A bare name reaches the LOOKUP as a name, not just as a route.

classify_node already routes "abc testing" after a team card to
manager_leave_request_lookup (tests/test_bare_name_continuation.py). This is
the step after it, where the live bug actually was:

    "show my team pending leaves"  -> the team card
    "abc testing"                  -> the WHOLE team's pending list, again

individual_report asks an LLM extractor who the message is about. That
extractor sees the message WITHOUT the card it continues, so a two-word
fragment with no verb and no question is its weakest possible input and its
failure mode is an empty field set - at which point the leave route fell
through to `team_wide`, which answers a question nobody asked. Because the
extractor is not deterministic, the same name worked one turn and not the
next.

The fix reuses classify_node's own _is_bare_person_fragment, so what counts
as a name is decided once, deterministically, by the same predicate that
routed the turn here in the first place.
"""

import pytest

import services.erp_client as erp_client
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, patch_leave_api,
    employee_leaves_response, name_match_response, no_match_response,
    team_leaves_response, patch_punch_api, punch_ok, TEAM_ROSTER,
    _fake_report_store, _default_extraction, _default_status_api,
)


ATTENDANCE = individual_report.ATTENDANCE_EXPLANATION_INTENT


# =============================================================================
# The regression
# =============================================================================

class TestABareNameIsUsedAsTheName:

    @pytest.mark.asyncio
    async def test_the_name_typed_is_the_name_searched(self, monkeypatch):
        """The extractor returns nothing (its live failure mode on this
        shape); the message itself has to supply the name."""
        calls = patch_leave_api(
            monkeypatch,
            name_match_response([TEAM_ROSTER[4]]),
            employee_leaves_response(),
        )
        await individual_report_node(base_state("B Geo"), FakeWriter())

        assert calls[0]["employee_name"] == "B Geo"

    @pytest.mark.asyncio
    async def test_it_does_not_answer_team_wide(self, monkeypatch):
        """The bug itself: a whole-team list in reply to one person's name."""
        patch_leave_api(
            monkeypatch,
            name_match_response([TEAM_ROSTER[4]]),
            employee_leaves_response(),
        )
        writer = FakeWriter()
        await individual_report_node(base_state("B Geo"), writer)

        assert writer.done()["data"]["team_wide"] is False

    @pytest.mark.asyncio
    async def test_the_answer_is_about_that_person(self, monkeypatch):
        patch_leave_api(
            monkeypatch,
            name_match_response([TEAM_ROSTER[4]]),
            employee_leaves_response(),
        )
        writer = FakeWriter()
        await individual_report_node(base_state("B Geo"), writer)

        assert "B Geo" in writer.done()["message"]
        assert "Your team" not in writer.done()["message"]

    @pytest.mark.asyncio
    async def test_an_extracted_name_still_wins(self, monkeypatch):
        """This is a FALLBACK. When the extractor does its job - including
        pulling a name out of a longer sentence - nothing here interferes."""
        mock_extraction(monkeypatch, employee_name="B Geo")
        calls = patch_leave_api(
            monkeypatch,
            name_match_response([TEAM_ROSTER[4]]),
            employee_leaves_response(),
        )
        await individual_report_node(
            base_state("show me B Geo's pending leave requests"), FakeWriter())

        assert calls[0]["employee_name"] == "B Geo"

    @pytest.mark.asyncio
    async def test_a_name_matching_nobody_offers_the_roster(self, monkeypatch):
        """Not a dead end when the guess is wrong: the unmatched-term path
        already answers with the caller's own team to pick from."""
        patch_leave_api(monkeypatch, no_match_response())
        writer = FakeWriter()
        await individual_report_node(base_state("Nobody Here"), writer)

        assert writer.done()["data"]["action_required"] == "select_employee"

    @pytest.mark.asyncio
    async def test_the_attendance_route_gets_it_too(self, monkeypatch):
        """A bare name after a team ATTENDANCE card continues that lookup -
        and this route has no team-wide shape, so without the fallback it
        asked "which team member?" about the one just named."""
        patch_leave_api(monkeypatch, name_match_response([TEAM_ROSTER[4]]))
        patch_punch_api(monkeypatch, punch_ok())
        writer = FakeWriter()
        await individual_report_node(base_state("B Geo", intent=ATTENDANCE), writer)

        assert "Which team member" not in writer.done()["message"]


# =============================================================================
# What must still go team-wide, or still ask
# =============================================================================

class TestTheTeamWidePathIsIntact:

    @pytest.mark.asyncio
    async def test_a_real_team_question_is_still_answered_team_wide(self, monkeypatch):
        patch_leave_api(monkeypatch, team_leaves_response())
        writer = FakeWriter()
        await individual_report_node(
            base_state("show me the pending leave requests"), writer)

        assert writer.done()["data"]["team_wide"] is True

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", [
        # Excluded by _NOT_A_NAME - a topic word and a conversational reply.
        "payroll", "yes", "pending leaves",
        # Excluded as a request REFERENCE rather than a person.
        "310",
    ])
    async def test_non_names_do_not_become_a_name_search(self, monkeypatch, query):
        calls = patch_leave_api(monkeypatch, team_leaves_response())
        await individual_report_node(base_state(query), FakeWriter())

        assert calls[0]["employee_name"] is None
