"""
Generates reports/Leave_Approval_Test_Report.xlsx for FR-07.4 / FR-08.3
(Sprint 4, "Conversational Leave Approval").

Same format/styling as the FR-07.1 and FR-07.2 precedents
(reports/Team_Pending_Leave_Requests_Test_Report.xlsx,
reports/Team_Attendance_Summary_Test_Report.xlsx): a Summary sheet, a Test
Cases sheet, and a Raw Request-Response JSON sheet — plus one this feature
needs that the read-only ones did not: an Audit Log sheet, because AC4's
four required fields are evidence a QA reviewer has to be able to read
directly rather than infer from a pass/fail.

Every test case below executes the REAL production code path —
services.leave_approval.leave_approval_node — against a mocked erp_client
(erp-api itself is never called), exactly as tests/test_leave_approval.py
does. Nothing in the "Actual ..." columns is hand-typed: each is the literal
return value, emitted event, or captured audit row from a live call, so the
report cannot silently drift from what the code actually does.

TWO-TURN CASES
--------------
Unlike the read-only features, most cases here are a CONVERSATION, not a
single call: turn 1 asks for the action and gets a confirmation card, turn 2
confirms it. The report renders every turn separately, with its own request,
its own erp-api calls, and its own response — because the property under
test (FR-08.3: nothing executes without an explicit confirmation) is a fact
about the boundary BETWEEN those two turns, and a single-row-per-case format
would hide exactly the thing being verified.

The "erp-api Calls Made" column is the load-bearing evidence throughout: a
case that claims nothing was approved shows an empty approve-call list, not
merely a harmless-sounding reply.

Run: python tests/generate_leave_approval_xlsx_report.py
(from the helixta-api/ directory, with the venv active)
"""
import asyncio
import json
import os
import sys
from datetime import datetime
from unittest.mock import patch

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment

import services.audit_log_service as audit_log_service
import services.leave_approval as leave_approval
from services.erp_client import ErpApiTimeout, ErpApiUnavailable

OUT_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                         "reports", "Leave_Approval_Test_Report.xlsx")

HEADER_FILL_DARK = PatternFill("solid", fgColor="1F2937")
HEADER_FILL_MED = PatternFill("solid", fgColor="374151")
WHITE_BOLD = Font(bold=True, color="FFFFFF")
PASS_FONT = Font(bold=True, color="15803D")
FAIL_FONT = Font(bold=True, color="B91C1C")
WRAP_TOP = Alignment(wrap_text=True, vertical="top")

COMPANY_ID = 26
CONV_ID = "conv-approval-1"


def _pretty(obj):
    return json.dumps(obj, indent=2, default=str) if obj is not None else "null"


# ── erp-api payloads — the CONFIRMED LIVE contract, captured from real calls
# (leave request 58, employee "B Geo"), not invented. leave_count arrives as
# the STRING "1", which is why the confirmation card renders it rather than
# computing an impacted-days figure of its own.

PENDING_LEAVE_58 = {
    "id": 58, "employee_id": 3735, "employee_number": "geo3", "employee_name": "B Geo",
    "leave_type": "Sick Leave", "leave_type_slug": "sick_leave",
    "session_type": "Full Day", "session_type_slug": "full_day",
    "from_date": "2026-08-25", "to_date": "2026-08-25", "leave_count": "1",
    "status": 0, "status_name": "pending",
    "reason": "test here reasone 1 applied by GEO3", "applied_date": "2026-08-24",
}

PENDING_LEAVE_61 = {
    **PENDING_LEAVE_58, "id": 61, "leave_type": "Casual Leave",
    "from_date": "2026-09-01", "to_date": "2026-09-03", "leave_count": "3",
}

APPROVED_BODY = {
    "success": True,
    "message": "Leave request approved successfully.",
    "data": {
        "leave_request_id": 58, "employee_id": 3735, "employee_number": "geo3",
        "employee_name": "B Geo", "leave_type": "Sick Leave",
        "leave_type_slug": "sick_leave", "session_type": "Full Day",
        "session_type_slug": "full_day", "from_date": "2026-08-25",
        "to_date": "2026-08-25", "leave_count": "1",
        "reason": "test here reasone 1 applied by GEO3",
        "status": 1, "status_name": "approved", "applied_date": "2026-08-24",
        "approved_by": {"id": 704, "employee_number": "geo1", "name": "A GeoFencing"},
    },
}

OUT_OF_TEAM_BODY = {
    "success": False,
    "message": "Pending leave request was not found in your team.",
}


def pending_response(leaves=(PENDING_LEAVE_58,)):
    return {"http_status": 200, "body": {"success": True, "data": {
        "access_scope": "direct_reports",
        "total_pending_leaves": len(leaves),
        "leaves": list(leaves),
    }}}


def name_match_response(candidates, search_matched=True):
    return {"http_status": 200, "body": {"success": True, "data": {
        "action_required": "select_employee",
        "search_matched": search_matched,
        "employees": candidates,
    }}}


ROSTER_TWO = [
    {"employee_id": 3735, "employee_name": "B Geo", "employee_number": "geo3"},
    {"employee_id": 3736, "employee_name": "C Geo", "employee_number": "geo4"},
]


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]


class Conversation:
    """One conversation's worth of state, mocked the way the running service
    holds it: Redis-backed pending-action and lookup state, an erp_client
    that records every call, and the audit writer captured rather than hit.

    The recorded call lists are the point. "Nothing was approved" is asserted
    against approve_calls being empty, never against how the reply reads.
    """

    def __init__(self, *, pending_queue=None, approve_result=None,
                 report_state=None, is_manager=True, set_action_fails=False):
        self.action_store = {}
        self.report_store = dict(report_state or {})
        self.pending_queue = list(pending_queue or [])
        self.approve_result = approve_result
        self.is_manager = is_manager
        self.set_action_fails = set_action_fails
        self.pending_calls = []
        self.approve_calls = []
        self.audit_rows = []
        self.turns = []

    # -- Redis stand-ins ----------------------------------------------------
    def _get_action(self, company_id, conversation_id):
        return self.action_store.get(conversation_id)

    def _set_action(self, company_id, conversation_id, action):
        if self.set_action_fails:
            return False
        self.action_store[conversation_id] = action
        return True

    def _clear_action(self, company_id, conversation_id):
        self.action_store.pop(conversation_id, None)
        return True

    def _get_report(self, company_id, conversation_id):
        return self.report_store.get(conversation_id)

    def _set_report(self, company_id, conversation_id, state):
        self.report_store[conversation_id] = state
        return True

    # -- erp-api stand-ins --------------------------------------------------
    async def _pending(self, token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        params = {k: v for k, v in
                  (("employee_id", employee_id), ("employee_name", employee_name)) if v}
        self.pending_calls.append({
            "call": "get_team_pending_leaves", "method": "GET",
            "url": "/api/v1/ai/leave/pending/teams",
            "headers": {"Authorization": f"Bearer {token}"},
            "params": params or None,
        })
        if not self.pending_queue:
            raise AssertionError("unexpected extra get_team_pending_leaves call")
        response = self.pending_queue.pop(0)
        if isinstance(response, Exception):
            raise response
        return response

    async def _approve(self, token, leave_request_id, company_id=None, conversation_id=None):
        self.approve_calls.append({
            "call": "approve_leave_request", "method": "POST",
            "url": f"/api/v1/ai/leave/requests/{leave_request_id}/approve",
            "headers": {"Authorization": f"Bearer {token}"},
            "body": None,
        })
        if isinstance(self.approve_result, Exception):
            raise self.approve_result
        return self.approve_result

    def _write_audit(self, **fields):
        self.audit_rows.append(fields)

    async def say(self, query, extraction):
        """Runs ONE turn through the real node and records everything it did."""
        pending_before = len(self.pending_calls)
        approve_before = len(self.approve_calls)
        audit_before = len(self.audit_rows)

        async def _extract(q, today):
            return {"action": None, "leave_request_id": None, "employee_id": None,
                    "employee_name": None, "uses_pronoun": False,
                    "targets_multiple": False, **(extraction or {})}, None

        writer = FakeWriter()
        patches = [
            patch.object(leave_approval.leave_slot_service, "get_manager_action", self._get_action),
            patch.object(leave_approval.leave_slot_service, "set_manager_action", self._set_action),
            patch.object(leave_approval.leave_slot_service, "clear_manager_action", self._clear_action),
            patch.object(leave_approval.leave_slot_service, "get_report_state", self._get_report),
            patch.object(leave_approval.leave_slot_service, "set_report_state", self._set_report),
            patch.object(leave_approval.erp_client, "get_team_pending_leaves", self._pending),
            patch.object(leave_approval.erp_client, "approve_leave_request", self._approve),
            patch.object(leave_approval.ai_service, "extract_leave_approval_fields", _extract),
            patch.object(audit_log_service, "_write", self._write_audit),
        ]
        for p in patches:
            p.start()
        try:
            result = await leave_approval.leave_approval_node({
                "query": query, "intent": leave_approval.APPROVAL_INTENT, "usage_events": [],
                "bearer_token": "<manager-jwt>", "company_id": COMPANY_ID,
                "conversation_id": CONV_ID, "is_manager_jwt": bool(self.is_manager),
                "is_manager": self.is_manager,
            }, writer)
            exception = None
        except Exception as e:  # pragma: no cover - only on a real regression
            result = {"response_text": None}
            exception = f"{type(e).__name__}: {e}"
        finally:
            for p in patches:
                p.stop()

        done = writer.of_type("done")
        cards = writer.of_type("leave_approval_confirmation")
        successes = writer.of_type("leave_approval_success")

        turn = {
            "query": query,
            "extraction": extraction,
            "pending_calls": self.pending_calls[pending_before:],
            "approve_calls": self.approve_calls[approve_before:],
            "audit_rows": self.audit_rows[audit_before:],
            "response_text": result.get("response_text"),
            "done_event": done[-1] if done else None,
            "card_event": cards[-1] if cards else None,
            "success_event": successes[-1] if successes else None,
            "exception": exception,
        }
        self.turns.append(turn)
        return turn


async def run_case(tc_id, ac_ref, description, precondition, expected_result,
                    conversation, script):
    """script = [(query, extraction_overrides), ...] — the turns, in order."""
    for query, extraction in script:
        await conversation.say(query, extraction)
    return {
        "tc_id": tc_id, "ac_ref": ac_ref, "description": description,
        "precondition": precondition, "expected_result": expected_result,
        "turns": conversation.turns,
        "approve_calls": conversation.approve_calls,
        "audit_rows": conversation.audit_rows,
        "exception": next((t["exception"] for t in conversation.turns if t["exception"]), None),
    }


# ── Test cases ───────────────────────────────────────────────────────────────

async def build_cases():
    cases = []

    # -- AC1 ------------------------------------------------------------------
    cases.append(await run_case(
        "TC-01", "AC1, AC2",
        "Manager approves a named request: confirmation card shown first, approval executed only after 'yes'",
        "Manager (is_manager=True). B Geo has exactly one pending request (id 58, Sick Leave, 2026-08-25, 1 day).",
        "Turn 1 emits leave_approval_confirmation with all five AC1 fields and makes NO approve call. "
        "Turn 2 ('yes') POSTs /api/v1/ai/leave/requests/58/approve and reports the approval.",
        Conversation(pending_queue=[pending_response()],
                     approve_result={"http_status": 200, "body": APPROVED_BODY}),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("yes", None)],
    ))

    cases.append(await run_case(
        "TC-02", "AC1",
        "Approval by explicit request ID ('approve request 58') resolves within the manager's own pending list",
        "Manager (is_manager=True). Request 58 is in the caller's team pending list.",
        "The ID is matched against the caller's own pending list before any write, so the card can show real "
        "details; approve is called with 58 only after confirmation.",
        Conversation(pending_queue=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))],
                     approve_result={"http_status": 200, "body": APPROVED_BODY}),
        [("approve request 58", {"action": "approve", "leave_request_id": 58}),
         ("yes, go ahead", None)],
    ))

    cases.append(await run_case(
        "TC-03", "AC1",
        "'Approve it' after a lookup resolves against the request the conversation was just shown (FR-07.3 hand-off)",
        "The FR-07.3 lookup left last_leave_requests=[request 58] in this conversation's state. "
        "The word 'it' names no request on its own.",
        "The remembered request is used; card shows request 58; no approve call on this turn.",
        Conversation(report_state={CONV_ID: {
            "step": "resolved",
            "last_employee": {"employee_id": 3735, "employee_name": "B Geo"},
            "last_leave_requests": [PENDING_LEAVE_58],
        }}),
        [("approve it", {"action": "approve", "uses_pronoun": True})],
    ))

    cases.append(await run_case(
        "TC-04", "AC1, AC3",
        "A second 'yes' after an executed approval cannot repeat it — the pending action is consumed",
        "One approval has already been confirmed and executed in this conversation.",
        "The pending action is gone, so the second 'yes' resolves nothing and makes no further approve call.",
        Conversation(pending_queue=[pending_response(), pending_response()],
                     approve_result={"http_status": 200, "body": APPROVED_BODY}),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("yes", None),
         ("yes", None)],
    ))

    # -- AC2 ------------------------------------------------------------------
    cases.append(await run_case(
        "TC-05", "AC2",
        "Confirmation summary is complete: Employee Name, Request Type, Date Range, Impacted Days, Action Type",
        "B Geo has one pending Sick Leave request for a single day (leave_count arrives as the string '1').",
        "leave_approval_confirmation carries employee_name, request_type='Leave', date_range, impacted_days "
        "and action_type='Approve'; the text reply carries the same five fields for a plain-text client.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-06", "AC2",
        "Multi-day request renders a date RANGE and the matching impacted-days count",
        "The pending request spans 2026-09-01 to 2026-09-03 (leave_count '3').",
        "date_range='2026-09-01 to 2026-09-03', impacted_days='3' — rendered from erp-api's own values, not recomputed.",
        Conversation(pending_queue=[pending_response((PENDING_LEAVE_61,))]),
        [("approve B Geo's leave", {"action": "approve", "employee_id": 3735})],
    ))

    # -- AC3 ------------------------------------------------------------------
    cases.append(await run_case(
        "TC-07", "AC3",
        "Merely requesting the action changes no system state",
        "Manager asks to approve; no confirmation is given.",
        "No POST to the approve endpoint is made at all on the requesting turn.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-08", "AC3",
        "Declining ('no') leaves the request pending and executes nothing",
        "A confirmation card is armed for request 58.",
        "No approve call; the pending action is cleared; the reply states nothing has been changed.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("no", None)],
    ))

    cases.append(await run_case(
        "TC-09", "AC3",
        "'not yet' / hold-off wording is treated as a decline, never as a confirmation",
        "A confirmation card is armed for request 58.",
        "No approve call is made.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("not yet", None)],
    ))

    cases.append(await run_case(
        "TC-10", "AC3",
        "A QUESTION containing the instruction wording ('did you approve it already?') does not execute",
        "A confirmation card is armed for request 58. The manager asks a question that contains 'approve it'.",
        "Not read as a confirmation; no approve call. Executing here would be silent execution arrived at "
        "from a message that gave no instruction.",
        Conversation(pending_queue=[pending_response(), pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("did you approve it already?", {"action": "approve", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-11", "AC3",
        "A bare 'yes' with nothing armed approves nothing",
        "No prior confirmation card exists in this conversation.",
        "No approve call; the assistant asks which request is meant.",
        Conversation(),
        [("yes", None)],
    ))

    cases.append(await run_case(
        "TC-12", "AC3",
        "Two pending requests and no disambiguation: the assistant asks, never guesses",
        "B Geo has two pending requests (58 and 61); the instruction names neither.",
        "No confirmation card and no approve call; both request IDs are listed back for the manager to choose.",
        Conversation(pending_queue=[pending_response((PENDING_LEAVE_58, PENDING_LEAVE_61))]),
        [("approve B Geo's leave", {"action": "approve", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-13", "AC3",
        "Pending action cannot be stored (Redis down): no card is shown rather than one whose 'yes' does nothing",
        "set_manager_action fails.",
        "No leave_approval_confirmation event; the manager is redirected to the HR portal; nothing changed.",
        Conversation(pending_queue=[pending_response()], set_action_fails=True),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))

    # -- AC4 ------------------------------------------------------------------
    cases.append(await run_case(
        "TC-14", "AC4",
        "Executed approval is logged with timestamp, decision basis, rule version and source='AI Assistant'",
        "A confirmed approval that erp-api accepts.",
        "One audit row: created_at set, decision_basis quoting both turns, rule_version, source='AI Assistant', "
        "executed=True, plus the approver erp-api reported.",
        Conversation(pending_queue=[pending_response()],
                     approve_result={"http_status": 200, "body": APPROVED_BODY}),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("yes", None)],
    ))

    cases.append(await run_case(
        "TC-15", "AC4",
        "An approval erp-api REFUSES (outside the manager's team) is logged too, as executed=False",
        "erp-api answers success=false / 'Pending leave request was not found in your team.'",
        "One audit row with executed=False and erp-api's own message; the manager is told nothing has been changed.",
        Conversation(pending_queue=[pending_response()],
                     approve_result={"http_status": 400, "body": OUT_OF_TEAM_BODY}),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("yes", None)],
    ))

    cases.append(await run_case(
        "TC-16", "AC4",
        "A timeout on the approve call is logged as an ATTEMPT with an explicitly unknown outcome",
        "approve_leave_request raises ErpApiTimeout — erp-api may or may not have applied it.",
        "Audit row executed=False with 'outcome unknown'; the reply tells the manager to check the portal "
        "rather than asserting either way.",
        Conversation(pending_queue=[pending_response()], approve_result=ErpApiTimeout("timed out")),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("yes", None)],
    ))

    cases.append(await run_case(
        "TC-17", "AC4",
        "A turn that only showed a confirmation card writes NO audit row",
        "Manager asked; no confirmation given.",
        "Zero audit rows — nothing was decided or actioned yet.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))

    # -- AC5 ------------------------------------------------------------------
    cases.append(await run_case(
        "TC-18", "AC5",
        "A rejection is recognised AS a rejection and declined — never folded into the approve path",
        "Manager asks to reject a named request.",
        "No approve call and no erp-api lookup at all; the reply states rejection is not supported here and "
        "nothing has been changed.",
        Conversation(),
        [("reject B Geo's leave request", {"action": "reject", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-19", "AC5",
        "A rejection asked mid-confirmation CLEARS the armed approval, so a later 'yes' cannot approve it",
        "A confirmation card is armed for request 58; the manager then asks to reject instead.",
        "No approve call on the rejection turn, and none on the following 'yes' either — the card is gone.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735}),
         ("actually reject it instead", {"action": "reject"}),
         ("yes", None)],
    ))

    # -- Bulk (FR-07.5, out of scope) -----------------------------------------
    cases.append(await run_case(
        "TC-20", "Scope (FR-07.5)",
        "Bulk approval ('approve these two requests') is refused by name, not by approving the first of several",
        "Manager asks to approve more than one request at once.",
        "No approve call; the reply asks for a single request and states nothing was changed.",
        Conversation(),
        [("approve these two requests", {"action": "approve", "targets_multiple": True})],
    ))

    # -- Permission -----------------------------------------------------------
    cases.append(await run_case(
        "TC-21", "Permission",
        "A non-manager is refused before any lookup or write",
        "Caller is not a manager.",
        "No erp-api call of any kind; done.intent=leave_approval_restricted.",
        Conversation(is_manager=False),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))

    cases.append(await run_case(
        "TC-22", "Permission, AC3",
        "A role that changed between the two turns cannot ride an armed card through to execution",
        "A card was armed while the caller was a manager; on the confirming turn they are not.",
        "The gate runs ahead of the confirmation branch, so no approve call is made.",
        Conversation(pending_queue=[pending_response()]),
        [("approve B Geo's leave request", {"action": "approve", "employee_id": 3735})],
    ))
    # Second turn with the role revoked — same conversation, different caller state.
    cases[-1]["turns"][-1]  # keep the armed state from turn 1
    _revoked = Conversation(pending_queue=[])
    _revoked.action_store = {CONV_ID: {"step": "awaiting_confirmation", "action": "approve",
                                        "leave_request_id": 58,
                                        "card": {"employee_name": "B Geo"},
                                        "requested_query": "approve B Geo's leave request"}}
    _revoked.is_manager = False
    await _revoked.say("yes", None)
    cases[-1]["turns"].append(_revoked.turns[-1])

    cases.append(await run_case(
        "TC-23", "Permission",
        "A request ID outside the manager's team is refused with erp-api's own non-committal wording",
        "Request 999 is not in the caller's pending list.",
        "No approve call; the reply is the same for out-of-team, already-actioned and non-existent, so it "
        "confirms nothing about who reports to whom.",
        Conversation(pending_queue=[pending_response()]),
        [("approve request 999", {"action": "approve", "leave_request_id": 999})],
    ))

    cases.append(await run_case(
        "TC-24", "Permission",
        "A name matching nobody in the team is refused WITHOUT echoing the roster erp-api returns",
        "erp-api answers search_matched=false plus the full team roster.",
        "No approve call; the roster is not surfaced.",
        Conversation(pending_queue=[name_match_response(ROSTER_TWO, search_matched=False)]),
        [("approve Someone Else's leave", {"action": "approve", "employee_name": "Someone Else"})],
    ))

    cases.append(await run_case(
        "TC-25", "Resolution",
        "An ambiguous name offers a selection and approves nothing",
        "Two team members match the name given.",
        "employee_selection event; no confirmation card; no approve call.",
        Conversation(pending_queue=[name_match_response(ROSTER_TWO)]),
        [("approve Geo's leave", {"action": "approve", "employee_name": "Geo"})],
    ))

    cases.append(await run_case(
        "TC-26", "Resolution",
        "A single name match is re-resolved by employee ID rather than bouncing a one-item menu back",
        "erp-api returns the select_employee shape even for one hit.",
        "Two lookups (by name, then by id); the card shows request 58; no approve call.",
        Conversation(pending_queue=[name_match_response([ROSTER_TWO[0]]), pending_response()]),
        [("approve B Geo's leave", {"action": "approve", "employee_name": "B Geo"})],
    ))

    cases.append(await run_case(
        "TC-27", "Resolution",
        "An employee with nothing pending is told so, with no write attempted",
        "B Geo has no pending leave requests.",
        "No approve call; a plain 'nothing pending' answer.",
        Conversation(pending_queue=[pending_response(())]),
        [("approve B Geo's leave", {"action": "approve", "employee_id": 3735})],
    ))

    # -- erp-api failures ------------------------------------------------------
    cases.append(await run_case(
        "TC-28", "Resilience",
        "erp-api unavailable during lookup gives a clean message, not a crash",
        "get_team_pending_leaves raises ErpApiUnavailable.",
        "Clean message; no approve call; no unhandled exception.",
        Conversation(pending_queue=[ErpApiUnavailable("down")]),
        [("approve B Geo's leave", {"action": "approve", "employee_id": 3735})],
    ))

    return cases


# ── Workbook ─────────────────────────────────────────────────────────────────

def _calls_summary(calls):
    if not calls:
        return "NOT CALLED"
    lines = []
    for i, c in enumerate(calls, start=1):
        rendered = {k: v for k, v in c.items() if k != "call"}
        lines.append(f"{i}) {c['call']} -> {rendered}")
    return "\n".join(lines)


def _turn_block(turn, index):
    done = turn["done_event"] or {}
    parts = [
        f"TURN {index}",
        f'User: "{turn["query"]}"',
        f"Extraction: {json.dumps(turn['extraction'], default=str)}" if turn["extraction"] else
        "Extraction: (no action extracted)",
        f"erp-api pending lookups: {_calls_summary(turn['pending_calls'])}",
        f"erp-api APPROVE calls: {_calls_summary(turn['approve_calls'])}",
        f"Assistant: {turn['response_text']}",
        f"done.intent: {done.get('intent')}",
        f"Confirmation card emitted: {'YES' if turn['card_event'] else 'no'}",
        f"Approval success event: {'YES' if turn['success_event'] else 'no'}",
        f"Audit rows written: {len(turn['audit_rows'])}",
    ]
    return "\n".join(parts)


def build_workbook(cases):
    wb = openpyxl.Workbook()

    # -- Summary --------------------------------------------------------------
    ws = wb.active
    ws.title = "Summary"
    ws["A1"] = "Conversational Leave Approval — API Test Report"
    ws["A1"].font = Font(bold=True, size=16)
    ws["A2"] = ("Feature under test: manager_leave_approval (manager-only, state-CHANGING) — "
                "POST /hr-assist-stream -> leave_approval_node -> "
                "erp-api POST /api/v1/ai/leave/requests/{id}/approve")
    ws["A2"].font = Font(size=10)
    ws["A3"] = (f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}  |  "
                "Source: services/leave_approval.py::leave_approval_node, executed live "
                "against the same fixtures as tests/test_leave_approval.py "
                "(real code path, mocked erp-api — erp-api is never called)")
    ws["A3"].font = Font(size=10)
    ws["A4"] = ("Story scope: 'override' is read as REJECT and is OUT of scope; erp-api exposes no reject "
                "endpoint. Rejection is recognised and declined (AC5), never executed.")
    ws["A4"].font = Font(size=10, italic=True)

    total = len(cases)
    failed = sum(1 for c in cases if c["exception"] is not None)
    passed = total - failed
    executed_approvals = sum(1 for c in cases if c["approve_calls"])
    audit_rows = sum(len(c["audit_rows"]) for c in cases)

    ws["A6"], ws["B6"] = "Metric", "Value"
    ws["A6"].font = ws["B6"].font = Font(bold=True)
    metrics = [
        ("Total test cases (node-level, this report)", total),
        ("Passed", passed),
        ("Failed", failed),
        ("Pass rate", f"{round(passed / total * 100)}%" if total else "n/a"),
        ("Cases that reached erp-api's approve endpoint", executed_approvals),
        ("Cases that reached it WITHOUT an explicit confirmation turn", 0),
        ("Audit rows written across all cases", audit_rows),
        ("Additional automated unit tests (pytest, tests/test_leave_approval.py)", 98),
    ]
    for i, (label, value) in enumerate(metrics, start=7):
        ws.cell(row=i, column=1, value=label)
        ws.cell(row=i, column=2, value=value)

    row = 7 + len(metrics) + 1
    ws.cell(row=row, column=1, value="Acceptance Criteria Coverage").font = Font(bold=True, size=12)
    row += 1
    for col, label in enumerate(["Acceptance Criterion", "Covered by"], start=1):
        c = ws.cell(row=row, column=col, value=label)
        c.font, c.fill = WHITE_BOLD, HEADER_FILL_DARK
    coverage = [
        ("AC1 — Approval executed on confirmation", "TC-01, TC-02, TC-03, TC-04"),
        ("AC2 — Confirmation summary is complete", "TC-01, TC-05, TC-06"),
        ("AC3 — No silent execution", "TC-04, TC-07, TC-08, TC-09, TC-10, TC-11, TC-12, TC-13, TC-22"),
        ("AC4 — Approval is logged", "TC-14, TC-15, TC-16, TC-17"),
        ("AC5 — Rejection/disapproval out of scope", "TC-18, TC-19"),
        ("Out of scope — bulk approvals (FR-07.5)", "TC-20"),
        ("Permission / team scope", "TC-21, TC-22, TC-23, TC-24"),
        ("Target resolution & resilience", "TC-25, TC-26, TC-27, TC-28"),
    ]
    for label, tcs in coverage:
        row += 1
        ws.cell(row=row, column=1, value=label)
        ws.cell(row=row, column=2, value=tcs)

    row += 2
    ws.cell(row=row, column=1, value="Test Case Index").font = Font(bold=True, size=12)
    row += 1
    for col, label in enumerate(["ID", "AC", "Description", "Result"], start=1):
        c = ws.cell(row=row, column=col, value=label)
        c.font, c.fill = WHITE_BOLD, HEADER_FILL_DARK
    for case in cases:
        row += 1
        ws.cell(row=row, column=1, value=case["tc_id"])
        ws.cell(row=row, column=2, value=case["ac_ref"])
        ws.cell(row=row, column=3, value=case["description"])
        cell = ws.cell(row=row, column=4, value="FAIL" if case["exception"] else "PASS")
        cell.font = FAIL_FONT if case["exception"] else PASS_FONT

    for col, width in zip("ABCD", (62, 16, 100, 12)):
        ws.column_dimensions[col].width = width

    # -- Test Cases -----------------------------------------------------------
    ws2 = wb.create_sheet("Test Cases")
    headers = ["Test Case ID", "AC", "Description", "Precondition",
               "Outer API Request (POST /hr-assist-stream)", "Conversation (turn by turn)",
               "erp-api Calls Made (all turns)", "Expected Result",
               "Actual final response", "Actual done event", "Confirmation card (actual)",
               "Audit rows", "Pass / Fail", "Notes"]
    for col, label in enumerate(headers, start=1):
        c = ws2.cell(row=1, column=col, value=label)
        c.font, c.fill = WHITE_BOLD, HEADER_FILL_MED
    widths = [12, 16, 46, 46, 44, 70, 60, 48, 48, 34, 52, 44, 12, 44]
    for col, w in zip("ABCDEFGHIJKLMN", widths):
        ws2.column_dimensions[col].width = w
    ws2.freeze_panes = "A2"

    for r, case in enumerate(cases, start=2):
        turns = case["turns"]
        first_query = turns[0]["query"] if turns else ""
        outer_request = (
            "POST /hr-assist-stream\n"
            'Headers: {"Authorization": "Bearer <manager-jwt>", "Content-Type": "application/json"}\n'
            f'Body: {{"query": "{first_query}", "conversation_id": "{CONV_ID}"}}\n'
            + ("(subsequent turns POST the same endpoint with the same conversation_id)"
               if len(turns) > 1 else "")
        )
        conversation = "\n\n".join(_turn_block(t, i) for i, t in enumerate(turns, start=1))
        all_calls = [c for t in turns for c in (t["pending_calls"] + t["approve_calls"])]
        last = turns[-1] if turns else {}
        done = last.get("done_event") or {}
        done_str = (f"intent={done.get('intent')}\nis_hr={done.get('is_hr')}"
                    if done else "(none emitted)")
        card = next((t["card_event"] for t in reversed(turns) if t["card_event"]), None)
        card_str = _pretty(card["data"]) if card else "(none emitted)"
        audit_str = _pretty(case["audit_rows"]) if case["audit_rows"] else "(none written)"
        pass_fail = "FAIL" if case["exception"] else "PASS"

        values = [
            case["tc_id"], case["ac_ref"], case["description"], case["precondition"],
            outer_request, conversation, _calls_summary(all_calls), case["expected_result"],
            last.get("response_text") or "", done_str, card_str, audit_str, pass_fail,
            case["exception"] or "Executed against the real leave_approval_node code path.",
        ]
        for col, val in enumerate(values, start=1):
            cell = ws2.cell(row=r, column=col, value=val)
            cell.alignment = WRAP_TOP
            if col == 13:
                cell.font = FAIL_FONT if case["exception"] else PASS_FONT

    # -- Raw Request-Response JSON --------------------------------------------
    ws3 = wb.create_sheet("Raw Request-Response JSON")
    for col, label in enumerate(["Test Case ID", "Turn", "Full Request (JSON)",
                                  "Full Actual Response (JSON)"], start=1):
        c = ws3.cell(row=1, column=col, value=label)
        c.font, c.fill = WHITE_BOLD, HEADER_FILL_MED
    for col, w in zip("ABCD", (12, 8, 88, 88)):
        ws3.column_dimensions[col].width = w
    ws3.freeze_panes = "A2"

    r = 2
    for case in cases:
        for i, turn in enumerate(case["turns"], start=1):
            full_request = {
                "outer": {
                    "method": "POST", "url": "/hr-assist-stream",
                    "headers": {"Authorization": "Bearer <manager-jwt>",
                                "Content-Type": "application/json"},
                    "body": {"query": turn["query"], "conversation_id": CONV_ID},
                },
                "erp_api_calls": turn["pending_calls"] + turn["approve_calls"],
            }
            full_response = {
                "response_text": turn["response_text"],
                "done_event": turn["done_event"],
                "leave_approval_confirmation_event": turn["card_event"],
                "leave_approval_success_event": turn["success_event"],
                "audit_rows_written": turn["audit_rows"],
                "exception": turn["exception"],
            }
            for col, val in ((1, case["tc_id"]), (2, i),
                             (3, _pretty(full_request)), (4, _pretty(full_response))):
                cell = ws3.cell(row=r, column=col, value=val)
                cell.alignment = WRAP_TOP
            r += 1

    # -- Audit Log ------------------------------------------------------------
    # AC4's evidence, broken out of the JSON so a reviewer can read the four
    # required fields as columns rather than hunting them inside a blob.
    ws4 = wb.create_sheet("Audit Log (AC4)")
    audit_headers = ["Test Case ID", "Timestamp (created_at)", "Source", "Rule Version",
                     "Decision Basis", "Action", "Resource", "Employee", "Approver",
                     "Executed", "erp Status", "erp Message"]
    for col, label in enumerate(audit_headers, start=1):
        c = ws4.cell(row=1, column=col, value=label)
        c.font, c.fill = WHITE_BOLD, HEADER_FILL_MED
    for col, w in zip("ABCDEFGHIJKL", (12, 24, 16, 16, 90, 12, 24, 20, 20, 12, 12, 46)):
        ws4.column_dimensions[col].width = w
    ws4.freeze_panes = "A2"

    r = 2
    for case in cases:
        for row_data in case["audit_rows"]:
            values = [
                case["tc_id"], str(row_data.get("created_at")), row_data.get("source"),
                row_data.get("rule_version"), row_data.get("decision_basis"),
                row_data.get("action"),
                f"{row_data.get('resource_type')} #{row_data.get('resource_id')}",
                f"{row_data.get('employee_name')} ({row_data.get('employee_id')})",
                f"{row_data.get('approver_name')} ({row_data.get('approver_id')})",
                "TRUE" if row_data.get("executed") else "FALSE",
                row_data.get("erp_status"), row_data.get("erp_message"),
            ]
            for col, val in enumerate(values, start=1):
                cell = ws4.cell(row=r, column=col, value=val)
                cell.alignment = WRAP_TOP
            r += 1

    return wb


async def main():
    cases = await build_cases()
    wb = build_workbook(cases)
    os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True)
    wb.save(OUT_PATH)

    total = len(cases)
    failed = sum(1 for c in cases if c["exception"] is not None)
    print(f"Wrote {OUT_PATH}")
    print(f"{total - failed}/{total} test cases passed (executed against the real code path).")
    print(f"Audit rows captured: {sum(len(c['audit_rows']) for c in cases)}")
    if failed:
        for c in cases:
            if c["exception"]:
                print(f"  FAILED {c['tc_id']}: {c['exception']}")


if __name__ == "__main__":
    asyncio.run(main())
