"""What a team capability says when it cannot answer — and the difference
between "you may not see this" and "the HR system is unwell".

Reported live, with a screenshot: an employee asked "show my team attendacne"
and was answered

    I'm unable to reach the HR system right now - please try again shortly.

That is an infrastructure sentence for what is really a permission answer. It
blames the system for a rule, invites a retry that can never succeed, and
hides the thing the user needed to be told - that this is someone else's data
and they can still check their own.

Two distinct causes, both covered here:

  * the ROLE LOOKUP itself failed (the node's own /leave/context call), so
    the node reported the feature as down when what it could not do was work
    out who was asking;
  * erp-api ANSWERED the data call with a refusal (401/403, or a body that
    says so in words) and the client surfaces that as an exception on routes
    that have not opted into reading the body.

The decision is made from erp-api's own response - the status it sent and the
message it sent - not from a guess about the caller.
"""

import pytest

import services.attendance as attendance_mod
import services.erp_client as erp_client
import services.hr_graph as hr_graph
import services.individual_report as individual_report
import services.permission_service as permission_service

OUTAGE = "I'm unable to reach the HR system right now — please try again shortly."
VERIFY = "I couldn't verify your access in time — please try again in a moment."


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

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

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


def _state(**flags):
    state = {"query": "show my team attendacne", "intent": "HRMS_TEAM_ATTENDANCE_QUERY",
             "usage_events": [], "bearer_token": "caller-token", "company_id": 1,
             "conversation_id": "conv-1", "has_date_expression": False}
    state.update(flags)
    return state


async def _context_ok(token, **kwargs):
    return {"http_status": 200, "body": {"success": True,
                                         "data": {"is_manager": False, "is_hr": False}}}


def _raises(exc):
    async def _f(token, **kwargs):
        raise exc
    return _f


def _returns(body, status=200):
    async def _f(token, **kwargs):
        return {"http_status": status, "body": body}
    return _f


# =============================================================================
# Reading erp-api's answer
# =============================================================================

class TestReadingErpsAnswer:

    @pytest.mark.parametrize("status", [401, 403])
    def test_a_permission_status_is_a_refusal(self, status):
        assert permission_service.erp_refused_for_permission(status_code=status) is True

    @pytest.mark.parametrize("message", [
        "You can only view your own team.",
        "I cannot retrieve information for other employees.",
        "Employee not found in your team",
        "You do not have permission to view this.",
        "This action is only available to managers.",
        "Unauthorized",
    ])
    def test_refusal_wording_is_a_refusal_whatever_the_status(self, message):
        """erp-api does not always use 403 for these, so the wording is read
        too - and vice versa, which is why both checks exist."""
        assert permission_service.erp_refused_for_permission(
            status_code=500, message=message) is True

    @pytest.mark.parametrize("status,message", [
        (500, "Internal server error"),
        (400, "Attendance is locked for this date."),
        (None, None),
        (502, None),
    ])
    def test_everything_else_is_not_a_refusal(self, status, message):
        """A real outage and a real business error must keep their own
        answers - calling those "not available" would be a false claim about
        the caller's access."""
        assert permission_service.erp_refused_for_permission(
            status_code=status, message=message) is False

    def test_it_reads_the_exception_the_client_raises(self):
        exc = erp_client.ErpApiUnavailable(
            "forbidden", status_code=403, body={"message": "You can only view your own team."})
        assert permission_service.erp_refused_for_permission(exc) is True

        outage = erp_client.ErpApiUnavailable("connection error")
        assert permission_service.erp_refused_for_permission(outage) is False


# =============================================================================
# Team attendance — the reported query
# =============================================================================

class TestTeamAttendanceAnswers:

    @pytest.fixture(autouse=True)
    def _plain_token(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context_ok)

    async def _run(self, monkeypatch, data_call, **flags):
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", data_call)
        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(_state(**flags), writer)
        return result["response_text"], writer

    async def test_an_employee_gets_the_card_not_an_outage(self, monkeypatch):
        text, writer = await self._run(
            monkeypatch, _returns({"success": True, "data": {}}),
            is_manager=False, is_hr_role=False)

        assert writer.of_type("access_notice")
        assert text != OUTAGE

    @pytest.mark.parametrize("exc", [
        erp_client.ErpApiUnavailable("forbidden", status_code=403,
                                     body={"message": "You can only view your own team."}),
        erp_client.ErpApiUnauthorized("token rejected", status_code=401, body={}),
        erp_client.ErpApiUnavailable("err", status_code=500,
                                     body={"message": "I cannot retrieve information for other employees."}),
    ])
    async def test_an_erp_permission_refusal_shows_the_card(self, monkeypatch, exc):
        """The exact reported symptom: erp-api refuses, and the user is told
        the HR system is down."""
        text, writer = await self._run(monkeypatch, _raises(exc), is_manager=True)

        assert writer.of_type("access_notice"), f"no card for {exc!r}"
        assert text != OUTAGE

    async def test_a_genuine_outage_still_reads_as_one(self, monkeypatch):
        """The other half of the contract: when erp-api really did not reply,
        saying so is correct, and claiming a permission rule would not be."""
        text, writer = await self._run(
            monkeypatch, _raises(erp_client.ErpApiUnavailable("connection error")),
            is_manager=True)

        assert text == OUTAGE
        assert writer.of_type("access_notice") == []

    async def test_a_business_error_keeps_erps_own_words(self, monkeypatch):
        text, _ = await self._run(
            monkeypatch,
            _raises(erp_client.ErpApiUnavailable(
                "locked", status_code=400,
                body={"message": "Attendance is locked for this date."})),
            is_manager=True)

        assert text == "Attendance is locked for this date."


class TestAFailedRoleLookupIsNotAnOutage:
    """The node's own /leave/context call - reached when the graph's gate
    left no answer on the state. What fails there is "who is asking?", not
    the team feature."""

    async def _run(self, monkeypatch, claims, **flags):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: claims)
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context",
                            _raises(erp_client.ErpApiUnavailable("connection error")))
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary",
                            _returns({"success": True, "data": {}}))
        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(_state(**flags), writer)
        return result["response_text"], writer

    async def test_it_no_longer_claims_the_hr_system_is_down(self, monkeypatch):
        text, _ = await self._run(monkeypatch, {})

        assert text != OUTAGE
        assert text == VERIFY

    @pytest.mark.parametrize("role", ["manager", "hr", "admin"])
    async def test_a_privileged_jwt_answers_without_the_round_trip(self, monkeypatch, role):
        """The JWT already names the role, so an erp-api blip on the role
        lookup must not cost a manager their answer."""
        text, writer = await self._run(monkeypatch, {"role_name": role})

        assert text not in (OUTAGE, VERIFY)
        assert writer.of_type("access_notice") == []

    async def test_the_timeout_half_behaves_the_same(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context",
                            _raises(erp_client.ErpApiTimeout("slow")))
        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(_state(), writer)

        assert result["response_text"] == VERIFY


class TestTheSameForTeamLeaveAndTeamMembers:
    """All three team capabilities share the shape, so they share the fix."""

    @pytest.fixture(autouse=True)
    def _plain_token(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context_ok)

    async def test_team_leave_shows_the_card_on_an_erp_refusal(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _raises(
            erp_client.ErpApiUnavailable("forbidden", status_code=403,
                                         body={"message": "You can only view your own team."})))

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            _state(query="show my team pending leaves", intent="HRMS_TEAM_LEAVE_QUERY",
                   is_manager=True), writer)

        assert writer.of_type("access_notice")
        assert result["response_text"] != OUTAGE

    async def test_team_members_shows_the_card_on_an_erp_refusal(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_team_members", _raises(
            erp_client.ErpApiUnavailable("forbidden", status_code=403,
                                         body={"message": "You can only view your own team."})))

        writer = FakeWriter()
        result = await hr_graph.team_members_node(
            _state(query="who is on my team", intent="HRMS_TEAM_MEMBERS_QUERY",
                   is_manager=True), writer)

        assert writer.of_type("access_notice")
        assert result["response_text"] != OUTAGE

    async def test_team_leave_still_reports_a_genuine_outage(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves",
                            _raises(erp_client.ErpApiUnavailable("connection error")))

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            _state(query="show my team pending leaves", intent="HRMS_TEAM_LEAVE_QUERY",
                   is_manager=True), writer)

        assert result["response_text"] == OUTAGE
        assert writer.of_type("access_notice") == []


class TestIndividualReportRoleLookup:
    """Same defect, same fix, on the named-employee lookups."""

    @pytest.fixture(autouse=True)
    def _no_extraction_call(self, monkeypatch):
        async def _fake(query, today=None):
            return {"employee_id": None, "employee_name": None,
                    "attendance_date": None, "asserted_status": None}, None
        monkeypatch.setattr(individual_report.ai_service,
                            "extract_individual_report_fields", _fake)

        async def _no_leaves(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(individual_report.erp_client, "get_team_leaves", _no_leaves)

    async def test_a_failed_role_lookup_does_not_read_as_an_outage(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})
        monkeypatch.setattr(individual_report.erp_client, "get_leave_context",
                            _raises(erp_client.ErpApiUnavailable("connection error")))

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            _state(query="show Ayush leave requests", intent="manager_leave_request_lookup"),
            writer)

        # Note the hyphen: individual_report's copy uses "-" where the graph
        # nodes use an em dash. Pinned as it ships rather than quietly
        # normalised here.
        assert result["response_text"] == (
            "I couldn't verify your access in time - please try again in a moment.")
        assert result["response_text"] != individual_report._ERP_UNAVAILABLE_MESSAGE

    @pytest.mark.parametrize("role", ["manager", "hr", "admin"])
    async def test_a_privileged_jwt_still_gets_through(self, monkeypatch, role):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims",
                            lambda token: {"role_name": role})
        monkeypatch.setattr(individual_report.erp_client, "get_leave_context",
                            _raises(erp_client.ErpApiUnavailable("connection error")))

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            _state(query="show Ayush leave requests", intent="manager_leave_request_lookup"),
            writer)

        assert result["response_text"] != individual_report.NOT_A_MANAGER_MESSAGE
        assert "couldn't verify your access" not in result["response_text"]
