"""
Tests for the Leave Eligibility feature (HEL-280):
  - services/hr_graph.py::evaluate_eligibility (pure rule evaluation)
  - services/hr_graph.py::_tenure_label
  - services/hr_graph.py::leave_eligibility_node (orchestration + SSE contract)
  - services/nlp_service.py::fast_classify eligibility routing
  - services/erp_client.py::ErpApiUnauthorized split

leave_eligibility_node is exercised directly with a fake StreamWriter and
mocked erp_client calls, matching the approach in test_leave_action.py, so
the conversation logic is pinned down without Redis, erp-api or an LLM.
"""

from datetime import date
import pytest
from unittest.mock import patch, AsyncMock

import services.hr_graph as hr_graph
from services.hr_graph import (
    evaluate_eligibility, _tenure_label, _probation_countdown_label, _parse_bool_ish, _parse_int_ish,
    _policy_details, _policy_summary_sentence, _parse_flexible_date, _format_date, _display_doj,
    _extract_claimed_doj, _doj_mismatch_note, _mentions_unconfigured_leave,
    _extract_unrecognised_leave_mention,
)
from services.erp_client import ErpApiTimeout, ErpApiUnavailable, ErpApiUnauthorized


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 done(self):
        events = self.of_type("done")
        return events[0] if events else None


# ── Fixtures ─────────────────────────────────────────────────────────────────

JOINING_TYPE = {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"}
CONFIRMATION_TYPE = {"name": "Earned Leave", "slug": "earned_leave", "benefit_start": "confirmation"}

CONFIRMED_EMPLOYEE = {
    "user_id": 3735, "name": "B Geo", "company_id": 26,
    "is_confirmed": True, "probation_end_date": "2025-06-14", "doj": "2025-06-14",
    "emp_no": "geo3",
}
PROBATION_EMPLOYEE = {
    "user_id": 9001, "name": "New Joiner", "company_id": 26,
    "is_confirmed": False, "probation_end_date": "2026-09-14", "doj": "2026-06-14",
}
UNKNOWN_EMPLOYEE = {**CONFIRMED_EMPLOYEE, "is_confirmed": None}

# Mirrors the live /ai/leave/balance payload: leave_quota lists six types,
# leave_settings.leave_type[] configures only four. comp_off and
# leave_without_pay therefore have no benefit_start and cannot be evaluated.
LEAVE_SETTINGS = {
    "leave_type": [
        {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"},
        {"name": "Sick Leave", "slug": "sick_leave", "benefit_start": "joining"},
        {"name": "Earned Leave", "slug": "earned_leave", "benefit_start": "confirmation"},
        {"name": "Short Leave", "slug": "short_leave", "benefit_start": "joining"},
    ]
}
LEAVE_QUOTA = {
    "casual_leave": {"total": 24, "remaining": "14"},
    "earned_leave": {"total": 6, "remaining": "0"},
    "comp_off": {"total": 0, "remaining": 0},
    "leave_without_pay": {"total": 0, "remaining": 0},
}


def _state(query: str) -> dict:
    return {
        "query": query, "bearer_token": "fake.jwt.token",
        "company_id": "3735", "conversation_id": "conv-1", "usage_events": [],
    }


def _erp(employee=CONFIRMED_EMPLOYEE, settings=LEAVE_SETTINGS, quota=LEAVE_QUOTA):
    """Patches both erp_client calls the node makes concurrently."""
    return patch.multiple(
        hr_graph.erp_client,
        get_leave_context=AsyncMock(return_value={
            "http_status": 200, "body": {"success": True, "data": employee}}),
        get_leave_balance=AsyncMock(return_value={
            "http_status": 200, "body": {"success": True, "data": {
                "leave_quota": quota, "leave_settings": settings}}}),
    )


async def _run(query, **kwargs):
    writer = FakeWriter()
    with _erp(**kwargs):
        await hr_graph.leave_eligibility_node(_state(query), writer)
    return writer


# ══ evaluate_eligibility — the truth table ═══════════════════════════════════

class TestEvaluateEligibility:
    def test_joining_is_always_eligible(self):
        """benefit_start 'joining' needs no employee data at all."""
        for employee in (CONFIRMED_EMPLOYEE, PROBATION_EMPLOYEE, UNKNOWN_EMPLOYEE, {}):
            result = evaluate_eligibility(JOINING_TYPE, employee)
            assert result["eligible"] is True
            assert result["reason_code"] == "AVAILABLE_FROM_JOINING"
            assert result["probation"] is False

    def test_confirmation_and_confirmed_is_eligible(self):
        result = evaluate_eligibility(CONFIRMATION_TYPE, CONFIRMED_EMPLOYEE)
        assert result["eligible"] is True
        assert result["reason_code"] == "CONFIRMED"
        # Bug found 2026-08-27: `probation` used to reflect the TYPE's
        # policy shape (benefit_start == "confirmation") regardless of
        # verdict, so an ELIGIBLE, already-confirmed employee still showed
        # "probation: true" — confusing on its own. It now reflects this
        # employee's CURRENT status: false whenever eligible is true, even
        # for a confirmation-gated type once probation is actually cleared.
        assert result["probation"] is False

    def test_confirmation_and_on_probation_is_not_eligible(self):
        result = evaluate_eligibility(CONFIRMATION_TYPE, PROBATION_EMPLOYEE)
        assert result["eligible"] is False
        assert result["reason_code"] == "REQUIRES_CONFIRMATION"
        # True here, and ONLY here — this is the one case where the
        # employee is actually, currently being denied for being on
        # probation.
        assert result["probation"] is True
        # AC 3: the response must name the rule that failed, with specifics.
        # Worded as "probation", not erp-api's internal "confirmation" —
        # probation is the word employees actually recognise.
        assert "probation" in result["reason"].lower()
        assert "confirmation" not in result["reason"].lower()
        assert "14 Sep 2026" in result["reason"]

    def test_probation_key_reflects_the_employees_current_status(self):
        """Same confirmation-gated type, two employees — 'probation' tracks
        the OUTCOME for this employee, never a fixed fact about the type."""
        confirmed_result = evaluate_eligibility(CONFIRMATION_TYPE, CONFIRMED_EMPLOYEE)
        probation_result = evaluate_eligibility(CONFIRMATION_TYPE, PROBATION_EMPLOYEE)
        assert confirmed_result["eligible"] is True
        assert confirmed_result["probation"] is False
        assert probation_result["eligible"] is False
        assert probation_result["probation"] is True

    def test_joining_type_never_reports_probation_regardless_of_employee(self):
        for employee in (CONFIRMED_EMPLOYEE, PROBATION_EMPLOYEE, UNKNOWN_EMPLOYEE, {}):
            result = evaluate_eligibility(JOINING_TYPE, employee)
            assert result["probation"] is False

    def test_probation_key_false_when_employee_data_is_unavailable(self):
        """eligible is None (undetermined) here — not confirmed to actually
        be on probation, so `probation` stays False rather than guessing."""
        result = evaluate_eligibility(CONFIRMATION_TYPE, UNKNOWN_EMPLOYEE)
        assert result["reason_code"] == "EMPLOYEE_DATA_UNAVAILABLE"
        assert result["probation"] is False

    def test_probation_key_false_for_an_unrecognised_rule(self):
        result = evaluate_eligibility(
            {"slug": "earned_leave", "name": "Earned Leave", "benefit_start": "bogus"},
            CONFIRMED_EMPLOYEE,
        )
        assert result["reason_code"] == "RULE_NOT_UNDERSTOOD"
        assert result["probation"] is False

    @pytest.mark.parametrize("falsy_is_confirmed", ["false", "0", "no", "", 0, False])
    def test_string_or_numeric_false_is_confirmed_still_denies(self, falsy_is_confirmed):
        """Bug found 2026-08-25 (this exact ticket): erp-api mixes real JSON
        booleans and string-encoded ones across leave_settings/context
        fields — a bare `if is_confirmed:` truthiness check would read the
        STRING "false" (a non-empty string) as truthy, silently flipping an
        employee still on probation to Eligible. Must use _parse_bool_ish,
        same as every other boolean-ish erp-api field this codebase reads."""
        employee = {**PROBATION_EMPLOYEE, "is_confirmed": falsy_is_confirmed}
        result = evaluate_eligibility(CONFIRMATION_TYPE, employee)
        assert result["eligible"] is False
        assert result["reason_code"] == "REQUIRES_CONFIRMATION"

    @pytest.mark.parametrize("truthy_is_confirmed", ["true", "1", "yes", 1, True])
    def test_string_or_numeric_true_is_confirmed_still_approves(self, truthy_is_confirmed):
        """Companion positive case — the same coercion must work both ways,
        not just default to denial for anything unexpected."""
        employee = {**CONFIRMED_EMPLOYEE, "is_confirmed": truthy_is_confirmed}
        result = evaluate_eligibility(CONFIRMATION_TYPE, employee)
        assert result["eligible"] is True
        assert result["reason_code"] == "CONFIRMED"

    @pytest.mark.parametrize("unparseable_is_confirmed", [None, "unknown", "maybe"])
    def test_unparseable_is_confirmed_still_fails_closed(self, unparseable_is_confirmed):
        """A genuinely missing/unrecognisable value must still be treated
        as 'we don't know', never coerced into a guessed True or False."""
        employee = {**CONFIRMED_EMPLOYEE, "is_confirmed": unparseable_is_confirmed}
        result = evaluate_eligibility(CONFIRMATION_TYPE, employee)
        assert result["eligible"] is None
        assert result["reason_code"] == "EMPLOYEE_DATA_UNAVAILABLE"

    def test_unknown_confirmation_status_fails_closed(self):
        """is_confirmed=None is 'we don't know', NOT 'no'. Must not deny."""
        result = evaluate_eligibility(CONFIRMATION_TYPE, UNKNOWN_EMPLOYEE)
        assert result["eligible"] is None
        assert result["reason_code"] == "EMPLOYEE_DATA_UNAVAILABLE"

    def test_missing_probation_end_date_still_answers(self):
        employee = {**PROBATION_EMPLOYEE, "probation_end_date": None}
        result = evaluate_eligibility(CONFIRMATION_TYPE, employee)
        assert result["eligible"] is False
        assert "still on probation" in result["reason"]

    @pytest.mark.parametrize("benefit_start", ["", None, "somethingelse", "JOINING_DATE"])
    def test_unrecognised_rule_fails_closed(self, benefit_start):
        """A rule we don't understand must never produce a verdict."""
        cfg = {**CONFIRMATION_TYPE, "benefit_start": benefit_start}
        result = evaluate_eligibility(cfg, CONFIRMED_EMPLOYEE)
        assert result["eligible"] is None
        assert result["reason_code"] == "RULE_NOT_UNDERSTOOD"

    @pytest.mark.parametrize("benefit_start", ["Confirmation", " CONFIRMATION ", "confirmation"])
    def test_benefit_start_casing_and_whitespace_tolerated(self, benefit_start):
        cfg = {**CONFIRMATION_TYPE, "benefit_start": benefit_start}
        assert evaluate_eligibility(cfg, PROBATION_EMPLOYEE)["eligible"] is False

    def test_falls_back_to_slug_when_name_missing(self):
        result = evaluate_eligibility(
            {"slug": "earned_leave", "benefit_start": "joining"}, CONFIRMED_EMPLOYEE)
        assert "Earned Leave" in result["reason"]


class TestProbationCountdown:
    """Live erp-api example, 2026-08-25: doj=2026-08-01, probation_end_date
    =2026-11-01, is_confirmed=false — the countdown label lets the reason
    text say how much longer, not just the bare end date."""

    @pytest.mark.parametrize("probation_end_date,today,expected", [
        ("2026-11-01", date(2026, 8, 25), "2 months remaining"),
        ("2026-09-14", date(2026, 8, 25), "20 days remaining"),
        ("2026-08-26", date(2026, 8, 25), "1 day remaining"),
        # Exact one-month-out still rounds to whole months, not days.
        ("2026-09-25", date(2026, 8, 25), "1 month remaining"),
        ("2027-08-25", date(2026, 8, 25), "12 months remaining"),
    ])
    def test_computes_countdown(self, probation_end_date, today, expected):
        assert _probation_countdown_label(probation_end_date, today) == expected

    @pytest.mark.parametrize("probation_end_date,today", [
        ("2026-08-25", date(2026, 8, 25)),  # ends today -> already at/past it
        ("2026-01-01", date(2026, 8, 25)),  # a data lag: is_confirmed hasn't caught up
    ])
    def test_already_past_end_date_does_not_claim_a_future_countdown(self, probation_end_date, today):
        assert _probation_countdown_label(probation_end_date, today) == "already past this date"

    @pytest.mark.parametrize("probation_end_date", [None, "", "not-a-date"])
    def test_bad_or_missing_end_date_returns_none(self, probation_end_date):
        assert _probation_countdown_label(probation_end_date, date(2026, 8, 25)) is None

    @pytest.mark.parametrize("probation_end_date", [
        "2026-11-01",              # plain ISO — control case
        "2026-11-01T00:00:00.000Z",  # ISO datetime with timezone
        "2026-11-01 00:00:00",     # ISO datetime with space
        "01-11-2026",              # DD-MM-YYYY
        "01/11/2026",              # DD/MM/YYYY
        "2026/11/01",              # YYYY/MM/DD with slashes
    ])
    def test_computes_countdown_for_non_iso_formats(self, probation_end_date):
        """Bug found 2026-08-25 ('Ineligible Due to Probation (With Future
        Date Guidance)'): erp-api's probation_end_date isn't guaranteed to
        be plain ISO, and the countdown was silently dropped (returning
        None) for any other shape, leaving the employee with a bare,
        unformatted date and no sense of when eligibility kicks in. All of
        these represent the same real-world date and must agree."""
        assert _probation_countdown_label(probation_end_date, date(2026, 8, 25)) == "2 months remaining"

    async def test_reason_text_includes_the_countdown_alongside_the_end_date(self):
        """Integration-level: evaluate_eligibility's own REQUIRES_CONFIRMATION
        reason carries both the formatted end date and the countdown,
        computed against the REAL today (so this can't hardcode an expected
        string — it derives the same label the code should produce)."""
        employee = {
            "is_confirmed": False, "probation_end_date": "2026-11-01", "doj": "2026-08-01",
        }
        cfg = {"slug": "casual_leave", "name": "Casual Leave", "benefit_start": "confirmation"}
        result = evaluate_eligibility(cfg, employee)
        expected_countdown = _probation_countdown_label("2026-11-01")
        assert result["reason"] == (
            f"Employees currently under probation cannot apply for Casual Leave. "
            f"Your probation ends on 01 Nov 2026 ({expected_countdown}), after which you will become eligible."
        )


class TestParseFlexibleDate:
    """_parse_flexible_date backs _format_date, _display_doj, _tenure_label
    and _probation_countdown_label alike — erp-api's date fields aren't
    guaranteed to be plain ISO (see _parse_bool_ish's own docstring for the
    same class of inconsistency on booleans)."""

    @pytest.mark.parametrize("value,expected", [
        ("2026-11-01", date(2026, 11, 1)),
        ("2026-11-01T00:00:00.000Z", date(2026, 11, 1)),
        ("2026-11-01 00:00:00", date(2026, 11, 1)),
        ("01-11-2026", date(2026, 11, 1)),   # DD-MM-YYYY, day-first
        ("01/11/2026", date(2026, 11, 1)),   # DD/MM/YYYY, day-first
        ("2026/11/01", date(2026, 11, 1)),   # YYYY/MM/DD with slashes
        ("1/11/2026", date(2026, 11, 1)),    # unpadded day
    ])
    def test_parses_known_shapes(self, value, expected):
        assert _parse_flexible_date(value) == expected

    @pytest.mark.parametrize("value", [None, "", "not-a-date", "13/40/2026"])
    def test_returns_none_for_unparseable_values(self, value):
        assert _parse_flexible_date(value) is None


class TestFormatDateAndDisplayDoj:
    """Bug found 2026-08-25 ('Ineligible Due to Probation (With Future Date
    Guidance)'): a non-ISO probation_end_date fell through to being shown
    raw and unformatted, with no countdown, instead of the polished
    '01 Nov 2026' the ISO case already got."""

    @pytest.mark.parametrize("value", ["2026-11-01", "01-11-2026", "01/11/2026", "2026/11/01"])
    def test_format_date_normalises_non_iso_shapes(self, value):
        assert _format_date(value) == "01 Nov 2026"

    def test_format_date_falls_back_to_raw_string_for_garbage(self):
        assert _format_date("not-a-date") == "not-a-date"

    @pytest.mark.parametrize("value", ["2026-11-01", "01-11-2026", "01/11/2026", "2026/11/01"])
    def test_display_doj_normalises_non_iso_shapes(self, value):
        assert _display_doj(value) == "1st November 2026"


class TestDojMismatchNote:
    """Bug found 2026-08-25: a chat query can embed a DOJ claim in prose
    ('am I eligible for casual leave (doj = 2025-06-14, today = 2026-08-25)')
    that the system never acted on — the real erp-api doj was always used
    correctly, but silently, with no acknowledgement that the query's own
    claim disagreed with it. The note makes that explicit without ever
    letting the claim actually change which doj is used for tenure/policy
    math — that still only ever comes from erp-api."""

    @pytest.mark.parametrize("query,expected", [
        ("doj = 2025-06-14", "2025-06-14"),
        ("doj: 2025-06-14", "2025-06-14"),
        ("my date of joining is 2025-06-14", "2025-06-14"),
        ("date of joining = 14-06-2025", "14-06-2025"),
        ("joining date 14/06/2025", "14/06/2025"),
        ("I joined on 2025-06-14", "2025-06-14"),
        ("am I eligible for casual leave (doj = 2025-06-14, today = 2026-08-25)", "2025-06-14"),
    ])
    def test_extracts_a_claimed_doj_from_prose(self, query, expected):
        assert _extract_claimed_doj(query) == expected

    @pytest.mark.parametrize("query", [
        "am I eligible for casual leave",
        "what is the date of joining policy",
        "when do I become eligible",
    ])
    def test_no_claim_found_in_ordinary_queries(self, query):
        assert _extract_claimed_doj(query) is None

    def test_mismatched_claim_produces_a_note_naming_both_dates(self):
        note = _doj_mismatch_note(
            "am I eligible for casual leave (doj = 2025-06-14, today = 2026-08-25)",
            "2026-08-01",
        )
        assert note is not None
        assert "14 Jun 2025" in note
        assert "01 Aug 2026" in note

    def test_matching_claim_produces_no_note(self):
        """Same date, just a different shape (dash vs ISO) — not a real
        mismatch, so no note should clutter the reply."""
        assert _doj_mismatch_note("doj = 01-08-2026", "2026-08-01") is None

    def test_no_claim_at_all_produces_no_note(self):
        assert _doj_mismatch_note("am I eligible for casual leave", "2026-08-01") is None

    def test_unparseable_claim_produces_no_note(self):
        assert _doj_mismatch_note("my date of joining is nonsense", "2026-08-01") is None

    async def test_node_prepends_the_note_to_the_answer(self):
        """Integration-level: the note reaches the actual chat answer, and
        the eligibility verdict underneath still uses the REAL doj (from
        CONFIRMED_EMPLOYEE's fixture, 2025-06-14), never the claimed one."""
        writer = await _run(
            "am I eligible for casual leave (doj = 2020-01-01, today = 2026-08-25)")
        answer = writer.done()["data"]["answer"]
        assert answer.startswith("The date of joining you mentioned (01 Jan 2020) doesn't match "
                                  "our records")
        assert "your recorded date of joining is 14 Jun 2025" in answer
        assert "Eligible" in answer
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert card["employee"]["doj"] == "14th June 2025"

    async def test_node_answer_unaffected_when_claim_matches_real_doj(self):
        """CONFIRMED_EMPLOYEE's fixture doj is 2025-06-14 — a claim of the
        same date, just reshaped, must not trigger a spurious note."""
        writer = await _run("am I eligible for casual leave (doj = 14-06-2025)")
        answer = writer.done()["data"]["answer"]
        assert "doesn't match our records" not in answer


class TestTenureLabel:
    @pytest.mark.parametrize("doj,today,expected", [
        ("2025-06-14", date(2026, 8, 18), "1 year 2 months"),
        ("2026-06-14", date(2026, 8, 18), "2 months"),
        # Exact-year anniversary drops the redundant "0 months".
        ("2024-08-18", date(2026, 8, 18), "2 years"),
        ("2025-08-18", date(2026, 8, 18), "1 year"),
        ("2026-08-01", date(2026, 8, 18), "0 months"),
        # Singular month is not "1 months".
        ("2025-07-18", date(2026, 8, 18), "1 year 1 month"),
    ])
    def test_computes_tenure(self, doj, today, expected):
        assert _tenure_label(doj, today) == expected

    @pytest.mark.parametrize("doj", [None, "", "not-a-date", "2027-01-01"])
    def test_bad_or_future_doj_returns_none(self, doj):
        assert _tenure_label(doj, date(2026, 8, 18)) is None


# ══ leave_eligibility_node — orchestration ═══════════════════════════════════

class TestEligibleResponses:
    async def test_joining_type_returns_eligible_card(self):
        """AC 1: verdict is delivered in chat via the card event."""
        writer = await _run("am I eligible for casual leave?")

        assert writer.of_type("checking_eligibility"), "progress event must be emitted"
        cards = writer.of_type("leave_eligibility")
        assert len(cards) == 1

        results = cards[0]["data"]["results"]
        assert len(results) == 1
        assert results[0]["eligible"] is True
        assert results[0]["leave_type"]["slug"] == "casual_leave"
        assert writer.done()["intent"] == "leave_eligibility"

    async def test_policy_summary_names_the_leave_type_instead_of_generic_days(self):
        """'You're entitled to 12 Sick Leaves a year; up to 2 Sick Leaves a
        month; and a maximum of 1 Sick Leave per application' — the actual
        leave type name in each figure (singular when the count is 1),
        never the generic 'days'/'applications' wording."""
        settings = {"leave_type": [
            {"name": "Sick Leave", "slug": "sick_leave", "benefit_start": "joining",
             "quota": 12, "max_apply_in_month": 2, "oneTypeMax": "1"},
        ]}
        writer = await _run("am I eligible for sick leave?", settings=settings)
        answer = writer.done()["data"]["answer"]
        assert "12 Sick Leaves a year" in answer
        assert "2 Sick Leaves a month" in answer
        assert "a maximum of 1 Sick Leave per application" in answer  # singular, not "1 Sick Leaves"
        assert "days a year" not in answer
        assert "applications a month" not in answer

    async def test_confirmed_employee_eligible_for_earned_leave(self):
        writer = await _run("am I eligible for earned leave?")
        result = writer.of_type("leave_eligibility")[0]["data"]["results"][0]
        assert result["eligible"] is True
        assert result["reason_code"] == "CONFIRMED"
        # reason_code keeps erp-api's vocabulary (stable frontend contract);
        # the prose the employee reads must not.
        assert "confirmation" not in result["reason"].lower()
        assert "probation" in result["reason"].lower()

    async def test_no_user_facing_text_says_confirmation(self):
        """erp-api's rule is named 'confirmation', but employees know it as
        their probation period. Guards every branch of the wording."""
        for employee in (CONFIRMED_EMPLOYEE, PROBATION_EMPLOYEE, UNKNOWN_EMPLOYEE):
            writer = await _run("am I eligible for earned leave?", employee=employee)
            answer = writer.done()["data"]["answer"]
            assert "confirmation" not in answer.lower(), f"leaked in: {answer}"

    async def test_employee_on_probation_not_eligible_with_reason(self):
        """AC 3: 'not eligible' must state the rule that failed."""
        writer = await _run("am I eligible for earned leave?", employee=PROBATION_EMPLOYEE)
        result = writer.of_type("leave_eligibility")[0]["data"]["results"][0]
        assert result["eligible"] is False
        assert result["reason_code"] == "REQUIRES_CONFIRMATION"
        assert "14 Sep 2026" in writer.done()["data"]["answer"]

    async def test_card_carries_employee_context(self):
        writer = await _run("am I eligible for casual leave?")
        employee = writer.of_type("leave_eligibility")[0]["data"]["employee"]
        assert employee["name"] == "B Geo"
        # "14th June 2025", not the raw ISO value — tenure_label below still
        # computes correctly since it reads erp-api's raw doj separately.
        assert employee["doj"] == "14th June 2025"
        assert employee["tenure_label"]  # computed locally from raw doj
        # Live-confirmed 2026-08-21: /ai/leave/context now returns emp_no,
        # the real human-readable employee code.
        assert employee["emp_code"] == "geo3"

    @pytest.mark.parametrize("query,slug,code", [
        ("am I eligible for casual leave?", "casual_leave", "CL"),
        ("am I eligible for sick leave?", "sick_leave", "SL"),
        ("am I eligible for earned leave?", "earned_leave", "EL"),
        ("am I eligible for short leave?", "short_leave", "SHL"),
    ])
    async def test_leave_type_carries_its_short_code(self, query, slug, code):
        """Same _LEAVE_TYPE_CODES table cancel-leave/leave-status cards
        already use — one shared source of truth rather than a second,
        independently-drifting copy."""
        writer = await _run(query)
        result = writer.of_type("leave_eligibility")[0]["data"]["results"][0]
        assert result["leave_type"]["slug"] == slug
        assert result["leave_type"]["leave_code"] == code

    async def test_multiple_leave_types_all_evaluated(self):
        writer = await _run("am I eligible for casual and sick leave?")
        results = writer.of_type("leave_eligibility")[0]["data"]["results"]
        assert {r["leave_type"]["slug"] for r in results} == {"casual_leave", "sick_leave"}
        assert all(r["eligible"] is True for r in results)

    async def test_probation_key_reaches_the_card_per_type(self):
        """The SSE card's per-result 'probation' flag reflects THIS
        employee's current status — false for a joining-based type
        (never probation-gated) AND for a confirmation-gated type this
        already-confirmed employee has cleared; true only when the
        confirmation-gated type is what's actually denying them."""
        confirmed_results = (
            await _run("am I eligible for casual and earned leave?")
        ).of_type("leave_eligibility")[0]["data"]["results"]
        by_slug = {r["leave_type"]["slug"]: r for r in confirmed_results}
        assert by_slug["casual_leave"]["eligible"] is True
        assert by_slug["casual_leave"]["probation"] is False
        assert by_slug["earned_leave"]["eligible"] is True
        assert by_slug["earned_leave"]["probation"] is False

        probation_results = (
            await _run("am I eligible for casual and earned leave?", employee=PROBATION_EMPLOYEE)
        ).of_type("leave_eligibility")[0]["data"]["results"]
        by_slug = {r["leave_type"]["slug"]: r for r in probation_results}
        assert by_slug["casual_leave"]["eligible"] is True
        assert by_slug["casual_leave"]["probation"] is False
        assert by_slug["earned_leave"]["eligible"] is False
        assert by_slug["earned_leave"]["probation"] is True

    async def test_eligible_verdict_leads_with_the_word_eligible(self):
        """HA-160 Scenario A/D: the answer opens with a plain 'Eligible —'
        verdict word ahead of the reason sentence."""
        writer = await _run("am I eligible for casual leave?")
        answer = writer.done()["data"]["answer"]
        assert answer.startswith("Eligible — ")

    @pytest.mark.parametrize("query", [
        "am I eligible for casual leave",
        "Am I eligible for Casual Leave?",
        "can I take casual leave",
        "is casual leave eligible for me",
        "casual leave eligibility",
        "do I qualify for casual leave",
    ])
    async def test_single_type_query_never_mentions_unrelated_unconfigured_types(self, query):
        """Bug reported three times, 2026-08-25 (never reproduced on this
        branch): a query naming only Casual Leave must answer ONLY Casual
        Leave — no unsolicited mention of Comp Off, Leave Without Pay,
        Maternity Leave, or any other type never named in the query. Both
        no_rule/not_in_policy label lists are always built from `requested`/
        `unresolved`, which only ever contain slugs the query text itself
        matched — this test locks that guarantee down explicitly rather
        than leaving it to be inferred from the absence of a failure card."""
        writer = await _run(query, quota={
            **LEAVE_QUOTA, "comp_off": {"total": 0, "remaining": 0},
            "leave_without_pay": {"total": 0, "remaining": 0},
        })
        answer = writer.done()["data"]["answer"]
        for unrelated in ("Comp Off", "comp off", "Maternity", "Leave Without Pay", "Sick Leave",
                          "Earned Leave", "Short Leave"):
            assert unrelated not in answer, f"unrelated mention of {unrelated!r} in: {answer!r}"
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave"}
        assert "not_in_policy" not in card
        assert "no_eligibility_rule" not in card

    async def test_not_eligible_verdict_leads_with_not_eligible(self):
        """HA-160 Scenario C: same idea, for a denial."""
        writer = await _run("am I eligible for earned leave?", employee=PROBATION_EMPLOYEE)
        answer = writer.done()["data"]["answer"]
        assert answer.startswith("Not Eligible — ")

    async def test_eligible_verdict_carries_the_balance_disclaimer(self):
        """HA-160 Scenario D: an eligible verdict never implies anything
        about remaining balance — said explicitly, not just true in code."""
        writer = await _run("am I eligible for casual leave?")
        answer = writer.done()["data"]["answer"]
        assert "does not reflect your available leave balance" in answer

    async def test_not_eligible_verdict_has_no_balance_disclaimer(self):
        """The disclaimer is about not over-reading an ELIGIBLE verdict as a
        balance statement — a denial doesn't need it."""
        writer = await _run("am I eligible for earned leave?", employee=PROBATION_EMPLOYEE)
        answer = writer.done()["data"]["answer"]
        assert "does not reflect your available leave balance" not in answer

    async def test_mixed_configured_and_quota_only_type_answers_both_halves(self):
        """A compound query can name one configured type alongside a
        quota-only one ('casual and comp off leave?'). The configured half
        must still get a verdict, and the other half must be acknowledged —
        as 'not supported in this portal', same as a genuinely unconfigured
        type (product direction, 2026-08-25: comp_off/leave_without_pay are
        pinned to the unsupported bucket for eligibility purposes even
        though erp-api does track a balance for them) — never silently
        dropped. Consolidated response format (2026-08-27): one title
        combining both applicable sections, one short answer."""
        writer = await _run("am I eligible for casual and comp off leave?")
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave"}
        assert card["not_in_policy"] == ["Comp Off"]
        assert "no_eligibility_rule" not in card

        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave and for Comp Off our access check failed as "
            "our Helix HR currently supports only these 4 leave types. Please contact your "
            "HR for assistance."
        )
        answer = done["answer"]
        assert "Casual Leave" in answer
        assert "'Comp Off' is not supported in this portal" in answer

    async def test_mixed_configured_and_unconfigured_named_type(self):
        """Same gap, but for a leave type named in prose rather than by its
        configured slug word ('casual and maternity leave?')."""
        writer = await _run("am I eligible for casual and maternity leave?")
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave"}
        assert card["not_in_policy"] == ["Maternity Leave"]

        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave and for Maternity Leave our access check "
            "failed as our Helix HR currently supports only these 4 leave types. Please "
            "contact your HR for assistance."
        )
        answer = done["answer"]
        assert "Maternity Leave" in answer
        assert "is not supported in this portal" in answer

    async def test_three_way_mix_combines_both_unsupported_types_in_one_message(self):
        """A single query can combine a real verdict (casual) with two
        unsupported types at once — a quota-only real type (comp off) and a
        genuinely unknown one (maternity). Both now share the same
        'Unsupported leave type' bucket and are named together in one
        sentence, not given two different wordings."""
        writer = await _run("am I eligible for casual and comp off and maternity leave?")
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave"}
        assert card["not_in_policy"] == ["Comp Off", "Maternity Leave"]
        assert "no_eligibility_rule" not in card

        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave and for Comp Off, and Maternity Leave our "
            "access check failed as our Helix HR currently supports only these 4 leave "
            "types. Please contact your HR for assistance."
        )
        answer = done["answer"]
        assert "You're eligible for these leaves: Casual Leave (CL)." in answer
        assert "'Comp Off', 'Maternity Leave' are not supported in this portal" in answer

    async def test_mixed_eligible_and_ineligible_named_types_both_explained(self):
        """Bug found 2026-08-25: naming 2+ real, configured types together
        while one is probation-blocked ('casual and earned leave?') used to
        collapse the denial to a bare 'Earned Leave: not eligible.' — the
        reason and the probation end date/countdown only ever reached the
        SSE card, never the chat answer itself. Each named type must be
        independently and fully explained in the reply, not just the card."""
        writer = await _run("am I eligible for casual and earned leave?", employee=PROBATION_EMPLOYEE)
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave", "earned_leave"}

        done = writer.done()["data"]
        assert done["title"] == "You're eligible for Casual Leave but not eligible for Earned Leave"
        answer = done["answer"]
        assert "You're eligible for these leaves: Casual Leave (CL)." in answer
        assert "You're not eligible for these leaves: Earned Leave (EL) —" in answer
        assert "Employees currently under probation cannot apply for Earned Leave" in answer
        expected_countdown = _probation_countdown_label(PROBATION_EMPLOYEE["probation_end_date"])
        assert f"({expected_countdown})" in answer
        assert "after which you will become eligible" in answer

    async def test_three_way_mix_with_a_real_denial_explains_every_category(self):
        """The ticket's exact repro: Casual (eligible), Earned (ineligible —
        on probation), Maternity (unsupported) asked together. All three
        must be independently, clearly explained — none silently dropped
        or reduced to a bare verdict word. Now grouped into three sections
        under one combined title (product direction, 2026-08-27)."""
        writer = await _run(
            "am I eligible for casual, earned, and maternity leave?", employee=PROBATION_EMPLOYEE)
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave", "earned_leave"}
        assert card["not_in_policy"] == ["Maternity Leave"]

        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave but not eligible for Earned Leave and for "
            "Maternity Leave our access check failed as our Helix HR currently supports "
            "only these 4 leave types. Please contact your HR for assistance."
        )
        answer = done["answer"]
        assert "You're eligible for these leaves: Casual Leave (CL)." in answer
        assert "You're not eligible for these leaves: Earned Leave (EL) —" in answer
        assert "Employees currently under probation cannot apply for Earned Leave" in answer
        assert "after which you will become eligible" in answer
        assert "'Maternity Leave' is not supported in this portal" in answer


class TestBalanceIsNeverConsidered:
    async def test_zero_balance_is_still_policy_eligible(self):
        """AC 5: policy eligibility and available balance are independent.
        earned_leave has remaining '0' in the fixture — the verdict must
        still be eligible for a confirmed employee."""
        writer = await _run("am I eligible for earned leave?")
        result = writer.of_type("leave_eligibility")[0]["data"]["results"][0]
        assert result["eligible"] is True

    async def test_verdict_unchanged_when_quota_absent_entirely(self):
        """The node must not read leave_quota at all — removing it changes
        nothing. This is AC 5 enforced structurally, not by convention."""
        writer = await _run("am I eligible for earned leave?", quota={})
        result = writer.of_type("leave_eligibility")[0]["data"]["results"][0]
        assert result["eligible"] is True
        assert "results" in writer.of_type("leave_eligibility")[0]["data"]


class TestUnknownAndAmbiguous:
    async def test_unconfigured_leave_type_names_it_and_lists_alternatives(self):
        """AC 7 (reworded): maternity leave isn't configured for this company.
        The employee didn't mistype anything, so the answer must state that
        plainly and NOT ask them to 'verify the leave type'."""
        writer = await _run("am I eligible for maternity leave?")
        assert not writer.of_type("leave_eligibility"), "no card for an unknown type"

        answer = writer.done()["data"]["answer"]
        assert "'Maternity Leave' is not supported in this portal" in answer
        assert "verify" not in answer.lower(), "must not imply the user mistyped"
        # Lists what they can actually ask about instead of a dead end.
        for name in ("Casual Leave", "Sick Leave", "Earned Leave", "Short Leave"):
            assert name in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"

    async def test_typo_in_an_unconfigured_leave_type_is_still_recognised(self):
        """Live bug repro: 'show my meternity leave eligibity' — the typo'd
        'meternity' didn't exact-match the unconfigured-word list, so this
        fell through to the ambiguous 'please specify a leave type'
        clarification even though a type was clearly named. Must still land
        on the correct not-in-policy answer, not the generic one."""
        writer = await _run("show my meternity leave eligibity")
        answer = writer.done()["data"]["answer"]
        assert "'Maternity Leave' is not supported in this portal" in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"

    async def test_heavier_typo_still_matches_at_the_075_cutoff(self):
        """'metrenity' (transposition + substitution, ratio 0.778 against
        'maternity') sits below the original 0.8 cutoff but above the
        current 0.75 one — confirms the lower cutoff actually buys more
        typo coverage, not just a cosmetic threshold change."""
        writer = await _run("do I get metrenity leave")
        answer = writer.done()["data"]["answer"]
        assert "'Maternity Leave' is not supported in this portal" in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"

    async def test_075_cutoff_does_not_misread_real_words_as_a_maternity_typo(self):
        """The lowered fuzzy cutoff must not start false-matching genuine
        English words that merely sound similar to "maternity" as if they
        were a TYPO of it — "material" must never resolve via the typo
        path. It's still correctly flagged as its own unsupported type
        (below), just via the generic '<word> leave' fallback, not by
        being misread as a garbled "maternity"."""
        assert _mentions_unconfigured_leave("do I get material leave") is None

    async def test_unrelated_sentence_with_no_leave_word_stays_ambiguous(self):
        """"my maternal instincts" contains no "leave" at all — nothing for
        either matcher to latch onto, so it's still a genuinely ambiguous,
        no-type-named query."""
        writer = await _run("my maternal instincts")
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_SPECIFIED"

    @pytest.mark.parametrize("query,label", [
        ("am I eligible for medical leave?", "Medical Leave"),
        ("am I eligible for religious leave?", "Religious Leave"),
        ("am I eligible for xyz leave?", "Xyz Leave"),
        ("do I get material leave", "Material Leave"),
    ])
    async def test_any_unrecognised_leave_type_name_reports_unsupported(self, query, label):
        """Bug found 2026-08-25: only the fixed _UNCONFIGURED_LEAVE_WORDS
        vocabulary (maternity, paternity, sabbatical, ...) got the
        'Unsupported leave type' message — anything else naming a real
        '<word> leave' phrase outside that closed list (medical, religious,
        or literally anything) fell through to the ambiguous 'please
        specify' clarification instead, as if no type had been named at
        all. Must work for ANY such name, not just the fixed nine."""
        writer = await _run(query)
        answer = writer.done()["data"]["answer"]
        assert "Helix AI currently supports" in answer
        assert f"'{label}' is not supported in this portal" in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"

    async def test_generic_fallback_never_overrides_a_real_configured_verdict(self):
        """A standalone real-type query must never be swept up by the more
        permissive generic fallback — 'casual' is excluded explicitly."""
        writer = await _run("am I eligible for casual leave")
        answer = writer.done()["data"]["answer"]
        assert "is not supported in this portal" not in answer
        assert answer.startswith("Eligible — ")

    async def test_generic_fallback_does_not_swallow_general_eligibility_questions(self):
        """'what kind of leaves am I eligible for' must still answer every
        configured type directly — the single preceding word before
        'leaves' here is 'of', a stopword, not a candidate type name."""
        writer = await _run("what kind of leaves am i eligible for")
        answer = writer.done()["data"]["answer"]
        assert "is not supported in this portal" not in answer
        assert answer.startswith("You're eligible for these leaves: Casual Leave (CL), Sick Leave (SL), "
                                  "Earned Leave (EL), Short Leave (SHL).")

    @pytest.mark.parametrize("query", [
        "check leave eligibility",
        "show leave eligibility",
        "check my leave eligibility",
        "show my leave eligibility",
        "leave eligibility",
        "can I take leave?",
        "do I get leave?",
        "may I avail leave?",
        "I want leave",
        "verify leave eligibility",
        "confirm leave eligibility",
        "view leave eligibility",
        "give me leave eligibility",
        "ask about leave eligibility",
        "raise leave",
        "book leave",
        "apply leave",
        "request leave",
        "submit leave",
    ])
    async def test_generic_fallback_ignores_verbs_pronouns_and_prepositions_before_leave(self, query):
        """Bug found 2026-08-26: 'check leave eligibility' failed while
        'check MY leave eligibility' worked — the generic '<word> leave'
        fallback (built for 'medical leave'/'religious leave') read
        "check"/"show" as if they were unrecognised TYPE names whenever no
        possessive separated them from "leave". Broader sweep found the
        same failure for "take"/"get"/"avail"/"want"/"verify"/"confirm"/
        "view"/"me"/"about"/"raise"/"book"/"apply"/"request"/"submit" — a
        single word immediately before "leave" is far more often a verb,
        pronoun, or preposition than an actual type name. None of these
        must ever be misread as an unsupported type; every one of these
        queries names no specific type at all, so they must land on the
        ordinary 'which type would you like to check' response, identical
        to the already-working 'check my leave eligibility'."""
        writer = await _run(query)
        answer = writer.done()["data"]["answer"]
        assert "is not supported in this portal" not in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_SPECIFIED"

    async def test_mixed_configured_and_generic_unrecognised_type(self):
        """A compound query naming one real type alongside a brand-new,
        never-before-seen name ('casual and medical leave?') must still
        answer the real half AND flag the unrecognised half — same
        acknowledgement compound queries already get for the fixed
        vocabulary (maternity, ...) and quota-only types (comp off)."""
        writer = await _run("am I eligible for casual and medical leave?")
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"casual_leave"}
        assert card["not_in_policy"] == ["Medical Leave"]

        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave and for Medical Leave our access check "
            "failed as our Helix HR currently supports only these 4 leave types. Please "
            "contact your HR for assistance."
        )
        answer = done["answer"]
        assert "You're eligible for these leaves: Casual Leave (CL)." in answer
        assert "'Medical Leave' is not supported in this portal" in answer

    async def test_genuinely_ambiguous_query_is_not_swept_up_by_the_typo_matcher(self):
        """The fuzzy fallback must not turn every unrecognised word into a
        false 'not in policy' guess — a query naming no leave type at all
        still asks for clarification."""
        writer = await _run("check eligibility")
        answer = writer.done()["data"]["answer"]
        assert "leave eligibility you'd like to check" in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_SPECIFIED"

    @pytest.mark.parametrize("query,label", [
        ("am I eligible for comp off?", "Comp Off"),
        ("am I eligible for leave without pay?", "Leave Without Pay"),
    ])
    async def test_quota_only_types_report_unsupported(self, query, label):
        """comp_off / leave_without_pay appear in leave_quota but have no
        entry in leave_settings.leave_type[], so no rule exists to apply.
        Product direction, 2026-08-25: these get the same 'Unsupported
        leave type' wording as a genuinely unconfigured type (Maternity,
        Sabbatical, ...), dynamically naming the company's real supported
        types, rather than the old distinct 'no eligibility rule
        configured' message."""
        writer = await _run(query)
        assert not writer.of_type("leave_eligibility")
        answer = writer.done()["data"]["answer"]
        assert "Helix AI currently supports" in answer
        assert f"'{label}' is not supported in this portal" in answer
        assert "Please contact HR for assistance." in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"

    async def test_ambiguous_query_asks_for_clarification(self):
        """AC 7: don't assume a leave type that was never named."""
        writer = await _run("am I eligible for some time off?")
        assert not writer.of_type("leave_eligibility")
        answer = writer.done()["data"]["answer"]
        assert "leave eligibility you'd like to check" in answer
        # Even the clarification names the real options rather than guessing.
        assert "Casual Leave" in answer
        assert writer.done()["data"]["reason_code"] == "LEAVE_TYPE_NOT_SPECIFIED"

    @pytest.mark.parametrize("query", [
        "what kind of leaves am i eligible for",
        "which leave types am I eligible for?",
        "what am I eligible for",
    ])
    async def test_general_eligibility_question_gives_consolidated_summary(self, query):
        """Unlike a genuinely ambiguous 'some time off' (no type at all,
        nothing to answer), 'what kind of leaves am I eligible for' is a
        real, answerable question about every configured type — must not
        be swept into the 'please specify' clarification. Consolidated
        response format (2026-08-27): one title, one short answer naming
        each type with its code."""
        writer = await _run(query)
        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave, Sick Leave, Earned Leave, and Short Leave"
        )
        assert done["answer"] == (
            "You're eligible for these leaves: Casual Leave (CL), Sick Leave (SL), "
            "Earned Leave (EL), Short Leave (SHL). (Note: this confirms policy eligibility "
            "based on your role and tenure — it does not reflect your available leave balance.)"
        )
        results = writer.of_type("leave_eligibility")[0]["data"]["results"]
        assert {r["leave_type"]["slug"] for r in results} == {
            "casual_leave", "sick_leave", "earned_leave", "short_leave"}

    async def test_general_eligibility_question_explains_ineligible_types_too(self):
        writer = await _run("what kind of leaves am i eligible for", employee=PROBATION_EMPLOYEE)
        done = writer.done()["data"]
        assert done["title"] == (
            "You're eligible for Casual Leave, Sick Leave, and Short Leave but not "
            "eligible for Earned Leave"
        )
        answer = done["answer"]
        assert "You're eligible for these leaves: Casual Leave (CL), Sick Leave (SL), Short Leave (SHL)." in answer
        assert "You're not eligible for these leaves: Earned Leave (EL) —" in answer
        assert "probation" in answer.lower()

    async def test_explicit_all_types_request_gets_the_same_consolidated_summary(self):
        """'show me all leave types eligibility' used to get a full
        per-type breakdown (name, code, verdict, and entitlement facts) —
        product direction, 2026-08-27: every multi-type query now gets the
        same short, consolidated, titled response regardless of exact
        phrasing, so this no longer differs from an ordinary 2-3 type
        query or a general 'what am I eligible for?'."""
        settings = {"leave_type": [
            {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining", "quota": 24},
            {"name": "Sick Leave", "slug": "sick_leave", "benefit_start": "joining", "quota": 12},
        ]}
        writer = await _run("show me all leave types eligibility", settings=settings)
        done = writer.done()["data"]
        assert done["title"] == "You're eligible for Casual Leave, and Sick Leave"
        assert done["answer"] == (
            "You're eligible for these leaves: Casual Leave (CL), Sick Leave (SL). "
            "(Note: this confirms policy eligibility based on your role and tenure "
            "— it does not reflect your available leave balance.)"
        )

    async def test_named_type_takes_priority_over_all_types_phrasing(self):
        """A query naming a real type must never be swept into all-types
        mode just because it also loosely matches 'eligib' + other words —
        the specific ask always wins."""
        writer = await _run("what is my casual leave eligibility")
        results = writer.of_type("leave_eligibility")[0]["data"]["results"]
        assert len(results) == 1
        assert results[0]["leave_type"]["slug"] == "casual_leave"

    async def test_undetermined_verdict_emits_no_card(self):
        """AC 6: 'unable to determine' must never render as a verdict."""
        writer = await _run("am I eligible for earned leave?", employee=UNKNOWN_EMPLOYEE)
        assert not writer.of_type("leave_eligibility")
        assert "I couldn't check your eligibility" in writer.done()["data"]["answer"]

    async def test_missing_leave_settings_fails_closed(self):
        """Absent policy configuration yields an explicit 'cannot determine' rather than a guessed verdict."""
        writer = await _run("am I eligible for casual leave?", settings={})
        assert not writer.of_type("leave_eligibility")
        assert "I couldn't check your eligibility" in writer.done()["data"]["answer"]


class TestTitleField:
    """Product direction, 2026-08-27: every eligibility response — single
    or multi-type — carries a 'title' field naming which of the three
    outcome sections apply (eligible / not-eligible / access check
    failed), separate from the detailed 'answer' text, so the frontend can
    render a heading without parsing prose."""

    async def test_single_eligible_type_title(self):
        writer = await _run("am I eligible for casual leave?")
        assert writer.done()["data"]["title"] == "You're eligible for Casual Leave"

    async def test_single_ineligible_type_title(self):
        writer = await _run("am I eligible for earned leave?", employee=PROBATION_EMPLOYEE)
        assert writer.done()["data"]["title"] == "You're not eligible for Earned Leave"

    async def test_standalone_unsupported_type_title(self):
        writer = await _run("am I eligible for maternity leave?")
        assert writer.done()["data"]["title"] == "Access check failed for Maternity Leave"

    async def test_ambiguous_no_type_named_has_no_title(self):
        """Not one of the three verdict sections — a clarifying question,
        so no title is set."""
        writer = await _run("am I eligible for some time off?")
        assert writer.done()["data"].get("title") is None

    async def test_multi_type_all_eligible_title(self):
        writer = await _run("am I eligible for casual and sick leave?")
        assert writer.done()["data"]["title"] == "You're eligible for Casual Leave, and Sick Leave"

    async def test_multi_type_mixed_title_combines_sections(self):
        writer = await _run(
            "am I eligible for casual, earned, and maternity leave?", employee=PROBATION_EMPLOYEE)
        assert writer.done()["data"]["title"] == (
            "You're eligible for Casual Leave but not eligible for Earned Leave and for "
            "Maternity Leave our access check failed as our Helix HR currently supports "
            "only these 4 leave types. Please contact your HR for assistance."
        )


# ══ HA-160: leave types outside the fixed common-synonym list ═══════════════
# Live bug fixed 2026-08-25: leave-type-name recognition used to be a
# hardcoded 6-word dict (casual/sick/earned/short/comp off/leave without
# pay) plus a SEPARATE fixed "these words are never configured" list
# (maternity/paternity/sabbatical/...). A company that genuinely configures
# Paternity Leave could never have it recognised — the fixed "never
# configured" list always won, regardless of what erp-api's real
# leave_settings actually said. HA-160 Scenario A is exactly this case.
SETTINGS_WITH_PATERNITY = {"leave_type": [
    {"name": "Casual Leave", "slug": "casual_leave", "benefit_start": "joining"},
    {"name": "Paternity Leave", "slug": "paternity_leave", "benefit_start": "joining"},
]}


class TestEligibilityClarificationIsResumable:
    """QA: 'the same UI is not showing when the query is different'.

    Asking eligibility WITHOUT naming a type ("am I eligible for leave?")
    lists the configured types and asks which was meant. Before this, that
    question recorded nothing — the eligibility flow was the only multi-turn
    flow in the codebase with no state store — so the one-word reply arrived
    with zero context, fast_classify returned None for a bare type name, and
    the turn fell through to the generic LLM path. That answered in prose and
    emitted no leave_eligibility event, so the SAME question rendered a card
    when asked in one turn and plain text when asked in two.
    """

    async def test_ambiguous_question_records_that_a_type_is_awaited(self):
        import services.leave_eligibility_service as les
        captured = {}
        with patch.object(les.leave_eligibility_clarify_state, "set_state",
                          side_effect=lambda c, cv, s: captured.update(s) or True), \
             patch.object(les.leave_eligibility_clarify_state, "clear_state", return_value=True):
            writer = await _run("am I eligible for leave?")
        assert writer.done()["data"].get("reason_code") == "LEAVE_TYPE_NOT_SPECIFIED"
        slugs = {e["slug"] for e in captured.get("available", [])}
        assert {"casual_leave", "sick_leave", "earned_leave", "short_leave"} <= slugs

    async def test_a_named_type_records_no_pending_question(self):
        """The clarify state must only be set when a type genuinely wasn't
        named — a normal answered question leaves nothing pending."""
        import services.leave_eligibility_service as les
        with patch.object(les.leave_eligibility_clarify_state, "set_state") as set_state, \
             patch.object(les.leave_eligibility_clarify_state, "clear_state", return_value=True):
            await _run("am I eligible for sick leave?")
        set_state.assert_not_called()

    @pytest.mark.parametrize("reply,expected_name", [
        ("Shrt.", "Short Leave"),
        ("Shrt", "Short Leave"),
        ("short", "Short Leave"),
        ("Short Leave", "Short Leave"),
        ("sick", "Sick Leave"),
        ("casul", "Casual Leave"),
        ("erned", "Earned Leave"),
    ])
    async def test_bare_type_reply_routes_back_to_eligibility(self, reply, expected_name):
        """The reply must come back as leave_eligibility with the type folded
        into the query, so the SAME node runs and the SAME card is emitted."""
        import services.classify_node as cn
        available = [{"slug": t["slug"], "name": t["name"]} for t in LEAVE_SETTINGS["leave_type"]]
        state = {"query": reply, "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t"}
        with patch.object(cn.leave_eligibility_clarify_state, "get_state",
                          return_value={"available": available}), \
             patch.object(cn.leave_eligibility_clarify_state, "clear_state", return_value=True):
            result = await cn.classify_node(state, lambda e: None)
        assert result["intent"] == "leave_eligibility"
        assert expected_name.lower() in result["query"].lower()

    async def test_no_pending_question_means_no_hijack(self):
        """A bare 'short' with nothing pending must NOT be forced into the
        eligibility flow — the fast-path is gated on the state existing."""
        import services.classify_node as cn
        state = {"query": "short", "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t"}
        with patch.object(cn.leave_eligibility_clarify_state, "get_state", return_value=None), \
             patch.object(cn, "classify_intent_structured",
                          AsyncMock(return_value=("general_hr", None, False))):
            result = await cn.classify_node(state, lambda e: None)
        assert result["intent"] != "leave_eligibility"

    async def test_an_ambiguous_reply_naming_two_types_falls_through(self):
        """'casual or sick?' resolves to two types — the fast-path must not
        guess. State is left in place and normal classification continues."""
        import services.classify_node as cn
        available = [{"slug": t["slug"], "name": t["name"]} for t in LEAVE_SETTINGS["leave_type"]]
        state = {"query": "casual or sick", "context": [], "company_id": 1,
                 "conversation_id": "conv-1", "bearer_token": "t"}
        with patch.object(cn.leave_eligibility_clarify_state, "get_state",
                          return_value={"available": available}), \
             patch.object(cn.leave_eligibility_clarify_state, "clear_state") as clear, \
             patch.object(cn, "classify_intent_structured",
                          AsyncMock(return_value=("general_hr", None, False))):
            await cn.classify_node(state, lambda e: None)
        clear.assert_not_called()


class TestMisspelledConfiguredLeaveTypes:
    """QA: leave-type keyword/spelling variations produced inconsistent,
    unrelated answers.

    Root cause was an asymmetry, not a missing feature: typo tolerance
    already existed for types the company does NOT offer
    (_mentions_unconfigured_leave matches "meternity" -> maternity), while
    the company's own CONFIGURED types were matched by exact word only. So
    the leave types an employee can actually take were the ones spelling had
    to be perfect for, and "casul"/"sik"/"shrt" fell through to the generic
    "please specify a leave type" clarification.
    """

    @pytest.mark.parametrize("typed,expected_slug", [
        ("Shot", "short_leave"),
        ("Shortt", "short_leave"),
        ("shortt", "short_leave"),
        ("shrt", "short_leave"),
        ("shortl", "short_leave"),
        ("casul", "casual_leave"),
        ("causual", "casual_leave"),
        ("sik", "sick_leave"),
        ("sic", "sick_leave"),
        ("Earn", "earned_leave"),
        ("erned", "earned_leave"),
    ])
    async def test_misspelled_type_still_gets_a_real_verdict(self, typed, expected_slug):
        writer = await _run(f"Am I eligible for {typed} leave?")
        results = writer.of_type("leave_eligibility")[0]["data"]["results"]
        assert len(results) == 1
        assert results[0]["leave_type"]["slug"] == expected_slug

    @pytest.mark.parametrize("query", [
        # No type named at all — must stay the ambiguous-clarification path,
        # never have one fuzzy-guessed onto it.
        "Am I eligible for leave?",
        "check my eligibility",
        "what leave types am I eligible for",
        # Genuinely unconfigured types must keep reaching the not-in-policy
        # answer rather than being snapped to the nearest configured one.
        "am I eligible for maternity leave?",
        "am I eligible for bereavement leave",
        "am I eligible for study leave",
    ])
    async def test_typo_matching_does_not_invent_a_type(self, query):
        from services.leave_eligibility_service import _match_configured_leave_types
        configured = {t["slug"]: t for t in LEAVE_SETTINGS["leave_type"]}
        assert _match_configured_leave_types(query, configured) == []

    async def test_a_correctly_named_type_is_never_joined_by_a_fuzzy_second_one(self):
        """The fallback runs only when the exact pass found nothing, so a
        query that names one type correctly can't pick up a guessed extra."""
        from services.leave_eligibility_service import _match_configured_leave_types
        configured = {t["slug"]: t for t in LEAVE_SETTINGS["leave_type"]}
        assert _match_configured_leave_types(
            "am I eligible for casual leave?", configured) == ["casual_leave"]

    async def test_compound_correctly_spelled_query_still_returns_both(self):
        from services.leave_eligibility_service import _match_configured_leave_types
        configured = {t["slug"]: t for t in LEAVE_SETTINGS["leave_type"]}
        assert sorted(_match_configured_leave_types(
            "am I eligible for casual and sick leave?", configured)) == ["casual_leave", "sick_leave"]

    @pytest.mark.parametrize("abbrev", ["CL", "SL", "EL"])
    async def test_abbreviations_are_still_unmatched(self, abbrev):
        """Documents a KNOWN, deliberate gap rather than asserting desired
        behaviour: CL/SL/EL score 0.25-0.50 against their full names, far
        below any safe fuzzy cutoff, so they need an explicit code map
        (_LEAVE_TYPE_CODES already exists but is used only for rendering
        output). Update this test when that work is picked up."""
        from services.leave_eligibility_service import _match_configured_leave_types
        configured = {t["slug"]: t for t in LEAVE_SETTINGS["leave_type"]}
        assert _match_configured_leave_types(f"Am I eligible for {abbrev}?", configured) == []


class TestDynamicLeaveTypeRecognition:
    async def test_a_genuinely_configured_type_outside_the_fixed_list_gets_a_real_verdict(self):
        """HA-160 Scenario A: Paternity Leave, when the company's real
        erp-api data actually configures it, must get a real eligible
        verdict — not the old hardcoded 'not part of your company's leave
        policy' regardless of the data."""
        writer = await _run("Am I eligible for Paternity Leave?", settings=SETTINGS_WITH_PATERNITY)
        results = writer.of_type("leave_eligibility")[0]["data"]["results"]
        assert len(results) == 1
        assert results[0]["leave_type"]["slug"] == "paternity_leave"
        assert results[0]["eligible"] is True
        answer = writer.done()["data"]["answer"]
        assert answer.startswith("Eligible — ")
        # Regression guard: this word is ALSO in the fixed "commonly
        # unconfigured" list, which used to unconditionally flag it as not
        # in policy even after it already got a real verdict above —
        # producing a contradictory "eligible... I couldn't find..." reply.
        assert "couldn't find" not in answer.lower()

    async def test_same_word_still_reports_not_in_policy_when_genuinely_unconfigured(self):
        """Companion negative case — Paternity Leave is NOT configured here,
        so it must still correctly fall back to the not-in-policy answer,
        proving the dynamic match doesn't just always say yes."""
        writer = await _run("Am I eligible for Paternity Leave?", settings=LEAVE_SETTINGS)
        assert not writer.of_type("leave_eligibility")
        answer = writer.done()["data"]["answer"]
        assert "'Paternity Leave' is not supported in this portal" in answer

    async def test_mixed_query_with_a_dynamically_recognised_type_has_no_contradiction(self):
        """The exact regression scenario: a compound query naming both a
        genuinely-configured 'fixed-list' word (paternity) and a real
        unconfigured one (maternity) must answer paternity for real and
        flag maternity as not-in-policy — never both for the same word."""
        writer = await _run(
            "am I eligible for paternity and maternity leave?", settings=SETTINGS_WITH_PATERNITY,
        )
        card = writer.of_type("leave_eligibility")[0]["data"]
        assert {r["leave_type"]["slug"] for r in card["results"]} == {"paternity_leave"}
        assert card["not_in_policy"] == ["Maternity Leave"]
        answer = writer.done()["data"]["answer"]
        assert "You're eligible for these leaves: Paternity Leave." in answer
        assert "'Maternity Leave' is not supported in this portal" in answer


class TestTimeoutBudget:
    async def test_both_calls_request_the_3s_sla(self):
        """HEL-280's documented target is tighter than erp_client's shared
        client default (read=10.0) — this node must override it explicitly
        on both calls rather than silently inheriting the generic default."""
        captured = {}

        async def _context(*a, **kw):
            captured["context_timeout"] = kw.get("timeout_seconds")
            return {"http_status": 200, "body": {"success": True, "data": CONFIRMED_EMPLOYEE}}

        async def _balance(*a, **kw):
            captured["balance_timeout"] = kw.get("timeout_seconds")
            return {"http_status": 200, "body": {"success": True, "data": {
                "leave_quota": LEAVE_QUOTA, "leave_settings": LEAVE_SETTINGS}}}

        with patch.multiple(hr_graph.erp_client, get_leave_context=_context, get_leave_balance=_balance):
            await hr_graph.leave_eligibility_node(_state("am I eligible for casual leave?"), FakeWriter())

        assert captured["context_timeout"] == hr_graph._ELIGIBILITY_TIMEOUT_SECONDS == 3.0
        assert captured["balance_timeout"] == hr_graph._ELIGIBILITY_TIMEOUT_SECONDS == 3.0


class TestErpFailureHandling:
    async def test_expired_token_asks_user_to_log_in(self):
        """AC 4/AC 6: a rejected token is distinguishable from an outage."""
        writer = FakeWriter()
        with patch.object(hr_graph.erp_client, "get_leave_context",
                          AsyncMock(side_effect=ErpApiUnauthorized("401"))), \
             patch.object(hr_graph.erp_client, "get_leave_balance",
                          AsyncMock(return_value={"http_status": 200, "body": {}})):
            await hr_graph.leave_eligibility_node(_state("am I eligible for casual leave?"), writer)

        answer = writer.done()["data"]["answer"]
        assert "session has expired" in answer
        assert not writer.of_type("leave_eligibility")

    @pytest.mark.parametrize("exc", [ErpApiTimeout("slow"), ErpApiUnavailable("500")])
    async def test_erp_failure_returns_controlled_fallback(self, exc):
        """AC 6: no eligibility decision without validated backend data."""
        writer = FakeWriter()
        with patch.object(hr_graph.erp_client, "get_leave_context",
                          AsyncMock(side_effect=exc)), \
             patch.object(hr_graph.erp_client, "get_leave_balance",
                          AsyncMock(return_value={"http_status": 200, "body": {}})):
            await hr_graph.leave_eligibility_node(_state("am I eligible for casual leave?"), writer)

        answer = writer.done()["data"]["answer"]
        assert "reach the HR system" in answer
        assert not writer.of_type("leave_eligibility")


# ══ Intent classification ════════════════════════════════════════════════════

class TestEligibilityClassification:
    @pytest.mark.parametrize("query", [
        "am I eligible for casual leave",
        "am I eligible for maternity leave?",
        "do I qualify for earned leave",
        "am I entitled to sick leave",
        "is my leave eligibility ok for casual leave",
        "am I allowed sick leave",
        # Modal permission questions — asking whether they qualify, not
        # instructing us to book anything.
        "can I take casual leave",
        "can i take casual leave?",
        "could I take sick leave",
        "may I take earned leave",
        "am I able to take casual leave",
        "can I take a day off",
    ])
    def test_eligibility_questions_classify_correctly(self, query):
        from services.nlp_service import fast_classify
        intent, is_hr, confidence = fast_classify(query)
        assert intent == "leave_eligibility", f"{query!r} -> {intent}"
        assert is_hr is True

    @pytest.mark.parametrize("query,expected", [
        ("apply for casual leave tomorrow", "apply_leave"),
        ("book sick leave for monday", "apply_leave"),
        # Plain action phrasings stay with the apply flow — only the
        # modal "can/could/may I take" form is a qualification question.
        ("I want to take casual leave", "apply_leave"),
        ("take casual leave tomorrow", "apply_leave"),
        ("I need to take sick leave on monday", "apply_leave"),
        ("i want to take leave next week", "apply_leave"),
        # "apply" signals intent to submit even behind a modal.
        ("can I apply for casual leave", "apply_leave"),
        ("how many casual leaves do I have left", "leave_balance"),
        ("what is my leave balance", "leave_balance"),
        ("is my leave approved", "leave_status"),
        ("what is the maternity leave policy", "policy"),  # renamed from leave_policy (85ff98d)
    ])
    def test_neighbouring_intents_not_regressed(self, query, expected):
        """The eligibility patterns run before the apply/balance checks, so
        this guards against them swallowing traffic that isn't theirs."""
        from services.nlp_service import fast_classify
        intent, _, _ = fast_classify(query)
        assert intent == expected, f"{query!r} -> {intent}"

    def test_eligibility_is_a_valid_intent_label(self):
        """Guards the allow-list that validates LLM classifier output — an
        intent missing from it is silently discarded."""
        assert "leave_eligibility" in hr_graph._VALID_INTENT_LABELS

    def test_routes_to_its_own_node(self):
        assert hr_graph._route_after_classify(
            {"intent": "leave_eligibility", "is_hr": True}) == "leave_eligibility_node"

    def test_not_in_leave_action_intents(self):
        """Eligibility is read-only and must not reach leave_action_node,
        which owns the apply flow's slot state."""
        assert "leave_eligibility" not in hr_graph._LEAVE_ACTION_INTENTS


class TestCachingContract:
    def test_eligibility_is_never_served_from_cache(self):
        """Answers depend on confirmation status and live policy config,
        either of which can change inside the cache TTL."""
        import main
        assert "leave_eligibility" in main._STATEFUL_QUERY_INTENTS

    def test_sse_events_are_whitelisted(self):
        """Event types absent from main.py's whitelist are silently dropped
        and never reach the browser."""
        import inspect
        import main
        source = inspect.getsource(main.hr_assist_stream)
        # The whitelist lives in _ai_stream, not the route — check the module.
        source = inspect.getsource(main)
        assert '"leave_eligibility"' in source
        assert '"checking_eligibility"' in source


class TestFailureCardForUnconfiguredType:
    """HEL-283: an unconfigured leave type is the eligibility flow's one
    in-scope failure, and it now emits the shared failure card."""

    async def test_unconfigured_type_emits_a_policy_failure_card(self):
        """A leave type the company has not configured produces a policy failure card naming the available alternatives."""
        writer = await _run("am I eligible for maternity leave?")

        cards = writer.of_type("leave_failure")
        assert len(cards) == 1
        failure = cards[0]["data"]["failure"]
        assert failure["reason_code"] == ["LEAVE_TYPE_NOT_IN_POLICY"]
        assert failure["badge"] == ["policy_rule"]
        assert failure["action"] == "leave_eligibility"
        assert failure["title"] == "Eligibility Check Not Completed"
        assert failure["is_fallback"] is False
        assert "is not supported in this portal" in failure["display_message"][0]
        # AC6: alternatives are named INLINE in the "Unsupported leave type"
        # wording itself ("Helix AI currently supports ...") — next_action
        # is None here rather than repeating the same list a second time
        # (the separate pure no-rule/NO_ELIGIBILITY_RULE_CONFIGURED path,
        # which still uses next_action, isn't reachable by any currently
        # known erp-api quota key — comp_off/leave_without_pay, the only
        # documented quota-only types, are pinned to this unsupported
        # bucket instead — but stays in place for a future one).
        assert "Casual Leave" in failure["display_message"][0]
        assert failure["next_action"] is None

    async def test_done_event_carries_the_card_too(self):
        """The done event repeats the card while preserving the pre-existing eligibility fields."""
        writer = await _run("am I eligible for maternity leave?")
        card = writer.of_type("leave_failure")[0]["data"]
        done = writer.done()["data"]
        assert done["failure"] == card["failure"]
        # Pre-existing HEL-280 fields must survive alongside it.
        assert done["reason_code"] == "LEAVE_TYPE_NOT_IN_POLICY"
        assert done["available_leave_types"]

    async def test_a_real_verdict_emits_no_failure_card(self):
        """A genuine eligibility verdict is an answer, not a failure, and emits no failure card."""
        writer = await _run("am I eligible for casual leave?")
        assert writer.of_type("leave_failure") == []
