"""
Parses test-report.xml (JUnit format) and writes a formatted Excel workbook.
Run:  python generate_test_report.py
Output: test-report.xlsx
"""

import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path

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

# ── Config ─────────────────────────────────────────────────────────────────
XML_PATH  = Path("test-report.xml")
XLSX_PATH = Path("test-report.xlsx")

PROJECT   = "Helix AI Assistant – Backend"
TICKET    = "HA-26"
AUTHOR    = "Arshad Khan"

# ── Colours ────────────────────────────────────────────────────────────────
C_HEADER_BG  = "1F3864"   # dark navy
C_HEADER_FG  = "FFFFFF"
C_SECTION_BG = "2E75B6"   # mid blue (section rows)
C_SECTION_FG = "FFFFFF"
C_PASS_BG    = "E2EFDA"   # light green
C_FAIL_BG    = "FFDDD2"   # light red / salmon
C_SKIP_BG    = "FFF2CC"   # light yellow
C_ALT_BG     = "F5F8FF"   # alternating row tint
C_BORDER     = "B8C4D4"

# ── Style helpers ──────────────────────────────────────────────────────────
def _fill(hex_color: str) -> PatternFill:
    return PatternFill("solid", fgColor=hex_color)

def _font(bold=False, color="000000", size=10) -> Font:
    return Font(bold=bold, color=color, size=size, name="Calibri")

def _border() -> Border:
    side = Side(style="thin", color=C_BORDER)
    return Border(left=side, right=side, top=side, bottom=side)

def _align(h="left", v="center", wrap=False) -> Alignment:
    return Alignment(horizontal=h, vertical=v, wrap_text=wrap)

def _hdr_cell(ws, row, col, value, width_hint=None):
    cell = ws.cell(row=row, column=col, value=value)
    cell.fill   = _fill(C_HEADER_BG)
    cell.font   = _font(bold=True, color=C_HEADER_FG, size=10)
    cell.border = _border()
    cell.alignment = _align("center")
    return cell

def _section_cell(ws, row, col, value):
    cell = ws.cell(row=row, column=col, value=value)
    cell.fill   = _fill(C_SECTION_BG)
    cell.font   = _font(bold=True, color=C_SECTION_FG, size=10)
    cell.border = _border()
    cell.alignment = _align("left")
    return cell

def _data_cell(ws, row, col, value, bg=None, bold=False, align="left"):
    cell = ws.cell(row=row, column=col, value=value)
    if bg:
        cell.fill = _fill(bg)
    cell.font   = _font(bold=bold)
    cell.border = _border()
    cell.alignment = _align(align, wrap=True)
    return cell


# ── Parse XML ──────────────────────────────────────────────────────────────

def parse_xml(path: Path) -> dict:
    tree = ET.parse(path)
    root = tree.getroot()

    # JUnit XML may have <testsuites> or directly <testsuite>
    suites = root.findall(".//testsuite") or [root]

    results = []
    for suite in suites:
        for tc in suite.findall("testcase"):
            class_name = tc.get("classname", "")
            # classname looks like "tests.test_api.TestHrAssistStream"
            parts = class_name.split(".")
            section = parts[-1] if parts else class_name

            raw_name = tc.get("name", "")
            # Convert snake_case to readable: test_stream_foo → Stream Foo
            friendly = raw_name.replace("test_", "").replace("_", " ").strip().title()

            duration = float(tc.get("time", "0"))

            failure = tc.find("failure")
            error   = tc.find("error")
            skip    = tc.find("skipped")

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

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

    total    = len(results)
    passed   = sum(1 for r in results if r["status"] == "PASS")
    failed   = sum(1 for r in results if r["status"] == "FAIL")
    errored  = sum(1 for r in results if r["status"] == "ERROR")
    skipped  = sum(1 for r in results if r["status"] == "SKIP")
    duration = sum(r["duration"] for r in results)

    return {
        "results":  results,
        "total":    total,
        "passed":   passed,
        "failed":   failed,
        "errored":  errored,
        "skipped":  skipped,
        "duration": duration,
    }


# ── Human-readable descriptions ────────────────────────────────────────────
# Keyed by the raw pytest test name.

DESCRIPTIONS = {
    # /hr-assist-stream
    "test_stream_existing_conversation_returns_events_in_order":
        "Verify that a full streaming request with an existing conversation_id returns events in the correct order: guardrail → intent → guardrail → chunk → done, with the correct conversation_id and server_ip in the done event.",

    "test_stream_no_conversation_id_creates_new":
        "When conversation_id is omitted the endpoint creates a new conversation automatically and the done SSE event contains the newly generated conversation_id.",

    "test_stream_cache_hit_returns_cached_events":
        "When Redis query cache has a matching entry the endpoint streams the cached answer immediately (no LangGraph / LLM call). The done event must carry cached=true.",

    "test_stream_non_hr_query_sends_redirect_message":
        "A query outside HR scope (e.g. 'weather') is classified as non_hr. The intent event must reflect this and the chunk event must contain the Helix AI redirect message.",

    "test_stream_guardrail_blocked_sends_failed_event":
        "When the input guardrail flags a harmful query a guardrail-failed event is streamed with the flagged categories. No chunk or done events should follow.",

    "test_stream_missing_query_returns_400":
        "A request body without the 'query' field must be rejected with HTTP 400 and an appropriate error message.",

    "test_stream_no_auth_header_returns_401_or_422":
        "A request without any Authorization header must be rejected with HTTP 401 or 422 (FastAPI validation).",

    "test_stream_invalid_jwt_returns_401":
        "A request with a syntactically malformed or unsigned JWT token must be rejected with HTTP 401.",

    "test_stream_writes_ai_message_to_redis_after_done":
        "After the LangGraph stream completes the finally block must call add_ai_message once, writing the assistant reply to Redis so the next turn has full conversation context.",

    "test_stream_populates_query_cache_for_fresh_query":
        "For fresh queries with no prior conversation context, set_cached_query must be called once after the stream finishes so identical future queries are served from cache.",

    # Redis failure scenarios
    "test_redis_write_failure_does_not_crash_stream":
        "When add_user_message raises (Redis unreachable) the exception is caught and logged. The stream must continue and deliver a complete LLM response to the client.",

    "test_redis_read_failure_falls_back_to_db_context":
        "When get_messages raises (Redis unavailable) the exception is caught, context_messages is set to [], and get_context (PostgreSQL) is called as the fallback for conversation history.",

    "test_redis_empty_triggers_db_context_fallback":
        "When Redis returns an empty list (key expired or cold cache) the endpoint must fall back to PostgreSQL via get_context to retrieve prior conversation context.",

    "test_redis_cache_read_failure_treated_as_miss":
        "When get_cached_query raises a Redis error the exception is caught and the request proceeds as a cache miss — LangGraph is called and a fresh LLM response is served.",

    "test_redis_ai_message_write_failure_response_still_returned":
        "When add_ai_message raises inside the finally block (post-stream Redis write) the exception is caught silently. The client has already received a valid done event.",

    "test_redis_cache_write_failure_response_still_returned":
        "When set_cached_query raises (Redis write error during cache population) the exception is caught silently. The SSE response already delivered to the client is unaffected.",

    "test_full_redis_outage_degrades_gracefully":
        "When all Redis operations fail simultaneously (full outage): DB fallback used for context (get_context), DB save executes (save_message), and the client receives a full valid LLM response.",

    "test_redis_failure_never_skips_db_save":
        "Even when Redis fails for both add_ai_message and set_cached_query in the finally block, save_message (PostgreSQL) must still be called exactly once — DB is the source of truth.",

    # /conversations (GET)
    "test_list_returns_conversations_for_company":
        "GET /conversations returns HTTP 200 with success=true, count matching the number of conversations, and a data array containing the expected id and company_id.",

    "test_list_returns_empty_when_no_conversations":
        "When no conversations exist for the company the response must have count=0 and data=[].",

    "test_list_passes_company_id_from_jwt":
        "The service function get_conversations must be called with the company_id decoded from the JWT token — not any hardcoded or client-supplied value.",

    "test_list_no_auth_returns_401_or_422":
        "An unauthenticated GET /conversations request must be rejected with HTTP 401 or 422.",

    "test_list_invalid_jwt_returns_401":
        "GET /conversations with a malformed JWT must return HTTP 401.",

    # /conversations/{id} (DELETE)
    "test_delete_existing_conversation_returns_success":
        "DELETE /conversations/{id} on an existing record returns HTTP 200 with success=true and a message containing the conversation_id.",

    "test_delete_nonexistent_conversation_returns_404":
        "When the DB service returns False (record not found or already deleted) the endpoint must respond with HTTP 404.",

    "test_delete_passes_correct_conversation_id":
        "The conversation_id from the URL path must be forwarded unchanged to the DB service function.",

    "test_delete_delegates_to_soft_delete_service":
        "delete_conversation_from_db must be called exactly once per request. It performs a soft delete (is_deleted=1) — the row is never physically removed.",

    "test_delete_no_auth_returns_401_or_422":
        "An unauthenticated DELETE request must be rejected with HTTP 401 or 422.",

    "test_delete_invalid_jwt_returns_401":
        "DELETE /conversations/{id} with a malformed JWT must return HTTP 401.",
}

# Friendly section labels
SECTION_LABELS = {
    "TestHrAssistStream":    "POST /hr-assist-stream  —  Streaming Endpoint",
    "TestRedisFailure":      "POST /hr-assist-stream  —  Redis Failure / Degradation",
    "TestListConversations": "GET /conversations  —  List Conversations",
    "TestDeleteConversation":"DELETE /conversations/{id}  —  Soft Delete Conversation",
}

# Expected result mapping (what we verify in each test)
EXPECTED = {
    "test_stream_existing_conversation_returns_events_in_order":
        "SSE events: guardrail, intent (leave_policy, is_hr=true), chunk ('Annual leave'), done (cached=false, conversation_id present, server_ip='1.2.3.4')",
    "test_stream_no_conversation_id_creates_new":
        "done event contains conversation_id equal to the newly created conversation UUID",
    "test_stream_cache_hit_returns_cached_events":
        "3 events: intent, chunk ('20 days'), done (cached=true, intent='leave_policy')",
    "test_stream_non_hr_query_sends_redirect_message":
        "intent event: non_hr / is_hr=false. chunk contains 'Helix' or 'HR'",
    "test_stream_guardrail_blocked_sends_failed_event":
        "guardrail event: stage=input, status=failed, categories=['hate']. No chunk events.",
    "test_stream_missing_query_returns_400":
        "HTTP 400, detail contains 'Query required'",
    "test_stream_no_auth_header_returns_401_or_422":
        "HTTP 401 or 422",
    "test_stream_invalid_jwt_returns_401":
        "HTTP 401",
    "test_stream_writes_ai_message_to_redis_after_done":
        "add_ai_message called once with args: (company_id=99, conversation_id=TEST_CONV_ID, text containing 'Annual leave')",
    "test_stream_populates_query_cache_for_fresh_query":
        "set_cached_query called once with payload: {success=true, intent='leave_policy', result containing 'Annual leave'}",

    "test_redis_write_failure_does_not_crash_stream":
        "HTTP 200 SSE stream completes. done event present. chunk text contains 'Annual leave'. No error event.",
    "test_redis_read_failure_falls_back_to_db_context":
        "get_context called once (DB fallback). done event present.",
    "test_redis_empty_triggers_db_context_fallback":
        "get_context called once. done event present.",
    "test_redis_cache_read_failure_treated_as_miss":
        "intent event present (LangGraph ran). done event: cached=false.",
    "test_redis_ai_message_write_failure_response_still_returned":
        "done event present (cached=false). chunk events present. No error event.",
    "test_redis_cache_write_failure_response_still_returned":
        "done event present. chunk events present.",
    "test_full_redis_outage_degrades_gracefully":
        "get_context called once. save_message called once. done event: cached=false. chunk text contains 'Annual leave'.",
    "test_redis_failure_never_skips_db_save":
        "save_message called exactly once despite Redis failures in finally block.",

    "test_list_returns_conversations_for_company":
        "HTTP 200, success=true, count=1, data[0].id=TEST_CONV_ID, data[0].company_id=99",
    "test_list_returns_empty_when_no_conversations":
        "HTTP 200, success=true, count=0, data=[]",
    "test_list_passes_company_id_from_jwt":
        "get_conversations called with company_id=99 (from JWT)",
    "test_list_no_auth_returns_401_or_422":
        "HTTP 401 or 422",
    "test_list_invalid_jwt_returns_401":
        "HTTP 401",

    "test_delete_existing_conversation_returns_success":
        "HTTP 200, success=true, message contains TEST_CONV_ID",
    "test_delete_nonexistent_conversation_returns_404":
        "HTTP 404",
    "test_delete_passes_correct_conversation_id":
        "delete_conversation_from_db called with conversation_id='specific-conv-id-xyz'",
    "test_delete_delegates_to_soft_delete_service":
        "HTTP 200, delete_conversation_from_db called exactly once",
    "test_delete_no_auth_returns_401_or_422":
        "HTTP 401 or 422",
    "test_delete_invalid_jwt_returns_401":
        "HTTP 401",
}

ENDPOINTS = {
    "TestHrAssistStream":     "POST /hr-assist-stream",
    "TestRedisFailure":       "POST /hr-assist-stream",
    "TestListConversations":  "GET /conversations",
    "TestDeleteConversation": "DELETE /conversations/{id}",
}


# ── Build workbook ─────────────────────────────────────────────────────────

def build_excel(data: dict, output: Path):
    wb = openpyxl.Workbook()

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

    # Title block
    ws_sum.merge_cells("A1:F1")
    t = ws_sum["A1"]
    t.value = f"Unit Test Report  —  {PROJECT}"
    t.font  = Font(bold=True, size=14, color=C_HEADER_FG, name="Calibri")
    t.fill  = _fill(C_HEADER_BG)
    t.alignment = _align("center")
    ws_sum.row_dimensions[1].height = 28

    meta = [
        ("Ticket",       TICKET),
        ("Author",       AUTHOR),
        ("Generated",    datetime.now().strftime("%Y-%m-%d  %H:%M")),
        ("Test File",    "tests/test_api.py"),
        ("Framework",    "pytest 9.0.3 + pytest-asyncio 1.3.0"),
        ("Total Tests",  data["total"]),
        ("Passed",       data["passed"]),
        ("Failed",       data["failed"] + data["errored"]),
        ("Skipped",      data["skipped"]),
        ("Duration (s)", f"{data['duration']:.2f}"),
        ("Pass Rate",    f"{data['passed'] / data['total'] * 100:.1f}%" if data["total"] else "0%"),
    ]
    for i, (k, v) in enumerate(meta, start=2):
        ka = ws_sum.cell(row=i, column=1, value=k)
        ka.font = _font(bold=True, color=C_HEADER_FG)
        ka.fill = _fill(C_SECTION_BG)
        ka.border = _border()
        ka.alignment = _align("left")

        va = ws_sum.cell(row=i, column=2, value=v)
        va.font   = _font()
        va.border = _border()
        va.alignment = _align("left")

        if k == "Passed":
            va.fill = _fill(C_PASS_BG)
            va.font = _font(bold=True)
        elif k == "Failed":
            va.fill = _fill(C_FAIL_BG)
            va.font = _font(bold=True)

    ws_sum.column_dimensions["A"].width = 18
    ws_sum.column_dimensions["B"].width = 38

    # ── Sheet 2: Test Cases ───────────────────────────────────────────────
    ws = wb.create_sheet("Test Cases")
    ws.sheet_view.showGridLines = False

    COL_NO      = 1
    COL_SECTION = 2
    COL_EP      = 3
    COL_NAME    = 4
    COL_DESC    = 5
    COL_EXPECTED= 6
    COL_STATUS  = 7
    COL_DURATION= 8
    COL_NOTES   = 9

    headers = [
        "#", "Module / Class", "Endpoint",
        "Test Case Name", "Description", "Expected Result",
        "Status", "Duration (s)", "Notes / Error",
    ]

    for col, h in enumerate(headers, 1):
        _hdr_cell(ws, 1, col, h)

    ws.row_dimensions[1].height = 22
    ws.freeze_panes = "A2"

    # Column widths
    widths = [5, 28, 30, 38, 60, 60, 10, 12, 40]
    for i, w in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(i)].width = w

    row = 2
    prev_section = None
    tc_num = 0

    for idx, r in enumerate(data["results"]):
        section = r["section"]

        # Section header row
        if section != prev_section:
            label = SECTION_LABELS.get(section, section)
            ws.merge_cells(
                start_row=row, start_column=1,
                end_row=row,   end_column=len(headers)
            )
            _section_cell(ws, row, 1, f"  {label}")
            ws.row_dimensions[row].height = 18
            row += 1
            prev_section = section
            tc_num = 0

        tc_num += 1
        bg = C_PASS_BG if r["status"] == "PASS" else (
             C_FAIL_BG  if r["status"] in ("FAIL", "ERROR") else
             C_SKIP_BG  if r["status"] == "SKIP" else
             (C_ALT_BG  if idx % 2 == 0 else None)
        )

        desc     = DESCRIPTIONS.get(r["raw_name"], "—")
        expected = EXPECTED.get(r["raw_name"], "—")
        endpoint = ENDPOINTS.get(section, "—")

        _data_cell(ws, row, COL_NO,       tc_num,         bg=bg, align="center")
        _data_cell(ws, row, COL_SECTION,  section,        bg=bg)
        _data_cell(ws, row, COL_EP,       endpoint,       bg=bg)
        _data_cell(ws, row, COL_NAME,     r["name"],      bg=bg, bold=True)
        _data_cell(ws, row, COL_DESC,     desc,           bg=bg)
        _data_cell(ws, row, COL_EXPECTED, expected,       bg=bg)

        status_cell = ws.cell(row=row, column=COL_STATUS, value=r["status"])
        status_cell.fill   = _fill(
            "70AD47" if r["status"] == "PASS" else
            "FF0000" if r["status"] in ("FAIL", "ERROR") else "FFD966"
        )
        status_cell.font   = _font(bold=True, color="FFFFFF" if r["status"] in ("PASS","FAIL","ERROR") else "000000")
        status_cell.border = _border()
        status_cell.alignment = _align("center")

        _data_cell(ws, row, COL_DURATION, round(r["duration"], 3), bg=bg, align="center")
        _data_cell(ws, row, COL_NOTES,    r["message"] or "—",      bg=bg)

        ws.row_dimensions[row].height = 52
        row += 1

    # ── Sheet 3: Summary by endpoint ────────────────────────────────────
    ws3 = wb.create_sheet("By Endpoint")
    ws3.sheet_view.showGridLines = False

    _hdr_cell(ws3, 1, 1, "Endpoint")
    _hdr_cell(ws3, 1, 2, "Total")
    _hdr_cell(ws3, 1, 3, "Passed")
    _hdr_cell(ws3, 1, 4, "Failed")
    _hdr_cell(ws3, 1, 5, "Pass Rate")

    ws3.column_dimensions["A"].width = 40
    for c in "BCDE":
        ws3.column_dimensions[c].width = 14

    ep_stats: dict = {}
    for r in data["results"]:
        ep = ENDPOINTS.get(r["section"], r["section"])
        if ep not in ep_stats:
            ep_stats[ep] = {"total": 0, "passed": 0, "failed": 0}
        ep_stats[ep]["total"]  += 1
        if r["status"] == "PASS":
            ep_stats[ep]["passed"] += 1
        else:
            ep_stats[ep]["failed"] += 1

    for i, (ep, s) in enumerate(ep_stats.items(), start=2):
        rate = f"{s['passed'] / s['total'] * 100:.0f}%" if s["total"] else "0%"
        bg = C_PASS_BG if s["failed"] == 0 else C_FAIL_BG
        for col, val in enumerate(
            [ep, s["total"], s["passed"], s["failed"], rate], start=1
        ):
            c = ws3.cell(row=i, column=col, value=val)
            c.fill   = _fill(bg)
            c.font   = _font(bold=(col == 1))
            c.border = _border()
            c.alignment = _align("center" if col > 1 else "left")

    wb.save(output)
    print(f"✅  Report saved → {output.resolve()}")


if __name__ == "__main__":
    if not XML_PATH.exists():
        raise FileNotFoundError(
            f"{XML_PATH} not found. Run:  "
            "python -m pytest tests/test_api.py --junit-xml=test-report.xml"
        )
    data = parse_xml(XML_PATH)
    build_excel(data, XLSX_PATH)

    print(f"\nSummary")
    print(f"  Total   : {data['total']}")
    print(f"  Passed  : {data['passed']}")
    print(f"  Failed  : {data['failed'] + data['errored']}")
    print(f"  Skipped : {data['skipped']}")
    print(f"  Duration: {data['duration']:.2f}s")
