"""
Multi-prompt test sweep for the leave conversational AI feature.

Exercises services.nlp_service.fast_classify() — the deterministic
keyword/regex layer that every fix this project has made lives in — against
a large, hand-curated set of realistic user phrasings across the four query
categories the feature supports:

    1. Apply Leave           (expected intent: apply_leave)
    2. Leave Balance         (expected intent: leave_balance)
    3. Leave Status          (expected intent: leave_status)
    4. Applied Leave Status  (expected intent: leave_status — phrasings
                               specifically about an already-submitted
                               leave's status/outcome, as opposed to
                               general "check my leave status" phrasing)

Plus a fifth control category, Negative / Non-Leave, of queries that must
NOT be routed into any of the three leave intents — this is what catches
over-broad regex patterns silently hijacking unrelated HR questions (the
exact failure mode of the "check my leave" regression caught and fixed
earlier in this same session).

Classification pass/fail (the Expected/Actual/Result columns) is decided by
fast_classify() alone. Separately, for every query that lands on a leave
intent, this script also drives the real services.hr_graph.leave_action_node
end-to-end against a REAL, RUNNING erp-api instance and a REAL logged-in
employee account — not fixture data — so the Bot Response column shows the
actual database-backed answer (real leave balance figures, real leave
requests with their real statuses) a live user would get for that exact
phrasing. leave_action_node's balance/status branches make a real HTTP call
per query; the apply_leave branch's first turn additionally makes a REAL
OpenAI call (services.ai_service._call_llm, the same slot-extraction call
production uses) to see what the assistant would actually ask for next.
This means results can vary run-to-run with the account's real leave data
and can be slower — it's making real network calls, not returning canned
data.

Nothing here can submit a real leave application: leave_action_node only
calls erp_client.apply_leave() on a confirmation turn (a prior turn must
already be sitting at step="awaiting_confirmation" AND this turn's
extraction must set is_affirmative), and every query in this sweep is
simulated as a single fresh turn with empty prior slots — so at most it
reaches "Shall I submit this request?" and stops there.

Requires, before running:
  - erp-api reachable and its login endpoint working (needs Redis up too —
    the login flow itself depends on it)
  - Env vars: REPORT_TEST_USER_EMAIL, REPORT_TEST_USER_PASSWORD identifying
    a real role_id=5 (employee, not manager) account to log in as
  - Optional: REPORT_ERP_API_URL to point at erp-api if it isn't at the
    ERP_API_URL already configured in .env (e.g. running it on a different
    port locally)

Not covered: the LLM intent-classification fallback (fast_classify returns
(None, True, 0.0) for low-confidence queries and LangGraph falls back to an
LLM call) and turns 2+ of the apply-leave conversation (date/confirmation
turns) — each query here is simulated as a single fresh turn with empty
prior slots, matching how a brand new conversation would start.

Run: python tests/multi_prompt_report.py
Writes: <repo>/reports/leave_ai_test_report_<timestamp>.xlsx
"""

import asyncio
import datetime
import os
import sys
from typing import Optional
from unittest.mock import patch

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

# services/ai_service.py reads its provider/API-key env vars at import time
# but doesn't call load_dotenv() itself — it relies on main.py (the real
# app entrypoint) having done that first. This script IS the entrypoint
# here, so it must load .env before importing anything under services/.
from dotenv import load_dotenv
load_dotenv()

from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter

from services.nlp_service import fast_classify
import services.hr_graph as hr_graph

# ---------------------------------------------------------------------------
# Test case catalogue: (query, expected_intent_or_None, category)
# expected_intent is one of "apply_leave" / "leave_balance" / "leave_status",
# or None for the negative-control category (any leave_* intent is a FAIL).
# ---------------------------------------------------------------------------

APPLY_LEAVE_CASES = [
    "I want to apply for leave",
    "Apply casual leave tomorrow",
    "Apply sick leave for next week",
    "Book sick leave for next Monday",
    "Please book casual leave for me",
    "I need a day off tomorrow",
    "I want to take a day off next Friday",
    "Raise a leave request for earned leave",
    "Request leave for 3 days starting Monday",
    "I want to take leave from 15th to 18th August",
    "Can I apply for annual leave next month?",
    "I need to apply for maternity leave",
    "Book a leave for me from tomorrow",
    "I want to take sick leave today",
    "Apply for 2 days casual leave",
    "I want to raise a leave application",
    "Need a day off for a family function",
    "I want to book earned leave for next week",
    "Apply for paternity leave starting next month",
    "I want to take unpaid leave for a week",
    "Please raise leave request for emergency leave",
    "I need to take leave tomorrow for a doctor's appointment",
    "Want to apply for leave from 20th to 22nd",
    "Book comp off for Friday",
    "I want to apply leave",
]

LEAVE_BALANCE_CASES = [
    "What is my leave balance?",
    "How many leaves do I have left?",
    "How many sick leaves do I have left?",
    "How many casual leaves do I have?",
    "sick leaves remaining",
    "What's my remaining leave balance?",
    "How many earned leaves are left?",
    "Check my leave balance",
    "check my leave",
    "check my leaves",
    "My casual leave balance please",
    "How much leave do I have remaining?",
    "leave quota remaining",
    "What is my sick leave balance?",
    "How many days of leave do I have left this year?",
    "remaining leave",
    "leaves left",
    "How many total leaves are left in my account?",
    "Can you tell me my leave balance?",
    "I want to know my leave balance",
    "How many paid leaves do I have remaining?",
    "What's the balance of my earned leave?",
    "leaves remaining for this year",
    "How many days off do I have left?",
    "casual leave balance",
]

LEAVE_STATUS_CASES = [
    "what is the status of my leave",
    "is my leave approved",
    "was my sick leave rejected",
    "check my leave request status",
    "leave status",
    "check my leave status",
    "What's the status of my casual leave?",
    "Has my leave been approved?",
    "Did my leave get rejected?",
    "leave approval status",
    "I want to know only pending leave status",
    "show me my pending leaves",
    "my rejected leaves",
    "cancelled leaves list",
    "I want to check my approved leaves",
    "check my approved leaves",
    "what's the status of my leave request",
    "Is my earned leave request approved yet?",
    "status of my leave application",
    "leave request status please",
    "Was my leave accepted?",
    "leave application status",
    "Did HR approve my leave?",
    "status of my casual leave",
]

APPLIED_LEAVE_STATUS_CASES = [
    "show me my applied leave",
    "show my applied leave",
    "my applied leave",
    "show me my leave applications",
    "view my leave requests",
    "I want to see the leave I applied for",
    "status of the leave I applied for",
    "what happened to the leave I applied for",
    "show me all leaves I've applied for",
    "list all my applied leaves",
    "I want to check my applied leave status",
    "applied leave status",
    "show me my leave application history",
    "can I see my applied leaves",
    "view all leave applications I've submitted",
    "what's the status of leave I applied for last week",
    "show my leave application list",
    "I want to see my submitted leave requests",
    "list of leaves I have applied",
    "show my previous leave applications",
]

NEGATIVE_CONTROL_CASES = [
    "What is the annual leave policy?",
    "What is the maternity leave policy?",
    "What is FMLA?",
    "How do I apply for a job?",
    "What is the casual leave policy?",
    "What is our sick leave policy?",
    "Tell me about the compensatory off policy",
    "What is the process for leave encashment?",
    "How many working hours per day?",
    "What is the work from home policy?",
    "How do I check in for attendance?",
    "What is our payroll processing schedule?",
    "How is my salary calculated?",
    "What health insurance benefits do we have?",
    "What are the job openings currently?",
    "Tell me about the onboarding process",
    "What is a performance improvement plan?",
    "hello",
    "thank you",
    "who are you",
]

CATEGORIES = [
    ("Apply Leave", APPLY_LEAVE_CASES, "apply_leave"),
    ("Leave Balance", LEAVE_BALANCE_CASES, "leave_balance"),
    ("Leave Status", LEAVE_STATUS_CASES, "leave_status"),
    ("Applied Leave Status", APPLIED_LEAVE_STATUS_CASES, "leave_status"),
    ("Negative Non-Leave Control", NEGATIVE_CONTROL_CASES, None),
]

_LEAVE_INTENTS = {"apply_leave", "leave_balance", "leave_status"}


def run_sweep():
    """Returns a list of result dicts: category, query, expected, actual,
    is_hr, confidence, passed."""
    results = []
    for category, queries, expected in CATEGORIES:
        for query in queries:
            intent, is_hr, confidence = fast_classify(query)
            if expected is None:
                passed = intent not in _LEAVE_INTENTS
                expected_label = "NOT apply_leave/leave_balance/leave_status"
            else:
                passed = intent == expected
                expected_label = expected
            results.append({
                "category": category,
                "query": query,
                "expected": expected_label,
                "actual": intent if intent else "(none / falls through to LLM)",
                "raw_actual_intent": intent,
                "is_hr": is_hr,
                "confidence": confidence,
                "passed": passed,
            })
    return results


# ---------------------------------------------------------------------------
# Response fetching — drives the real leave_action_node per query against a
# REAL, logged-in erp-api account. See module docstring for requirements and
# why this can never actually submit a leave application.
# ---------------------------------------------------------------------------

class _CapturingWriter:
    """leave_action_node's actual chat message ('Here's your current leave
    balance.') is deliberately generic — the real numbers go out separately
    as structured data (a 'leave_balance' stream event) for the UI to render
    as a card, and _finish()'s return value only carries the plain-text
    message, not that structured data. A no-op writer would silently drop
    the numbers this report needs; capture every event instead."""

    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 _format_leave_quota(leave_quota: dict) -> str:
    if not leave_quota:
        return "(no leave types found)"
    parts = []
    for slug, info in leave_quota.items():
        label = slug.replace("_", " ").title()
        parts.append(f"{label}: {info.get('remaining', '?')}/{info.get('total', '?')} remaining")
    return " | ".join(parts)


async def _login_real_account(erp_api_url: str, email: str, password: str) -> dict:
    """Logs in exactly like the Angular app does (browser_id is a required
    field) and returns the fields leave_action_node needs: the
    ai_assist_jwt_token (the credential erp_client actually authenticates
    leave calls with — a separate token from the Sanctum session token) plus
    the account's real user_id/company_id."""
    import httpx
    async with httpx.AsyncClient(timeout=20.0) as client:
        resp = await client.post(
            f"{erp_api_url}/api/v1/login",
            json={"email": email, "password": password, "browser_id": "multi-prompt-report-script"},
        )
    resp.raise_for_status()
    body = resp.json()
    if not body.get("success"):
        raise RuntimeError(f"erp-api login failed: {body.get('message')}")
    data = body["data"]
    if str(data.get("role_id")) != "5":
        raise RuntimeError(
            f"REPORT_TEST_USER_EMAIL must be a role_id=5 employee account "
            f"(this account has role_id={data.get('role_id')}) — a manager account "
            f"gets blocked by leave_action_node's role gate before any leave data is fetched."
        )
    return {
        "token": data["ai_assist_jwt_token"],
        "user_id": data["id"],
        "company_id": data["company_id"],
    }


_MAX_ERP_ATTEMPTS = 5


async def _fetch_one_response(query: str, intent: str, index: int, account: dict) -> str:
    """Runs leave_action_node for a single query against the REAL, logged-in
    account's real erp-api data. apply_leave's first turn additionally makes
    a real OpenAI slot-extraction call (see module docstring).

    Retries a few times on failure: `php artisan serve` is single-threaded
    and re-bootstraps Laravel on every request, and under 114 back-to-back
    real requests it occasionally drops a connection outright (confirmed via
    the server's own log showing zero exceptions for the failed calls — this
    is dev-server fragility, not an erp-api or leave_action_node bug, so
    retrying the same read-only/non-submitting call is safe and appropriate
    here specifically)."""
    if intent not in _LEAVE_INTENTS:
        return "(N/A — not classified into a leave-action intent; see Actual Intent column)"

    conversation_id = f"multi-prompt-report-{index}"
    state = {
        "query": query, "intent": intent, "usage_events": [],
        "bearer_token": account["token"], "company_id": account["company_id"],
        "conversation_id": conversation_id,
    }

    last_error: Optional[Exception] = None
    for attempt in range(1, _MAX_ERP_ATTEMPTS + 1):
        writer = _CapturingWriter()
        try:
            result = await hr_graph.leave_action_node(state, writer)
            message = result.get("response_text") or "(empty response)"

            if intent == "leave_balance":
                balance_events = writer.of_type("leave_balance")
                if balance_events:
                    leave_quota = balance_events[-1].get("data", {}).get("leave_quota", {})
                    message = f"{message} {_format_leave_quota(leave_quota)}"

            return message
        except Exception as e:
            last_error = e
            if attempt < _MAX_ERP_ATTEMPTS:
                await asyncio.sleep(min(1.5 * (2 ** (attempt - 1)), 10.0))
        finally:
            # Each query is simulated as an independent fresh turn — don't
            # leave a half-filled apply_leave draft sitting in Redis under
            # this conversation_id for the next attempt/run to trip over.
            hr_graph.leave_slot_service.clear_slots(account["company_id"], conversation_id)

    return f"(error generating response after {_MAX_ERP_ATTEMPTS} attempts: {last_error})"


async def _fetch_all_responses(results: list, account: dict) -> None:
    """Populates result['response'] in place.

    Deliberately SEQUENTIAL, not concurrent — two independent reasons:
    (1) an earlier version of this script mocked erp_client's methods via
    patch.object, which mutates the shared module rather than a per-task
    copy; running ~114 of those concurrently let one coroutine's __exit__
    restore the attribute out from under another still mid-await, and that
    race is exactly what corrupted a prior run's real OpenAI calls into
    timeouts. (2) now that every query hits the REAL erp-api dev server
    (`php artisan serve`, effectively single-threaded), firing requests at
    it concurrently would just queue or intermittently fail rather than
    actually go faster."""
    total = len(results)
    for i, r in enumerate(results):
        intent = r["raw_actual_intent"]
        r["response"] = await _fetch_one_response(r["query"], intent, i, account)
        if r["raw_actual_intent"] in _LEAVE_INTENTS:
            # Small pacing gap between real erp-api hits — the dev server
            # handles one request at a time; back-to-back real requests over
            # a sustained run are what triggered the dropped-connection
            # failures the retry logic above exists to recover from.
            await asyncio.sleep(0.15)
        if (i + 1) % 20 == 0 or (i + 1) == total:
            print(f"  ...{i + 1}/{total} responses fetched")


# ---------------------------------------------------------------------------
# Excel report generation
# ---------------------------------------------------------------------------

HEADER_FILL = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid")
HEADER_FONT = Font(color="FFFFFF", bold=True)
PASS_FILL = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
PASS_FONT = Font(color="006100")
FAIL_FILL = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
FAIL_FONT = Font(color="9C0006", bold=True)
THIN_BORDER = Border(*([Side(style="thin", color="D9D9D9")] * 4))


def _style_header_row(ws, row_idx, num_cols):
    for col in range(1, num_cols + 1):
        cell = ws.cell(row=row_idx, column=col)
        cell.fill = HEADER_FILL
        cell.font = HEADER_FONT
        cell.alignment = Alignment(vertical="center", wrap_text=True)
        cell.border = THIN_BORDER


def _autofit(ws, widths):
    for i, w in enumerate(widths, start=1):
        ws.column_dimensions[get_column_letter(i)].width = w


def build_report(results, out_path):
    wb = Workbook()

    # --- Summary sheet -----------------------------------------------------
    summary = wb.active
    summary.title = "Summary"
    summary["A1"] = "Leave AI Feature — Multi-Prompt Test Report"
    summary["A1"].font = Font(size=14, bold=True)
    summary["A2"] = f"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    summary["A2"].font = Font(italic=True, color="666666")
    summary["A3"] = (
        "Pass/Fail is decided by services.nlp_service.fast_classify() alone. "
        "The Response column additionally runs the real leave_action_node "
        "end-to-end against a REAL logged-in erp-api employee account — real "
        "leave balance figures, real leave requests — not fixture data "
        "(apply_leave's first turn also makes a real OpenAI call, same as "
        "production) — see the script's module docstring for scope."
    )
    summary["A3"].font = Font(italic=True, color="666666", size=9)
    summary.merge_cells("A3:F3")
    summary.row_dimensions[3].height = 24
    summary["A3"].alignment = Alignment(wrap_text=True, vertical="top")

    headers = ["Category", "Total", "Passed", "Failed", "Pass Rate"]
    header_row = 5
    for c, h in enumerate(headers, start=1):
        summary.cell(row=header_row, column=c, value=h)
    _style_header_row(summary, header_row, len(headers))

    by_category = {}
    for r in results:
        by_category.setdefault(r["category"], []).append(r)

    row = header_row + 1
    total_all = passed_all = 0
    for category, _, _ in CATEGORIES:
        rows = by_category.get(category, [])
        total = len(rows)
        passed = sum(1 for r in rows if r["passed"])
        failed = total - passed
        total_all += total
        passed_all += passed
        rate = f"{(passed / total * 100):.0f}%" if total else "n/a"

        summary.cell(row=row, column=1, value=category)
        summary.cell(row=row, column=2, value=total)
        summary.cell(row=row, column=3, value=passed)
        summary.cell(row=row, column=4, value=failed)
        rate_cell = summary.cell(row=row, column=5, value=rate)
        for col in range(1, 6):
            summary.cell(row=row, column=col).border = THIN_BORDER
        if failed > 0:
            rate_cell.fill = FAIL_FILL
            rate_cell.font = FAIL_FONT
        else:
            rate_cell.fill = PASS_FILL
            rate_cell.font = PASS_FONT
        row += 1

    row += 1
    summary.cell(row=row, column=1, value="TOTAL").font = Font(bold=True)
    summary.cell(row=row, column=2, value=total_all).font = Font(bold=True)
    summary.cell(row=row, column=3, value=passed_all).font = Font(bold=True)
    summary.cell(row=row, column=4, value=total_all - passed_all).font = Font(bold=True)
    overall_rate = f"{(passed_all / total_all * 100):.1f}%" if total_all else "n/a"
    summary.cell(row=row, column=5, value=overall_rate).font = Font(bold=True)

    _autofit(summary, [30, 10, 10, 10, 12])

    # --- All Results sheet (every case, one row each) -----------------------
    detail = wb.create_sheet("All Results")
    headers = ["#", "Category", "Query", "Expected Intent", "Actual Intent",
               "Is HR?", "Confidence", "Result", "Bot Response"]
    for c, h in enumerate(headers, start=1):
        detail.cell(row=1, column=c, value=h)
    _style_header_row(detail, 1, len(headers))

    for i, r in enumerate(results, start=1):
        row = i + 1
        values = [
            i, r["category"], r["query"], r["expected"], r["actual"],
            "Yes" if r["is_hr"] else "No", r["confidence"],
            "PASS" if r["passed"] else "FAIL", r.get("response", ""),
        ]
        for c, v in enumerate(values, start=1):
            cell = detail.cell(row=row, column=c, value=v)
            cell.border = THIN_BORDER
            if c in (3, 9):
                cell.alignment = Alignment(wrap_text=True)
        result_cell = detail.cell(row=row, column=8)
        if r["passed"]:
            result_cell.fill = PASS_FILL
            result_cell.font = PASS_FONT
        else:
            result_cell.fill = FAIL_FILL
            result_cell.font = FAIL_FONT

    detail.freeze_panes = "A2"
    detail.auto_filter.ref = f"A1:I{len(results) + 1}"
    _autofit(detail, [5, 22, 45, 30, 20, 8, 11, 9, 55])

    # --- One sheet per category ---------------------------------------------
    for category, _, _ in CATEGORIES:
        rows = by_category.get(category, [])
        sheet_name = category[:31]
        ws = wb.create_sheet(sheet_name)
        for c, h in enumerate(headers[1:], start=1):
            ws.cell(row=1, column=c, value=h)
        _style_header_row(ws, 1, len(headers) - 1)
        for i, r in enumerate(rows, start=2):
            values = [
                r["category"], r["query"], r["expected"], r["actual"],
                "Yes" if r["is_hr"] else "No", r["confidence"],
                "PASS" if r["passed"] else "FAIL", r.get("response", ""),
            ]
            for c, v in enumerate(values, start=1):
                cell = ws.cell(row=i, column=c, value=v)
                cell.border = THIN_BORDER
                if c in (2, 8):
                    cell.alignment = Alignment(wrap_text=True)
            result_cell = ws.cell(row=i, column=7)
            if r["passed"]:
                result_cell.fill = PASS_FILL
                result_cell.font = PASS_FONT
            else:
                result_cell.fill = FAIL_FILL
                result_cell.font = FAIL_FONT
        ws.freeze_panes = "A2"
        ws.auto_filter.ref = f"A1:H{len(rows) + 1}"
        _autofit(ws, [22, 45, 30, 20, 8, 11, 9, 55])

    # --- Failures Only sheet -------------------------------------------------
    failures = [r for r in results if not r["passed"]]
    fws = wb.create_sheet("Failures Only")
    for c, h in enumerate(headers, start=1):
        fws.cell(row=1, column=c, value=h)
    _style_header_row(fws, 1, len(headers))
    if failures:
        for i, r in enumerate(failures, start=1):
            row = i + 1
            values = [
                i, r["category"], r["query"], r["expected"], r["actual"],
                "Yes" if r["is_hr"] else "No", r["confidence"], "FAIL", r.get("response", ""),
            ]
            for c, v in enumerate(values, start=1):
                cell = fws.cell(row=row, column=c, value=v)
                cell.border = THIN_BORDER
                if c in (3, 9):
                    cell.alignment = Alignment(wrap_text=True)
            fws.cell(row=row, column=8).fill = FAIL_FILL
            fws.cell(row=row, column=8).font = FAIL_FONT
    else:
        fws.cell(row=2, column=1, value="No failures — all test cases passed.").font = Font(
            bold=True, color="006100")
    fws.freeze_panes = "A2"
    _autofit(fws, [5, 22, 45, 30, 20, 8, 11, 9, 55])

    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    wb.save(out_path)


async def _run_with_real_account(results: list) -> None:
    email = os.getenv("REPORT_TEST_USER_EMAIL")
    password = os.getenv("REPORT_TEST_USER_PASSWORD")
    if not email or not password:
        raise RuntimeError(
            "REPORT_TEST_USER_EMAIL and REPORT_TEST_USER_PASSWORD must be set — "
            "this report logs into a real erp-api employee account to fetch real "
            "leave data. See the module docstring for what's required."
        )
    erp_api_url = os.getenv("REPORT_ERP_API_URL") or hr_graph.erp_client.ERP_API_URL

    print(f"Logging into erp-api at {erp_api_url} as {email}...")
    account = await _login_real_account(erp_api_url, email, password)
    print(f"  Logged in — user_id={account['user_id']} company_id={account['company_id']}")

    print("Fetching bot responses (real leave_action_node against real erp-api data; "
          "apply_leave queries also make a real OpenAI call)...")
    with patch.object(hr_graph.erp_client, "ERP_API_URL", erp_api_url):
        await _fetch_all_responses(results, account)


def main():
    results = run_sweep()

    asyncio.run(_run_with_real_account(results))

    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    out_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "reports")
    out_path = os.path.join(out_dir, f"leave_ai_test_report_{timestamp}.xlsx")
    build_report(results, out_path)

    total = len(results)
    passed = sum(1 for r in results if r["passed"])
    print(f"\n{'='*70}")
    print(f"Leave AI multi-prompt test sweep — {total} queries")
    print(f"{'='*70}")
    for category, _, _ in CATEGORIES:
        rows = [r for r in results if r["category"] == category]
        p = sum(1 for r in rows if r["passed"])
        print(f"  {category:32} {p:3}/{len(rows):<3} passed")
    print(f"{'-'*70}")
    print(f"  {'TOTAL':32} {passed:3}/{total:<3} passed ({passed/total*100:.1f}%)")
    print(f"{'='*70}")

    failures = [r for r in results if not r["passed"]]
    if failures:
        print(f"\n{len(failures)} FAILING QUERIES:\n")
        for r in failures:
            print(f"  [{r['category']}] {r['query']!r}")
            print(f"      expected={r['expected']!r}  actual={r['actual']!r}")
    else:
        print("\nNo failures.")

    print(f"\nExcel report written to: {out_path}")
    return out_path


if __name__ == "__main__":
    main()
