"""
Runs tests/test_hr_leave_query_cases.py (HR / non-HR query classification +
Apply Leave / Get Leave Status / Get Leave Balance action tests) and writes a
formatted Excel report of the results.

Fully self-contained and deterministic: every external call (erp-api HTTP
calls, the LLM slot-extraction/classification calls) is mocked inside the
test file itself, so this needs no live credentials, network access, or
running erp-api instance — unlike tests/multi_prompt_report.py, which drives
the same kind of scenarios against a real logged-in account.

Run:    python tests/generate_hr_leave_xlsx_report.py
Writes: <repo>/reports/hr_leave_unit_test_report_<timestamp>.xlsx
"""

import datetime
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

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

REPO_ROOT = Path(__file__).resolve().parent.parent
TEST_FILE = "tests/test_hr_leave_query_cases.py"
JUNIT_XML = REPO_ROOT / "hr_leave_test_report.xml"

# ── Styling (matches the project's existing report scripts) ─────────────────
HEADER_FILL = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid")
HEADER_FONT = Font(color="FFFFFF", bold=True)
SECTION_FILL = PatternFill(start_color="2E75B6", end_color="2E75B6", fill_type="solid")
SECTION_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))

# Section (test class) → human-readable category + short description used on
# the Summary sheet. Falls back to the raw class name if a new class is added
# without updating this map.
CATEGORY_INFO = {
    "TestHRRelatedQueriesFastClassify": (
        "HR Queries — Keyword Classifier",
        "fast_classify() correctly recognizes HR-related queries across every supported category (leave, payroll, salary, benefits, recruitment, attendance, performance, training, compliance, onboarding, etc.) and flags them is_hr=True.",
    ),
    "TestHRRelatedQueriesClassifyNode": (
        "HR Queries — LLM Fallback Classifier",
        "For phrasing fast_classify can't confidently keyword-match, classify_node's LLM-backed fallback (mocked) still routes the result through correctly with is_hr=True.",
    ),
    "TestNonHRRelatedQueriesFastClassify": (
        "Non-HR Queries — Keyword Classifier",
        "fast_classify() correctly flags code requests as non_hr, greetings/small-talk as is_hr=False, and returns a deliberate 'no opinion' (confidence 0.0) for pure general-knowledge trivia rather than guessing.",
    ),
    "TestNonHRRelatedQueriesClassifyNode": (
        "Non-HR Queries — LLM Fallback & Guardrail",
        "General-knowledge queries are classified non_hr via the mocked LLM fallback, and harmful/prompt-injection queries are blocked by the custom guardrail before any LLM call is made.",
    ),
    "TestApplyLeaveAction": (
        "Apply Leave",
        "leave_action_node's apply-leave conversation: access check, slot collection, single/multi-day requests, insufficient/zero balance denial, unrecognized leave type, and confirm/cancel submission.",
    ),
    "TestGetLeaveStatusAction": (
        "Get Leave Status",
        "leave_action_node's leave-status branch: access check, single/multiple results, empty result messaging, status-word filtering, and ERP timeout handling.",
    ),
    "TestGetLeaveBalanceAction": (
        "Get Leave Balance",
        "leave_action_node's leave-balance branch: access check, full breakdown, single/multiple named-type filtering, zero-balance reporting, and ERP unavailability handling.",
    ),
}

CATEGORY_ORDER = list(CATEGORY_INFO.keys())


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 _friendly_name(raw_name: str) -> str:
    return raw_name.replace("test_", "").replace("_", " ").strip().capitalize()


def run_pytest() -> None:
    print(f"Running pytest on {TEST_FILE} ...")
    result = subprocess.run(
        [sys.executable, "-m", "pytest", TEST_FILE, "-v", f"--junit-xml={JUNIT_XML}"],
        cwd=REPO_ROOT,
    )
    if result.returncode not in (0, 1):
        # 0 = all passed, 1 = some tests failed (still produces a valid report).
        raise RuntimeError(f"pytest exited unexpectedly with code {result.returncode}")


def parse_results() -> list:
    tree = ET.parse(JUNIT_XML)
    root = tree.getroot()
    suites = root.findall(".//testsuite") or [root]

    results = []
    for suite in suites:
        for tc in suite.findall("testcase"):
            class_name = tc.get("classname", "")
            section = class_name.split(".")[-1] if class_name else "Unknown"
            raw_name = tc.get("name", "")
            duration = float(tc.get("time", "0"))

            failure = tc.find("failure")
            error = tc.find("error")
            if failure is not None:
                status = "FAIL"
                message = (failure.get("message") or failure.text or "").strip()[:400]
            elif error is not None:
                status = "ERROR"
                message = (error.get("message") or error.text or "").strip()[:400]
            else:
                status = "PASS"
                message = ""

            results.append({
                "section": section,
                "raw_name": raw_name,
                "name": _friendly_name(raw_name),
                "status": status,
                "duration": duration,
                "message": message,
            })
    return results


def build_report(results: list, out_path: Path) -> None:
    wb = Workbook()

    total = len(results)
    passed = sum(1 for r in results if r["status"] == "PASS")
    failed = total - passed

    by_section: dict = {}
    for r in results:
        by_section.setdefault(r["section"], []).append(r)

    # ── Sheet 1: Summary ──────────────────────────────────────────────────
    summary = wb.active
    summary.title = "Summary"
    summary.sheet_view.showGridLines = False

    summary.merge_cells("A1:E1")
    title_cell = summary["A1"]
    title_cell.value = "Unit Test Report — HR / Non-HR Query Classification & Leave Actions"
    title_cell.font = Font(bold=True, size=14, color="FFFFFF")
    title_cell.fill = HEADER_FILL
    title_cell.alignment = Alignment(horizontal="center", vertical="center")
    summary.row_dimensions[1].height = 28

    meta = [
        ("Test File", TEST_FILE),
        ("Generated", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
        ("Total Tests", total),
        ("Passed", passed),
        ("Failed", failed),
        ("Pass Rate", f"{(passed / total * 100):.1f}%" if total else "n/a"),
    ]
    for i, (k, v) in enumerate(meta, start=2):
        ka = summary.cell(row=i, column=1, value=k)
        ka.font = Font(bold=True, color="FFFFFF")
        ka.fill = SECTION_FILL
        ka.border = THIN_BORDER
        va = summary.cell(row=i, column=2, value=v)
        va.border = THIN_BORDER
        if k == "Passed":
            va.fill, va.font = PASS_FILL, Font(bold=True)
        elif k == "Failed" and failed > 0:
            va.fill, va.font = FAIL_FILL, Font(bold=True)
    _autofit(summary, [16, 55])

    header_row = len(meta) + 4
    headers = ["Category", "Description", "Total", "Passed", "Failed", "Pass Rate"]
    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))

    row = header_row + 1
    for section in CATEGORY_ORDER:
        rows = by_section.get(section, [])
        label, desc = CATEGORY_INFO.get(section, (section, ""))
        s_total = len(rows)
        s_passed = sum(1 for r in rows if r["status"] == "PASS")
        s_failed = s_total - s_passed
        rate = f"{(s_passed / s_total * 100):.0f}%" if s_total else "n/a"

        summary.cell(row=row, column=1, value=label).font = Font(bold=True)
        desc_cell = summary.cell(row=row, column=2, value=desc)
        desc_cell.alignment = Alignment(wrap_text=True, vertical="top")
        summary.cell(row=row, column=3, value=s_total)
        summary.cell(row=row, column=4, value=s_passed)
        summary.cell(row=row, column=5, value=s_failed)
        rate_cell = summary.cell(row=row, column=6, value=rate)
        for col in range(1, 7):
            summary.cell(row=row, column=col).border = THIN_BORDER
        rate_cell.fill, rate_cell.font = (FAIL_FILL, FAIL_FONT) if s_failed else (PASS_FILL, PASS_FONT)
        summary.row_dimensions[row].height = 40
        row += 1

    summary.column_dimensions["B"].width = 90
    for col_letter, w in zip("ACDEF", [30, 8, 8, 8, 10]):
        summary.column_dimensions[col_letter].width = w

    # ── Sheet 2: All Results ─────────────────────────────────────────────
    detail = wb.create_sheet("All Results")
    detail.sheet_view.showGridLines = False
    headers = ["#", "Category", "Test Case", "Status", "Duration (s)", "Failure Message"]
    for c, h in enumerate(headers, start=1):
        detail.cell(row=1, column=c, value=h)
    _style_header_row(detail, 1, len(headers))
    detail.freeze_panes = "A2"

    row = 2
    num = 0
    for section in CATEGORY_ORDER:
        rows = by_section.get(section, [])
        if not rows:
            continue
        label, _ = CATEGORY_INFO.get(section, (section, ""))
        detail.merge_cells(start_row=row, start_column=1, end_row=row, end_column=len(headers))
        sec_cell = detail.cell(row=row, column=1, value=f"  {label}")
        sec_cell.fill, sec_cell.font = SECTION_FILL, SECTION_FONT
        for c in range(1, len(headers) + 1):
            detail.cell(row=row, column=c).border = THIN_BORDER
        row += 1

        for r in rows:
            num += 1
            values = [num, label, r["name"], r["status"], round(r["duration"], 4), r["message"] or "—"]
            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, 6):
                    cell.alignment = Alignment(wrap_text=True)
            status_cell = detail.cell(row=row, column=4)
            status_cell.fill, status_cell.font = (
                (PASS_FILL, PASS_FONT) if r["status"] == "PASS" else (FAIL_FILL, FAIL_FONT)
            )
            row += 1

    detail.auto_filter.ref = f"A1:F{row - 1}"
    _autofit(detail, [5, 32, 55, 10, 12, 55])

    # ── Sheet 3: Failures Only ───────────────────────────────────────────
    failures = [r for r in results if r["status"] != "PASS"]
    fws = wb.create_sheet("Failures Only")
    fws.sheet_view.showGridLines = False
    for c, h in enumerate(["#", "Category", "Test Case", "Status", "Failure Message"], start=1):
        fws.cell(row=1, column=c, value=h)
    _style_header_row(fws, 1, 5)
    if failures:
        for i, r in enumerate(failures, start=1):
            label, _ = CATEGORY_INFO.get(r["section"], (r["section"], ""))
            values = [i, label, r["name"], r["status"], r["message"]]
            for c, v in enumerate(values, start=1):
                cell = fws.cell(row=i + 1, column=c, value=v)
                cell.border = THIN_BORDER
                if c == 5:
                    cell.alignment = Alignment(wrap_text=True)
            fws.cell(row=i + 1, column=4).fill = FAIL_FILL
            fws.cell(row=i + 1, column=4).font = FAIL_FONT
    else:
        fws.cell(row=2, column=1, value="No failures — all test cases passed.").font = Font(bold=True, color="006100")
    _autofit(fws, [5, 32, 55, 10, 60])

    out_path.parent.mkdir(parents=True, exist_ok=True)
    wb.save(out_path)


def main():
    run_pytest()
    results = parse_results()

    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    out_path = REPO_ROOT / "reports" / f"hr_leave_unit_test_report_{timestamp}.xlsx"
    build_report(results, out_path)

    total = len(results)
    passed = sum(1 for r in results if r["status"] == "PASS")
    print(f"\n{'=' * 70}")
    print(f"HR / Non-HR & Leave Action unit tests — {total} cases")
    print(f"{'=' * 70}")
    for section in CATEGORY_ORDER:
        rows = [r for r in results if r["section"] == section]
        if not rows:
            continue
        label, _ = CATEGORY_INFO[section]
        p = sum(1 for r in rows if r["status"] == "PASS")
        print(f"  {label:38} {p:3}/{len(rows):<3} passed")
    print(f"{'-' * 70}")
    print(f"  {'TOTAL':38} {passed:3}/{total:<3} passed ({passed / total * 100:.1f}%)")
    print(f"{'=' * 70}")
    print(f"\nExcel report written to: {out_path}")
    return out_path


if __name__ == "__main__":
    main()
