"""Acting on the team pending-leave card that is already on the screen.

Reported: a team with ONE pending request. The manager asks for their team's
pending leaves, gets the card, and types "approve casual leave" - and is
asked "Which request would you like me to approve?", one turn after the only
candidate was put on the screen.

Two things were missing, and both had to land for the instruction to resolve:

1. THE CARD FORGOT WHAT IT SHOWED. leave_approval._resolve_target answers a
   target-less instruction from `last_leave_requests`, which individual_
   report writes after every lookup - including its own team-wide one.
   team_leave_query_node, the node that actually serves "show my team's
   pending leaves", wrote nothing, so there was never anything to resolve
   against.

2. A NAMED LEAVE TYPE DID NOT NARROW A REMEMBERED LIST. "approve casual
   leave" says which request is meant. The per-employee branch already
   honoured that; the remembered-list branch went straight to "which one?".

The guard on the second is what keeps it honest: a remembered TEAM list
spans people, so narrowing it by type could pick an employee the manager
never named. It narrows only when every remembered row belongs to one
person - which is exactly the reported case - and disambiguates otherwise.
"""

import pytest

import services.erp_client as erp_client
import services.hr_graph as hr_graph
import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node

from tests.test_team_leave_status_filter import (
    FakeWriter, base_state, leave_row, manager_context, team_leaves,
)


ONE_PENDING = [leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1)]

TWO_FOR_ONE_PERSON = [
    leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1),
    leave_row("Vikram Shah", "Sick Leave", "2026-09-22", "2026-09-23", 2),
]


@pytest.fixture
def report_store(monkeypatch):
    """Shared by both modules on purpose - the point of these tests is that
    what hr_graph writes is what leave_approval later reads."""
    store = {}

    def _get(company_id, conversation_id):
        return store.get((str(company_id), conversation_id))

    def _set(company_id, conversation_id, value):
        store[(str(company_id), conversation_id)] = value
        return True

    for mod in (hr_graph, leave_approval):
        monkeypatch.setattr(mod.leave_slot_service, "get_report_state", _get)
        monkeypatch.setattr(mod.leave_slot_service, "set_report_state", _set)
    return store


def show_team_card(monkeypatch, rows, query="show my team's pending leave requests"):
    monkeypatch.setattr(erp_client, "get_leave_context", manager_context())
    monkeypatch.setattr(erp_client, "get_team_leaves", team_leaves(rows))
    return hr_graph.team_leave_query_node(base_state(query), FakeWriter())


# =============================================================================
# 1 - The card remembers what it showed
# =============================================================================

class TestTheTeamCardRemembersItsRows:

    async def test_the_rows_are_remembered(self, monkeypatch, report_store):
        await show_team_card(monkeypatch, ONE_PENDING)

        remembered = report_store[("26", "conv-1")]["last_leave_requests"]
        assert [lv["id"] for lv in remembered] == [ONE_PENDING[0]["id"]]

    async def test_they_are_remembered_in_the_shape_an_action_needs(
            self, monkeypatch, report_store):
        """The same projection individual_report stores, so leave_approval
        reads one shape whichever list it is resolving against."""
        await show_team_card(monkeypatch, ONE_PENDING)

        row = report_store[("26", "conv-1")]["last_leave_requests"][0]
        assert row["employee_name"] == "Vikram Shah"
        assert row["leave_type"] == "Casual Leave"
        assert row["from_date"] == "2026-09-18"

    async def test_no_subject_is_remembered_for_a_team_list(
            self, monkeypatch, report_store):
        """A team list has no single subject; recording one would make
        whoever sorts first the answer to the next "his"/"her"."""
        await show_team_card(monkeypatch, ONE_PENDING)

        assert "last_employee" not in report_store[("26", "conv-1")]

    async def test_all_rows_are_remembered_not_just_the_three_shown(
            self, monkeypatch, report_store):
        """The card renders the top 3, but the instruction that follows it is
        about the queue, not about the excerpt."""
        rows = [leave_row(f"Emp {i}", "Casual Leave", f"2026-09-0{i}", f"2026-09-0{i}", 1)
                for i in range(1, 6)]
        await show_team_card(monkeypatch, rows)

        assert len(report_store[("26", "conv-1")]["last_leave_requests"]) == 5

    @pytest.mark.parametrize("query,status", [
        ("show my team's approved leaves", "approved"),
        ("show my team's cancelled leaves", "cancelled"),
        ("show all my team's leave requests", "all"),
    ])
    async def test_a_decided_list_is_not_remembered(
            self, monkeypatch, report_store, query, status):
        """These rows are already decided. Remembering them would let
        "approve it" resolve onto a request there is nothing left to
        approve."""
        rows = [leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1,
                          status_name=status)]
        await show_team_card(monkeypatch, rows, query=query)

        assert report_store == {}

    async def test_an_empty_queue_remembers_nothing(self, monkeypatch, report_store):
        await show_team_card(monkeypatch, [])

        assert report_store == {}


# =============================================================================
# 2 - The instruction that follows it resolves
# =============================================================================

@pytest.fixture
def approval_harness(monkeypatch):
    """leave_approval's own collaborators. The extractor returns action=
    approve and NO target, which is what it returns for "approve casual
    leave" - a leave type is not a target."""
    store = {}
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_manager_action",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_manager_action",
                        lambda c, k, v: bool(store.__setitem__((str(c), k), v)) or True)
    monkeypatch.setattr(leave_approval.leave_slot_service, "clear_manager_action",
                        lambda c, k: store.pop((str(c), k), None))

    async def _extract(query, today):
        return {"action": "approve", "leave_request_id": None, "employee_id": None,
                "employee_name": None, "uses_pronoun": False,
                "targets_multiple": False}, None

    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields", _extract)
    return store


def approve_state(query):
    return {"query": query, "intent": "leave_approval", "usage_events": [],
            "bearer_token": "t", "company_id": 26, "conversation_id": "conv-1",
            "is_manager": True}


class TestApproveAfterTheTeamCard:

    async def test_the_single_request_reaches_the_confirmation(
            self, monkeypatch, report_store, approval_harness):
        """The reported case, end to end: card, then "approve casual leave"."""
        await show_team_card(monkeypatch, ONE_PENDING)
        writer = FakeWriter()
        await leave_approval_node(approve_state("approve casual leave"), writer)

        assert writer.of_type("leave_approval_confirmation"), \
            "the approval flow never started"

    async def test_it_no_longer_asks_which_request(
            self, monkeypatch, report_store, approval_harness):
        await show_team_card(monkeypatch, ONE_PENDING)
        writer = FakeWriter()
        result = await leave_approval_node(approve_state("approve casual leave"), writer)

        assert "Which request" not in result["response_text"]

    async def test_the_named_type_picks_the_matching_request(
            self, monkeypatch, report_store, approval_harness):
        """One person, two pending requests: "casual" says which."""
        await show_team_card(monkeypatch, TWO_FOR_ONE_PERSON)
        writer = FakeWriter()
        await leave_approval_node(approve_state("approve casual leave"), writer)

        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_type"] == "Casual Leave"
        assert card["leave_request_id"] == TWO_FOR_ONE_PERSON[0]["id"]

    async def test_a_type_matching_both_still_asks(
            self, monkeypatch, report_store, approval_harness):
        """Naming a type that narrows nothing has resolved nothing."""
        rows = [leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1),
                leave_row("Vikram Shah", "Casual Leave", "2026-09-22", "2026-09-23", 2)]
        await show_team_card(monkeypatch, rows)
        writer = FakeWriter()
        await leave_approval_node(approve_state("approve casual leave"), writer)

        assert not writer.of_type("leave_approval_confirmation")

    async def test_a_type_that_spans_people_is_never_narrowed(
            self, monkeypatch, report_store, approval_harness):
        """The guard. Two team members, only one casual leave between them -
        narrowing would approve somebody the manager never named."""
        rows = [leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1),
                leave_row("Priya Nair", "Sick Leave", "2026-09-22", "2026-09-23", 2)]
        await show_team_card(monkeypatch, rows)
        writer = FakeWriter()
        await leave_approval_node(approve_state("approve casual leave"), writer)

        assert not writer.of_type("leave_approval_confirmation")
