"""One question about one person must always render the same way.

QA screenshot: a manager asked about B Sharma twice and got two different
UIs for the identical sentence - a titled "Leave Request - B Sharma /
Direct report" card the first time, a bare grey chat bubble the second.

The cause was structural, not cosmetic. individual_report_node emitted the
`individual_leave_request` event only when there were rows to show:

    zero pending -> ['fetching_individual_report', 'done']
    one pending  -> ['fetching_individual_report', 'individual_leave_request', 'done']

so "no pending leave requests" had no card to render into and fell back to
whatever the client does with plain text. The two payloads also disagreed:
the empty one omitted `total_pending_leaves`, which the populated one
carried, so a renderer keying off that field saw two shapes for one card.

These tests pin the contract that fixes it: the same event, with the same
keys, for every outcome. They are about SHAPE, not wording - the wording
differences are asserted in test_individual_report.py.

Deliberately NOT the rule for team_leave_query_node: FR-07.1 AC#6 requires
the bare "Great news!" line and no card for an empty TEAM queue. That is a
different card, and test_access_notice.py pins it the other way.
"""

import pytest

import services.individual_report as individual_report
import services.erp_client as erp_client


EMPLOYEE = {"employee_id": 42, "employee_name": "B Sharma",
            "designation": "Engineer", "emp_no": "bs1"}

PENDING_ROW = {
    "employee_name": "B Sharma", "leave_type": "Casual Leave",
    "leave_type_slug": "casual_leave", "from_date": "2026-09-20",
    "to_date": "2026-09-20", "leave_count": "1", "status_name": "pending",
}

#: Every key the card is built from. The point of the fix is that this set
#: does not depend on whether there were any rows.
CARD_KEYS = {"employee", "leaves", "team_wide", "total_pending_leaves",
             "leave_type_filter"}


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def types(self):
        return [e.get("type") for e in self.events]

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]

    def done(self):
        return self.of_type("done")[0]


@pytest.fixture(autouse=True)
def _report_store(monkeypatch):
    store = {}
    monkeypatch.setattr(individual_report.leave_slot_service, "get_report_state",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(individual_report.leave_slot_service, "set_report_state",
                        lambda c, k, s: store.__setitem__((str(c), k), s))
    monkeypatch.setattr(individual_report.leave_slot_service, "clear_report_state",
                        lambda c, k: store.pop((str(c), k), None))
    return store


@pytest.fixture(autouse=True)
def _names_b_sharma(monkeypatch):
    async def _extract(query, today):
        return {"employee_id": 42, "employee_name": "B Sharma",
                "uses_pronoun": False, "attendance_date": None,
                "attendance_status": None}, None
    monkeypatch.setattr(individual_report.ai_service,
                        "extract_individual_report_fields", _extract)


def patch_leaves(monkeypatch, leaves, total=None):
    async def _fake(bearer_token, company_id=None, conversation_id=None,
                    employee_id=None, employee_name=None):
        return {"http_status": 200, "body": {"success": True, "data": {
            "employee": EMPLOYEE,
            "total_pending_leaves": len(leaves) if total is None else total,
            "leaves": list(leaves),
        }}}
    monkeypatch.setattr(erp_client, "get_team_pending_leaves", _fake)


def state(query="show leave request of B Sharma"):
    return {"query": query, "intent": individual_report.LEAVE_REQUEST_INTENT,
            "usage_events": [], "bearer_token": "t", "company_id": 1,
            "conversation_id": "conv-1", "is_manager": True}


async def run(monkeypatch, leaves, query="show leave request of B Sharma"):
    patch_leaves(monkeypatch, leaves)
    writer = FakeWriter()
    result = await individual_report.individual_report_node(state(query), writer)
    return writer, result


class TestTheCardIsEmittedForEveryOutcome:

    @pytest.mark.parametrize("leaves,label", [
        ([], "zero pending"),
        ([PENDING_ROW], "one pending"),
        ([PENDING_ROW, {**PENDING_ROW, "from_date": "2026-09-25"}], "two pending"),
    ])
    async def test_the_card_event_is_always_emitted(self, monkeypatch, leaves, label):
        writer, _ = await run(monkeypatch, leaves)

        assert len(writer.of_type("individual_leave_request")) == 1, (
            f"{label}: the answer must render in the same card as every other "
            f"answer about this person")

    async def test_the_event_sequence_does_not_depend_on_the_result(self, monkeypatch):
        """The exact regression: two turns, same question, different streams."""
        empty_writer, _ = await run(monkeypatch, [])
        full_writer, _ = await run(monkeypatch, [PENDING_ROW])

        assert empty_writer.types() == full_writer.types()

    @pytest.mark.parametrize("leaves", [[], [PENDING_ROW]])
    async def test_the_card_payload_has_the_same_keys_either_way(self, monkeypatch, leaves):
        writer, _ = await run(monkeypatch, leaves)

        assert set(writer.of_type("individual_leave_request")[0]["data"]) == CARD_KEYS

    @pytest.mark.parametrize("leaves", [[], [PENDING_ROW]])
    async def test_the_done_payload_has_the_same_keys_either_way(self, monkeypatch, leaves):
        """A non-streaming client and a replayed conversation read `done`,
        not the event, so it has to be consistent too."""
        writer, _ = await run(monkeypatch, leaves)

        assert set(writer.done()["data"]) == CARD_KEYS | {"answer"}

    async def test_an_empty_card_still_names_the_employee(self, monkeypatch):
        """The card's title is built from `employee` - without it the empty
        state cannot render as "Leave Request - B Sharma" at all."""
        writer, _ = await run(monkeypatch, [])

        card = writer.of_type("individual_leave_request")[0]["data"]
        assert card["employee"]["employee_name"] == "B Sharma"
        assert card["leaves"] == []
        assert card["total_pending_leaves"] == 0

    async def test_the_card_and_the_bubble_agree(self, monkeypatch):
        """`done.data` carries the card payload AND the sentence, so whichever
        the client renders from, it shows the same thing."""
        writer, result = await run(monkeypatch, [])

        done = writer.done()["data"]
        card = writer.of_type("individual_leave_request")[0]["data"]
        assert done["answer"] == result["response_text"]
        assert all(done[k] == card[k] for k in CARD_KEYS)


class TestCountsAreNotInvented:

    async def test_zero_is_reported_as_zero(self, monkeypatch):
        writer, _ = await run(monkeypatch, [])
        assert writer.of_type("individual_leave_request")[0]["data"][
            "total_pending_leaves"] == 0

    async def test_the_count_survives_a_populated_result(self, monkeypatch):
        writer, _ = await run(monkeypatch, [PENDING_ROW])
        assert writer.of_type("individual_leave_request")[0]["data"][
            "total_pending_leaves"] == 1
