"""
Tests for the centralised leave failure layer (HEL-283):
  - services/leave_failure.py::is_failure
  - services/leave_failure.py::interpret_failure
  - services/leave_failure.py::classify

The payloads marked "live" below were captured from erp-api staging on
2026-08-19 by triggering each rejection for real, not written from the ticket.
That distinction matters: the ticket assumes structured reason codes and a
balance/blocked-date/policy taxonomy, and erp-api returns neither.
"""

import pytest

from services.leave_failure import (
    FALLBACK_MESSAGE,
    LeaveFailure,
    classify,
    interpret_failure,
    is_failure,
    local_failure,
)


# ── Live erp-api payloads ────────────────────────────────────────────────────

DUPLICATE_APPLY = {
    "success": False,
    "message": "You have already applied Casual Leave from 2026-08-20 to 2026-08-20.",
    "data": {"error": "You have already applied Casual Leave from 2026-08-20 to 2026-08-20."},
}

CANCEL_ATTENDANCE_CALCULATED = {
    "success": False,
    "message": "You cannot cancel this leave because attendance has already been calculated.",
    "data": {"error": "You cannot cancel this leave because attendance has already been calculated."},
}

CANCEL_ALREADY_CANCELLED = {
    "success": False,
    "message": "This leave request has already been cancelled.",
    "data": {"error": "This leave request has already been cancelled."},
}

APPLY_SUCCESS = {
    "success": True,
    "data": {"leave_id": 51, "status_name": "Pending"},
    "message": "Leave request submitted successfully.",
}


class TestIsFailure:
    def test_live_rejections_are_failures(self):
        """Each of the three rejections captured live from erp-api is recognised as a failure."""
        for body in (DUPLICATE_APPLY, CANCEL_ATTENDANCE_CALCULATED, CANCEL_ALREADY_CANCELLED):
            assert is_failure(body) is True

    def test_success_is_not_a_failure(self):
        """A successful apply is not misread as a failure, so the card never appears on a request that went through."""
        assert is_failure(APPLY_SUCCESS) is False

    def test_missing_success_key_is_treated_as_failure(self):
        """A body we can't read is not a success we can confirm."""
        assert is_failure({"message": "who knows"}) is True

    def test_non_dict_is_treated_as_failure(self):
        """A malformed or absent body is treated as a failure rather than assumed successful."""
        assert is_failure(None) is True
        assert is_failure("boom") is True


class TestVerbatimPassthrough:
    """AC1-AC3: the employee sees erp-api's reason, never a generic error and
    never a reworded one."""

    @pytest.mark.parametrize("body", [
        DUPLICATE_APPLY, CANCEL_ATTENDANCE_CALCULATED, CANCEL_ALREADY_CANCELLED,
    ])
    def test_message_is_passed_through_unchanged(self, body):
        """erp-api's sentence reaches the employee character for character, with no rewording or summarising."""
        result = interpret_failure(body)
        assert result.display_message == body["message"]
        assert result.is_fallback is False

    def test_no_generic_message_when_backend_explained(self):
        """When the backend did explain itself, the generic fallback is never substituted for its words."""
        result = interpret_failure(DUPLICATE_APPLY)
        assert result.display_message != FALLBACK_MESSAGE


class TestReasonCodes:
    def test_live_payloads_map_to_observed_codes(self):
        """The three live payloads resolve to the reason codes derived from their wording."""
        assert interpret_failure(DUPLICATE_APPLY).reason_code == "DUPLICATE_APPLICATION"
        assert interpret_failure(CANCEL_ALREADY_CANCELLED).reason_code == "ALREADY_CANCELLED"
        assert interpret_failure(CANCEL_ATTENDANCE_CALCULATED).reason_code == "ATTENDANCE_LOCKED"

    def test_attendance_locked_wording_from_apply_is_also_matched(self):
        """The apply flow returns a different phrasing for the same condition
        (seen live and pinned in test_leave_action.py)."""
        assert classify("Attendance is locked for date 2026-09-01") == "ATTENDANCE_LOCKED"

    def test_unrecognised_message_defaults_to_policy_rule(self):
        """Product decision (2026-08-24): an unrecognised message no longer
        omits the category — it defaults to POLICY_RULE rather than None,
        while the display_message itself is still shown exactly as erp-api
        wrote it (never reworded, never invented)."""
        result = interpret_failure({
            "success": False,
            "message": "Your manager is currently unavailable to approve this.",
        })
        assert result.reason_code == "POLICY_RULE"
        assert result.display_message == "Your manager is currently unavailable to approve this."
        assert result.is_fallback is False

    def test_ticket_categories_are_not_invented(self):
        """HEL-283 is written around INSUFFICIENT_BALANCE / BLOCKED_DATE /
        POLICY_RESTRICTION. None has ever appeared in a real erp-api response,
        so nothing may map to them until one does — a message that merely
        mentions balance must not be filed as a balance failure. It still
        gets the generic POLICY_RULE default, just not the specific one."""
        result = interpret_failure({
            "success": False,
            "message": "Your leave balance summary could not be loaded.",
        })
        assert result.reason_code != "INSUFFICIENT_BALANCE"
        assert result.reason_code == "POLICY_RULE"


class TestFallback:
    """AC5: unknown/absent detail gets a controlled fallback, never silence
    and never an invented explanation."""

    def test_missing_message_falls_back(self):
        """A body with no message at all produces the controlled fallback, not silence or an empty card."""
        result = interpret_failure({"success": False})
        assert result.display_message == FALLBACK_MESSAGE
        assert result.is_fallback is True
        assert result.reason_code == "POLICY_RULE"

    def test_empty_and_whitespace_message_falls_back(self):
        """An empty or whitespace-only message is treated as no explanation and falls back."""
        assert interpret_failure({"success": False, "message": ""}).is_fallback is True
        assert interpret_failure({"success": False, "message": "   "}).is_fallback is True

    def test_non_string_message_falls_back(self):
        """A message that is not text (a nested object) cannot be displayed and falls back."""
        assert interpret_failure({"success": False, "message": {"nested": "thing"}}).is_fallback is True

    def test_data_error_used_only_when_message_absent(self):
        """data.error is used as a backstop when message is missing, since the two are always identical."""
        result = interpret_failure({"success": False, "data": {"error": "Leave already approved."}})
        assert result.display_message == "Leave already approved."
        assert result.is_fallback is False


class TestTechnicalLeakGuard:
    """AC5: raw technical detail must never reach an employee. erp-api offers
    no guarantee against it on unhandled paths, so the layer refuses to
    display anything carrying internal markers."""

    @pytest.mark.parametrize("leak", [
        "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry",
        "Exception: Call to a member function format() on null",
        "#0 /var/www/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54)",
        "<!DOCTYPE html><html><head><title>500 Server Error</title>",
        "Undefined index: leave_type_slug",
    ])
    def test_technical_strings_are_replaced_by_the_fallback(self, leak):
        """SQL errors, exceptions, stack frames and HTML error pages are replaced wholesale, never shown."""
        result = interpret_failure({"success": False, "message": leak})
        assert result.display_message == FALLBACK_MESSAGE
        assert result.is_fallback is True
        assert leak not in result.display_message

    def test_leaky_message_falls_through_to_clean_data_error(self):
        """A leaking message falls through to a clean data.error rather than straight to the fallback."""
        result = interpret_failure({
            "success": False,
            "message": "SQLSTATE[23000]: Integrity constraint violation",
            "data": {"error": "This leave request has already been cancelled."},
        })
        assert result.display_message == "This leave request has already been cancelled."
        assert result.is_fallback is False


class TestContract:
    def test_result_is_immutable(self):
        """The display message is the employee-facing text; nothing
        downstream may edit it in place."""
        result = interpret_failure(DUPLICATE_APPLY)
        assert isinstance(result, LeaveFailure)
        with pytest.raises(Exception):
            result.display_message = "something else"


# Live erp-api payload captured 2026-08-19 — a monthly cap, not a balance
# shortfall. The distinction matters: see TestMonthlyLimit.
MONTHLY_LIMIT = {
    "success": False,
    "message": "Monthly sick leave limit reached. Monthly limit: 2, already applied: 2, requested: 1.",
    "data": {"error": "Monthly sick leave limit reached. Monthly limit: 2, already applied: 2, requested: 1."},
}


class TestMonthlyLimit:
    def test_monthly_cap_maps_to_its_own_code(self):
        """The monthly quota rejection resolves to its own code rather than being folded into another."""
        assert interpret_failure(MONTHLY_LIMIT).reason_code == "MONTHLY_LIMIT_REACHED"

    def test_monthly_cap_is_not_filed_as_insufficient_balance(self):
        """An employee can hit a monthly cap while still holding plenty of
        annual balance for that leave type, so the two are different failures.
        Filing this under INSUFFICIENT_BALANCE would tell them to check a
        balance that isn't the problem."""
        assert interpret_failure(MONTHLY_LIMIT).reason_code != "INSUFFICIENT_BALANCE"

    def test_numbers_reach_the_employee_without_being_parsed(self):
        """The limit/applied/requested context AC asks for is already inside
        erp-api's sentence. Passing it through verbatim delivers that context
        without parsing prose into fields that erp-api never promised."""
        result = interpret_failure(MONTHLY_LIMIT)
        assert "Monthly limit: 2" in result.display_message
        assert "already applied: 2" in result.display_message
        assert "requested: 1" in result.display_message
        assert result.is_fallback is False

    def test_any_leave_type_can_hit_the_cap(self):
        """The cap is not sick-leave specific — the pattern must not bind to
        one leave type."""
        for kind in ("sick", "casual", "earned", "short"):
            body = {"success": False,
                    "message": f"Monthly {kind} leave limit reached. Monthly limit: 2, "
                               f"already applied: 2, requested: 1."}
            assert interpret_failure(body).reason_code == "MONTHLY_LIMIT_REACHED"

    def test_cap_is_not_mistaken_for_a_duplicate_application(self):
        """Regression: the cap message contains the substring 'already
        applied: 2', which a loose DUPLICATE_APPLICATION pattern swallowed —
        reporting a quota failure as a duplicate. The duplicate pattern is
        anchored to erp-api's actual phrasing ('You have already applied
        Casual Leave from ...') to keep the two apart."""
        assert interpret_failure(MONTHLY_LIMIT).reason_code == "MONTHLY_LIMIT_REACHED"
        assert interpret_failure(DUPLICATE_APPLY).reason_code == "DUPLICATE_APPLICATION"


class TestBadgeMapping:
    """Codes and badges are separate layers: codes stay precise, badges are
    the coarse grouping the mockup renders. The mapping table is the
    'approved mapping matrix' HEL-283's QA section requires."""

    def test_balance_maps_to_the_balance_badge(self):
        """A balance shortfall carries the balance badge."""
        from services.leave_failure import BADGE_BALANCE, badge_for
        assert badge_for("INSUFFICIENT_BALANCE") == BADGE_BALANCE

    def test_blocked_date_maps_to_its_badge(self):
        """Backed by /api/v1/ai/leave/holidays as of 2026-08-20."""
        from services.leave_failure import BADGE_BLOCKED_DATE, badge_for
        assert badge_for("BLOCKED_DATE") == BADGE_BLOCKED_DATE

    def test_policy_codes_share_the_policy_badge(self):
        """Several distinct policy codes group under one policy badge, which is why codes and badges are separate layers."""
        from services.leave_failure import BADGE_POLICY_RULE, badge_for
        assert badge_for("LEAVE_TYPE_NOT_IN_POLICY") == BADGE_POLICY_RULE
        assert badge_for("REQUIRES_CONFIRMATION") == BADGE_POLICY_RULE

    def test_unmapped_codes_get_no_badge_pending_ba_signoff(self):
        """These are real failures that fit none of the mockup's three boxes.
        No badge is the correct render — the employee still sees the exact
        reason — and forcing them into a box is how a 'Balance' badge ends up
        on a failure that has nothing to do with balance."""
        from services.leave_failure import badge_for
        for code in ("ALREADY_CANCELLED", "ATTENDANCE_LOCKED", "MONTHLY_LIMIT_REACHED"):
            assert badge_for(code) is None

    def test_duplicate_application_maps_to_its_own_badge(self):
        """2026-08-26: a duplicate request is common enough (and distinct
        enough from a blocked date or a policy rule) to get its own badge
        rather than sitting unmapped — matching the Duplicate Request label
        used elsewhere for the same condition."""
        from services.leave_failure import BADGE_DUPLICATE_REQUEST, badge_for, badge_label_for
        assert badge_for("DUPLICATE_APPLICATION") == BADGE_DUPLICATE_REQUEST
        assert badge_label_for("DUPLICATE_APPLICATION") == "Duplicate Request"

    def test_no_code_means_no_badge(self):
        """An absent code yields no badge rather than a default one."""
        from services.leave_failure import badge_for
        assert badge_for(None) is None
        assert badge_for("") is None


class TestCardShape:
    """One payload shape across apply, cancel and eligibility, so the three
    can't drift apart — the duplication HEL-283 exists to prevent."""

    def test_title_comes_from_the_action_not_the_message(self):
        """The card title is chosen from which action failed, so no interpretation of the message is involved."""
        from services.leave_failure import build_card
        card = build_card("apply_leave", interpret_failure(DUPLICATE_APPLY))["failure"]
        assert card["title"] == "Leave Request Not Completed"
        assert build_card("cancel_leave", interpret_failure(CANCEL_ALREADY_CANCELLED))["failure"]["title"] \
            == "Cancellation Not Completed"
        assert build_card("leave_eligibility", interpret_failure(DUPLICATE_APPLY))["failure"]["title"] \
            == "Eligibility Check Not Completed"

    def test_card_carries_the_full_contract(self):
        """The card carries exactly the agreed fields, including the Status / Reason Code / Display Message trio the story names."""
        from services.leave_failure import build_card
        card = build_card("apply_leave", interpret_failure(MONTHLY_LIMIT),
                          next_action="Want to try a different month?")["failure"]
        assert set(card) == {"status", "action", "title", "display_message",
                             "reason_code", "badge", "badge_label", "sub_title",
                             "is_fallback", "next_action", "next_actions"}
        # HEL-283 names Status / Reason Code / Display Message as the trio the
        # employee-facing failure response must carry.
        assert card["status"] == "REJECTED"
        # Index-aligned lists, one entry per reason.
        assert card["display_message"] == [MONTHLY_LIMIT["message"]]
        assert card["reason_code"] == ["MONTHLY_LIMIT_REACHED"]
        assert card["badge"] == [None]
        assert card["badge_label"] == [None]
        # Scalar, not a list — for the primary reason only.
        assert card["sub_title"] is None
        assert card["next_action"] == "Want to try a different month?"
        # No chips passed -> [], not None, so a renderer can iterate directly.
        assert card["next_actions"] == []

    def test_next_actions_chips_are_carried_alongside_the_spoken_sentence(self):
        """HA-163 Sprint 2 spec: the card's quick-reply chips are a separate,
        structured field from the spoken next_action sentence — a renderer
        wants distinct {label, action} buttons, not a sentence to parse."""
        from services.leave_failure import build_card, chip
        card = build_card(
            "apply_leave", interpret_failure(MONTHLY_LIMIT),
            next_action="Would you like to check your balance instead?",
            next_actions=[chip("Check Available Balance", "check_leave_balance"),
                          chip("Apply for 3 Days", "apply_reduced_days")],
        )["failure"]
        assert card["next_action"] == "Would you like to check your balance instead?"
        assert card["next_actions"] == [
            {"label": "Check Available Balance", "action": "check_leave_balance"},
            {"label": "Apply for 3 Days", "action": "apply_reduced_days"},
        ]

    def test_top_level_reason_code_and_badge_label_mirror_the_primary_reason(self):
        """The outer dict (sibling to is_failure/failure, same level as
        is_failure itself) carries flat, scalar mirrors of the PRIMARY
        reason's code and badge label — so a consumer that only cares about
        the leading reason can read card["reason_code"] / card["badge_label"]
        directly, without unpacking failure.reason_code[0]/badge_label[0]."""
        from services.leave_failure import build_card
        card = build_card("cancel_leave", interpret_failure(DUPLICATE_APPLY))
        assert set(card) == {"is_failure", "reason_code", "badge_label", "failure"}
        assert card["reason_code"] == card["failure"]["reason_code"][0] == "DUPLICATE_APPLICATION"
        # DUPLICATE_APPLICATION now has an approved badge (2026-08-26), so
        # the top-level mirror carries its label, same as the nested one.
        assert card["badge_label"] == "Duplicate Request"

        # An actually-unmapped code still gets no badge, so the mirror is
        # None too, not a guess.
        unmapped_card = build_card("cancel_leave", interpret_failure(
            {"success": False, "message": "This leave request has already been cancelled."}))
        assert unmapped_card["badge_label"] is None

        policy_card = build_card("cancel_leave", interpret_failure(
            {"success": False, "message": "Policy LP-14: cancel at least 48 hours before start."}))
        assert policy_card["reason_code"] == "POLICY_RULE"
        assert policy_card["badge_label"] == "Policy rule"

    def test_top_level_reason_code_is_the_primary_ones_even_with_multiple_reasons(self):
        """With several reasons on one card, the flat top-level mirror still
        reflects only the FIRST (primary) one — the same one sub_title and
        is_fallback already single out — never the last or a merged value."""
        from services.leave_failure import build_card, local_failure
        card = build_card("apply_leave", [
            interpret_failure(DUPLICATE_APPLY),
            local_failure("2026-08-15 is a company holiday (Quarter-End Freeze).", "BLOCKED_DATE"),
        ])
        assert card["reason_code"] == "DUPLICATE_APPLICATION"
        assert card["failure"]["reason_code"] == ["DUPLICATE_APPLICATION", "BLOCKED_DATE"]

    def test_several_reasons_stay_index_aligned(self):
        """Codes, badges and messages remain positionally aligned so the UI can render one bullet per reason with its own chip."""
        from services.leave_failure import build_card, local_failure
        card = build_card("apply_leave", [
            interpret_failure(MONTHLY_LIMIT),
            local_failure("2026-07-14 is a company holiday (Good Wednesday).", "BLOCKED_DATE"),
            local_failure("You have 0 day(s) remaining, but this request needs 1.0.",
                          "INSUFFICIENT_BALANCE"),
        ])["failure"]
        assert card["reason_code"] == [
            "MONTHLY_LIMIT_REACHED", "BLOCKED_DATE", "INSUFFICIENT_BALANCE"]
        # Null where the code has no approved badge, so positions still line up.
        assert card["badge"] == [None, "blocked_date", "balance"]
        # erp-api's sentence leads; ours follow, one entry each.
        assert card["display_message"][0].startswith("Monthly sick leave limit reached.")
        assert "Good Wednesday" in card["display_message"][1]
        assert "0 day(s) remaining" in card["display_message"][2]
        assert len(card["reason_code"]) == len(card["badge"]) == len(card["display_message"])

    def test_unrecognised_reason_gets_the_policy_rule_default(self):
        """An unrecognised message still gets a real code/badge (POLICY_RULE)
        rather than a null slot — the message itself is still shown exactly
        as erp-api wrote it either way."""
        from services.leave_failure import build_card
        card = build_card("apply_leave", interpret_failure(
            {"success": False, "message": "Your manager is unavailable."}))["failure"]
        assert card["reason_code"] == ["POLICY_RULE"]
        assert card["badge"] == ["policy_rule"]
        assert card["display_message"] == ["Your manager is unavailable."]

    def test_cancel_policy_rule_card_matches_the_approved_mockup(self):
        """Reproduces the exact mockup card (2026-08-24): 'Cancellation Not
        Completed' title, 'Blocked by leave policy' sub_title, 'Policy rule'
        badge label, and erp-api's own LP-14 sentence shown untouched."""
        from services.leave_failure import build_card
        body = {
            "success": False,
            "message": (
                "Policy LP-14: approved leave can only be cancelled at least "
                "48 hours before the start date. Your leave starts on 06 Aug 2026."
            ),
        }
        card = build_card("cancel_leave", interpret_failure(body))["failure"]
        assert card["title"] == "Cancellation Not Completed"
        assert card["sub_title"] == "Blocked by leave policy"
        assert card["reason_code"] == ["POLICY_RULE"]
        assert card["badge"] == ["policy_rule"]
        assert card["badge_label"] == ["Policy rule"]
        assert card["display_message"] == [body["message"]]

    def test_duplicate_application_and_blocked_date_get_their_own_subtitles(self):
        """Live UX request (2026-08-24): a per-reason-code subtitle, same
        idea as the POLICY_RULE one — applies on apply_leave too, not just
        cancel. Scalar string, not a list."""
        from services.leave_failure import build_card
        dup_card = build_card("apply_leave", interpret_failure(DUPLICATE_APPLY))["failure"]
        assert dup_card["sub_title"] == "Requested date is a duplicate"

        blocked_card = build_card(
            "apply_leave",
            local_failure("2026-08-15 is a company holiday (Quarter-End Freeze).", "BLOCKED_DATE"),
        )["failure"]
        assert blocked_card["sub_title"] == "Requested date is blocked"

    def test_unknown_action_still_produces_a_usable_card(self):
        """An unrecognised action still yields a renderable card rather than an error."""
        from services.leave_failure import build_card
        card = build_card("something_new", interpret_failure(DUPLICATE_APPLY))["failure"]
        assert card["title"] == "Request Not Completed"


class TestLocalFailure:
    """Failures Helix determines itself — the balance pre-check and the
    unconfigured-leave-type check. Not fallbacks: the text IS the reason."""

    def test_local_failure_is_not_marked_as_fallback(self):
        """A reason Helix determined from erp-api data is a real reason, not a fallback."""
        from services.leave_failure import local_failure
        f = local_failure("You only have 0 day(s) remaining, but this request needs 2.",
                          "INSUFFICIENT_BALANCE")
        assert f.is_fallback is False
        assert f.reason_code == "INSUFFICIENT_BALANCE"

    def test_local_failure_gets_a_badge_like_any_other(self):
        """Locally determined reasons are badged on the same rules as backend ones."""
        from services.leave_failure import BADGE_BALANCE, build_card, local_failure
        card = build_card("apply_leave", local_failure("...", "INSUFFICIENT_BALANCE"))["failure"]
        assert card["badge"] == [BADGE_BALANCE]
        assert card["display_message"] == ["..."]


class TestUnknownErrorCodes:
    """AC5: 'If the LMS returns only a technical error code, unknown error
    code, or does not provide a user-facing reason, Helix AI must display a
    controlled fallback message.' These strings are clean — they carry no
    stack trace or SQL — but none of them explains anything to an employee."""

    @pytest.mark.parametrize("code", [
        "ERR_5521",
        "E1042",
        "500",
        "LEAVE_APPLY_FAILED",
        "Failed.",
        "ERR 5521",
        "LEAVE ERROR 42",
    ])
    def test_bare_codes_get_the_controlled_fallback(self, code):
        """A bare error code explains nothing to an employee, so it is replaced by the controlled fallback."""
        result = interpret_failure({"success": False, "message": code})
        assert result.display_message == FALLBACK_MESSAGE
        assert result.is_fallback is True
        assert code not in result.display_message

    def test_fallback_text_matches_the_wording_in_ac5(self):
        """The fallback wording matches the story text exactly, pinned so it cannot drift."""
        assert FALLBACK_MESSAGE == (
            "Unable to complete your leave request at this time. Please try "
            "again later or contact HR support if the issue persists."
        )

    @pytest.mark.parametrize("real", [
        "This leave request has already been cancelled.",
        "You cannot cancel this leave because attendance has already been calculated.",
        "Monthly sick leave limit reached. Monthly limit: 2, already applied: 2, requested: 1.",
    ])
    def test_genuine_sentences_are_still_shown(self, real):
        """The guard must not swallow real explanations."""
        result = interpret_failure({"success": False, "message": real})
        assert result.display_message == real
        assert result.is_fallback is False

    def test_code_in_message_falls_through_to_a_usable_data_error(self):
        """A coded message falls through to a readable data.error before resorting to the fallback."""
        result = interpret_failure({
            "success": False,
            "message": "ERR_5521",
            "data": {"error": "This leave request has already been cancelled."},
        })
        assert result.display_message == "This leave request has already been cancelled."
        assert result.is_fallback is False
