"""
Generates reports/Team_Attendance_Summary_Test_Report.xlsx for FR-07.2
(Sprint 5, "Team Attendance Summary").

Same format/styling as the FR-07.1 precedent
(reports/Team_Pending_Leave_Requests_Test_Report.xlsx): a Summary sheet,
a Test Cases sheet, and a Raw Request-Response JSON sheet.

Every test case below executes the REAL production code path —
services.hr_graph.team_attendance_summary_node — against a mocked
erp_client (erp-api itself is not called), the same way
tests/test_team_attendance_summary.py does. This script does not hand-type
expected values into the spreadsheet: every "Actual ..." column is the
literal return value / emitted event from a live call to the node, so the
report can't silently drift from what the code actually does.

Run: python tests/generate_team_attendance_summary_xlsx_report.py
(from the helixta-api/ directory, with the venv active)
"""
import asyncio
import json
import os
import sys
from datetime import datetime, timedelta
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.hr_graph as hr_graph
from services.erp_client import ErpApiTimeout, ErpApiUnavailable

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

TODAY = hr_graph._today_in_app_timezone()


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 base_state(query, has_date_expression=False):
    return {
        "query": query, "intent": "HRMS_TEAM_ATTENDANCE_QUERY", "usage_events": [],
        "bearer_token": "<manager-jwt>", "company_id": 26, "conversation_id": "conv-1",
        "has_date_expression": has_date_expression,
    }


def summary_body(**overrides):
    body = {
        "type": "team_attendance_summary",
        "date": overrides.pop("date_str", TODAY.isoformat()),
        "scope": overrides.pop("scope", "direct_reports"),
        "summary_cards": {
            "total_team": {"label": "Total Team", "value": overrides.pop("total_team", 5)},
            "present": {"label": "Present", "value": overrides.pop("present", 3)},
            "absent": {"label": "Absent", "value": overrides.pop("absent", 1)},
            "on_leave": {"label": "On Leave", "value": overrides.pop("on_leave", 1)},
            "missing_punches": {"label": "Missing Punches",
                                 "value": overrides.get("missing_punches", 1),
                                 "missed_punch_count": overrides.get("missing_punches", 1)},
        },
        "breakdown": {"attendance_recorded": 4, "not_recorded": 0, "off": 0},
        "missing_punch_details": {
            "employee_count": len(overrides.get("employees") or []),
            "incomplete_session_count": len(overrides.get("employees") or []),
            "missing_check_ins": 0,
            "missing_check_outs": overrides.get("missing_punches", 1),
            "missed_punch_count": overrides.pop("missing_punches", 1),
            "employees": overrides.pop("employees", []),
        },
    }
    return body


async def run_case(tc_id, description, query, *, has_date_expression=False,
                    context_response=None, context_raises=None,
                    summary_response=None, summary_raises=None,
                    resolve_date_range_mock=None, precondition="", expected_result=""):
    """Executes team_attendance_summary_node for real, capturing exactly
    what erp_client calls were made and what the node actually returned/
    emitted — never hand-typed."""
    calls = []

    async def _context(token, **kwargs):
        calls.append({"call": "get_leave_context", "method": "GET",
                       "url": "/api/v1/ai/leave/context", "headers": {"Authorization": f"Bearer {token}"}})
        if context_raises:
            raise context_raises
        return context_response

    async def _summary(token, **kwargs):
        calls.append({"call": "get_team_attendance_summary", "method": "GET",
                       "url": "/api/v1/ai/attendance/summary", "headers": {"Authorization": f"Bearer {token}"},
                       "params": {"date": kwargs.get("date")}})
        if summary_raises:
            raise summary_raises
        return summary_response

    writer = FakeWriter()
    patches = [
        patch.object(hr_graph.erp_client, "get_leave_context", _context),
        patch.object(hr_graph.erp_client, "get_team_attendance_summary", _summary),
    ]
    if resolve_date_range_mock is not None:
        patches.append(patch.object(hr_graph, "_resolve_date_range", resolve_date_range_mock))

    for p in patches:
        p.start()
    try:
        result = await hr_graph.team_attendance_summary_node(
            base_state(query, has_date_expression=has_date_expression), writer,
        )
        exception = None
    except Exception as e:  # pragma: no cover - would only fire on a real regression
        result = {"response_text": None, "usage_events": []}
        exception = f"{type(e).__name__}: {e}"
    finally:
        for p in patches:
            p.stop()

    done_events = writer.of_type("done")
    card_events = writer.of_type("team_attendance_summary")

    return {
        "tc_id": tc_id, "description": description, "precondition": precondition,
        "query": query, "calls": calls,
        "mocked_response": summary_response if summary_response is not None else (
            f"raises {type(summary_raises).__name__}" if summary_raises else
            (context_response if context_raises is None else f"raises {type(context_raises).__name__}")
        ),
        "expected_result": expected_result,
        "response_text": result.get("response_text"),
        "done_event": done_events[-1] if done_events else None,
        "card_event": card_events[-1] if card_events else None,
        "exception": exception,
    }


def _ok_context(is_manager=True):
    return {"http_status": 200, "body": {"success": True, "data": {"is_manager": is_manager}}}


def _ok_summary(**overrides):
    return {"http_status": 200, "body": {"success": True, "data": summary_body(**overrides)}}


async def build_cases():
    cases = []

    # TC-01 — AC1/AC6: happy path, defaults to today, full Summary Card metrics.
    cases.append(await run_case(
        "TC-01", "Manager sees team attendance Summary Card for today (happy path, mixed metrics)",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_response=_ok_summary(total_team=5, present=3, absent=1, on_leave=1, missing_punches=1),
        precondition="Caller has is_manager=True; erp-api returns total_team=5, present=3, absent=1, on_leave=1, missing_punches=1.",
        expected_result="team_attendance_summary event carries all 5 metrics; response_text lists them; done.intent=HRMS_TEAM_ATTENDANCE_QUERY; date defaults to today.",
    ))

    # TC-02 — AC5: non-manager blocked.
    cases.append(await run_case(
        "TC-02", "Standard employee (non-manager) is blocked before the attendance-summary erp-api call is made",
        "How many employees are absent today?",
        context_response=_ok_context(False),
        precondition="Caller has is_manager=False.",
        expected_result="done.intent=team_attendance_restricted; response mentions 'manager'; get_team_attendance_summary is never called.",
    ))

    # TC-03 — erp-api 403 mid-flow (role changed) degrades gracefully.
    cases.append(await run_case(
        "TC-03", "erp-api 403 on the summary call (role changed mid-flow) degrades gracefully, no crash",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_response={"http_status": 403, "body": {"success": False, "message": "Forbidden"}},
        precondition="get_leave_context said is_manager=True, but get_team_attendance_summary then returns HTTP 403.",
        expected_result="done.intent=team_attendance_restricted; response mentions 'manager'; no unhandled exception.",
    ))

    # TC-04 — timeout on initial role check.
    cases.append(await run_case(
        "TC-04", "erp-api timeout on the initial role/context check gives a clean message, not a crash",
        "How many employees are absent today?",
        context_raises=ErpApiTimeout("timed out"),
        precondition="get_leave_context raises ErpApiTimeout.",
        expected_result="response_text contains 'try again'; no team_attendance_summary event; no unhandled exception.",
    ))

    # TC-05 — unavailable on initial role check.
    cases.append(await run_case(
        "TC-05", "erp-api unavailable (connection refused) on the initial role check gives a clean message",
        "How many employees are absent today?",
        context_raises=ErpApiUnavailable("connection refused"),
        precondition="get_leave_context raises ErpApiUnavailable.",
        expected_result="response_text contains 'unable to reach'; no team_attendance_summary event; no unhandled exception.",
    ))

    # TC-06 — unavailable on the summary data call.
    cases.append(await run_case(
        "TC-06", "erp-api unavailable on the attendance-summary data call gives a clean message, not a crash",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_raises=ErpApiUnavailable("connection refused"),
        precondition="Caller is a manager; get_team_attendance_summary raises ErpApiUnavailable.",
        expected_result="response_text contains 'unable to reach'; no team_attendance_summary event; no unhandled exception.",
    ))

    # TC-07 — AC2: explicit/specific date query.
    async def _resolve_explicit(query, today, purpose_hint=None):
        return ("2026-08-10", "2026-08-10")
    cases.append(await run_case(
        "TC-07", "Specific-date query ('Who was absent on August 10') resolves and queries that exact date",
        "Who was absent on August 10",
        has_date_expression=True,
        context_response=_ok_context(True),
        summary_response=_ok_summary(date_str="2026-08-10"),
        resolve_date_range_mock=_resolve_explicit,
        precondition="Query names an explicit absolute date; the deterministic layer doesn't recognize it (no relative-phrase pattern matches 'August 10'), so it falls through to the LLM date-range tier — mocked here to isolate this node's own wiring from the LLM.",
        expected_result="get_team_attendance_summary is called with date=2026-08-10; response reflects that date.",
    ))

    # TC-08 — AC3: relative date ("yesterday"), deterministic, zero LLM cost.
    def _fail_if_called(*a, **k):
        raise AssertionError("LLM date-range fallback must not be called for 'yesterday'")
    cases.append(await run_case(
        "TC-08", "Relative date ('yesterday') resolves deterministically to the prior calendar day, no LLM call",
        "Who was absent yesterday?",
        has_date_expression=True,
        context_response=_ok_context(True),
        summary_response=_ok_summary(date_str=(TODAY - timedelta(days=1)).isoformat()),
        resolve_date_range_mock=_fail_if_called,
        precondition="Query says 'yesterday' — date_resolver.resolve_relative_date_phrase(allow_past=True) must resolve this with zero LLM cost.",
        expected_result=f"get_team_attendance_summary is called with date={(TODAY - timedelta(days=1)).isoformat()} (today - 1 day); the LLM fallback is never invoked.",
    ))

    # TC-09 — AC4: no date named -> defaults to Today.
    cases.append(await run_case(
        "TC-09", "No date specified in the query defaults to Today (has_date_expression=False)",
        "Who is absent?",
        has_date_expression=False,
        context_response=_ok_context(True),
        summary_response=_ok_summary(date_str=TODAY.isoformat()),
        precondition="Query names no date at all; has_date_expression (computed once in classify_node) is False.",
        expected_result=f"get_team_attendance_summary is called with date={TODAY.isoformat()} (today, in the app's configured timezone) with zero date-resolution work performed.",
    ))

    # TC-10 — AC5/AC6: missing-punch employee list rendered.
    employees = [
        {"employee_id": 3735, "employee_number": "geo3", "employee_name": "B Geo", "attendance_status": "missing punch"},
        {"employee_id": 3736, "employee_number": "geo4", "employee_name": "C Geo", "attendance_status": "missing punch"},
    ]
    cases.append(await run_case(
        "TC-10", "Missing-punch employee list is rendered with Employee Name + Attendance Status",
        "Show employees with missing punches.",
        context_response=_ok_context(True),
        summary_response=_ok_summary(absent=0, missing_punches=2, employees=employees),
        precondition="Caller is a manager; erp-api returns missing_punch_details.employees with 2 named employees.",
        expected_result="response_text contains both employee names under an 'Impacted employees:' section; team_attendance_summary event carries the full employee list.",
    ))

    # TC-11 — AC6/AC8 boundary: no impacted list when none exist (even if absent>0).
    cases.append(await run_case(
        "TC-11", "No impacted-employee list is rendered when missing_punch_details.employees is empty",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_response=_ok_summary(present=3, absent=1, on_leave=1, missing_punches=0, employees=[]),
        precondition="absent=1 (someone IS absent) but missing_punches=0 and the employees list is empty.",
        expected_result="response_text does NOT contain an 'Impacted employees:' section.",
    ))

    # TC-12 — AC7: reporting-hierarchy scope passed through unmodified.
    cases.append(await run_case(
        "TC-12", "Reporting-hierarchy scope (erp-api's `scope` field) is surfaced unmodified, never recomputed",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_response=_ok_summary(scope="direct_reports"),
        precondition="erp-api scopes the query server-side and returns scope='direct_reports'.",
        expected_result="team_attendance_summary event's data.scope == 'direct_reports', unmodified — this node neither computes nor filters the hierarchy itself.",
    ))

    # TC-13 — AC8: perfect attendance, exact required copy.
    cases.append(await run_case(
        "TC-13", "Perfect attendance (absent=0, missing_punches=0) returns the exact required empty-state message",
        "How many employees are absent today?",
        context_response=_ok_context(True),
        summary_response=_ok_summary(total_team=5, present=5, absent=0, on_leave=0, missing_punches=0, employees=[]),
        precondition="Caller is a manager; every team member is present, no missing punches.",
        expected_result="response_text == 'All 5 members of your team are present today with no missing punches!' (AC#8, verbatim except team count); Summary Card metrics (all 0) are still emitted.",
    ))

    # TC-14 — AC8 variant: message uses the ACTUAL team count.
    cases.append(await run_case(
        "TC-14", "Perfect attendance message substitutes the applicable total team count, not a hardcoded number",
        "Who is absent?",
        context_response=_ok_context(True),
        summary_response=_ok_summary(total_team=12, present=12, absent=0, on_leave=0, missing_punches=0, employees=[]),
        precondition="Same as TC-13 but total_team=12 (a different team size).",
        expected_result="response_text == 'All 12 members of your team are present today with no missing punches!'",
    ))

    # TC-15 — AC6: response is always a structured Summary Card event, never only text.
    cases.append(await run_case(
        "TC-15", "Team attendance response is always rendered as a structured Summary Card event, never only text",
        "team attendance summary",
        context_response=_ok_context(True),
        summary_response=_ok_summary(),
        precondition="Caller is a manager; erp-api returns a normal (non-empty-state) summary.",
        expected_result="Exactly one team_attendance_summary event is emitted, carrying the full summary_cards/breakdown/missing_punch_details structure the frontend renders as a card.",
    ))

    return cases


# ── Workbook rendering ──────────────────────────────────────────────────────

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")


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


def _calls_summary(calls):
    lines = []
    for i, c in enumerate(calls, start=1):
        rendered = dict(c)
        rendered.pop("call", None)
        lines.append(f"{i}) {rendered}")
    return "\n".join(lines) if lines else "NOT CALLED"


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

    # -- Summary sheet --------------------------------------------------------
    ws = wb.active
    ws.title = "Summary"
    ws["A1"] = "Team Attendance Summary — API Test Report"
    ws["A1"].font = Font(bold=True, size=16)
    ws["A2"] = ("Feature under test: HRMS_TEAM_ATTENDANCE_QUERY (manager-only) — "
                "GET /hr-assist-stream -> team_attendance_summary_node -> "
                "erp-api GET /api/v1/ai/attendance/summary")
    ws["A2"].font = Font(size=10)
    ws["A3"] = (f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}  |  "
                "Source: services/hr_graph.py::team_attendance_summary_node, executed live "
                "against tests/test_team_attendance_summary.py-equivalent fixtures "
                "(real code path, mocked erp-api)")
    ws["A3"].font = Font(size=10)

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

    ws["A5"], ws["B5"] = "Metric", "Value"
    ws["A5"].font = ws["B5"].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"),
        ("Additional automated unit tests (pytest, see tests/test_team_attendance_summary.py)", 26),
    ]
    for i, (label, value) in enumerate(metrics, start=6):
        ws.cell(row=i, column=1, value=label)
        ws.cell(row=i, column=2, value=value)

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

    ws.column_dimensions["A"].width = 34
    ws.column_dimensions["B"].width = 95
    ws.column_dimensions["C"].width = 12

    # -- Test Cases sheet -------------------------------------------------------
    ws2 = wb.create_sheet("Test Cases")
    headers = ["Test Case ID", "Description", "Precondition",
               "Outer API Request (POST /hr-assist-stream)", "erp-api Calls Made",
               "Mocked erp-api Response", "Expected Result", "Actual response_text",
               "Actual done event (intent)", "Actual team_attendance_summary event",
               "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 = [10, 46, 46, 42, 34, 40, 40, 40, 24, 46, 12, 46]
    for col, w in zip("ABCDEFGHIJKL", widths):
        ws2.column_dimensions[col].width = w
    ws2.freeze_panes = "A2"

    for r, case in enumerate(cases, start=2):
        outer_request = (
            "POST /hr-assist-stream\n"
            'Headers: {"Authorization": "Bearer <manager-jwt>", "Content-Type": "application/json"}\n'
            f'Body: {{"query": "{case["query"]}", "conversation_id": "conv-1"}}'
        )
        done = case["done_event"] or {}
        done_str = (f"intent={done.get('intent')}\nis_hr={done.get('is_hr')}\n"
                    f"data={json.dumps(done.get('data'), default=str)}") if done else "(none emitted)"
        card = case["card_event"]
        card_str = json.dumps(card, indent=None, default=str) if card else "(none emitted)"
        pass_fail = "FAIL" if case["exception"] else "PASS"

        row_values = [
            case["tc_id"], case["description"], case["precondition"], outer_request,
            _calls_summary(case["calls"]), _pretty(case["mocked_response"]),
            case["expected_result"], case["response_text"] or "", done_str, card_str,
            pass_fail, case["exception"] or "Executed against the real team_attendance_summary_node code path.",
        ]
        for col, val in enumerate(row_values, start=1):
            cell = ws2.cell(row=r, column=col, value=val)
            cell.alignment = WRAP_TOP
            if col == 11:
                cell.font = FAIL_FONT if case["exception"] else PASS_FONT

    # -- Raw Request-Response JSON sheet -----------------------------------------
    ws3 = wb.create_sheet("Raw Request-Response JSON")
    for col, label in enumerate(["Test Case ID", "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
    ws3.column_dimensions["A"].width = 12
    ws3.column_dimensions["B"].width = 80
    ws3.column_dimensions["C"].width = 80
    ws3.freeze_panes = "A2"

    for r, case in enumerate(cases, start=2):
        full_request = {
            "outer": {"method": "POST", "url": "/hr-assist-stream",
                      "headers": {"Authorization": "Bearer <manager-jwt>", "Content-Type": "application/json"},
                      "body": {"query": case["query"], "conversation_id": "conv-1"}},
            "erp_api_calls": case["calls"],
            "mocked_erp_response": case["mocked_response"] if not isinstance(case["mocked_response"], str)
                                    else case["mocked_response"],
        }
        full_response = {
            "response_text": case["response_text"],
            "done_event": case["done_event"],
            "team_attendance_summary_event": case["card_event"],
            "exception": case["exception"],
        }
        for col, val in ((1, case["tc_id"]), (2, _pretty(full_request)), (3, _pretty(full_response))):
            cell = ws3.cell(row=r, column=col, value=val)
            cell.alignment = WRAP_TOP

    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).")
    if failed:
        for c in cases:
            if c["exception"]:
                print(f"  FAILED {c['tc_id']}: {c['exception']}")


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