"""
Live end-to-end intent-classification + leave-action test sweep.

Unlike tests/test_intent_classification.py (CI-safe, mocked HTTP) and
tests/multi_prompt_report.py (drives fast_classify + leave_action_node
directly, bypassing the live HTTP server), this script exercises the ACTUAL
running helixta-api server's real /hr-assist-stream endpoint end-to-end:
real JWT auth, real structured-LLM intent classification, real streaming
response, real conversation persistence in Postgres — the same path the
Angular client uses.

What this proves that nothing else in the repo does:
  1. Every one of the 180 cases in tests/fixtures/intent_eval_dataset.py
     (all 24 valid intent labels) actually classifies correctly through the
     LIVE structured-output LLM call, not a mocked stand-in — this is the
     "live-accuracy sweep" gap tests/test_intent_classification.py's own
     module docstring flags as not covered by the mocked layer.
  2. HR queries get answered (is_hr=True, a real generated answer) and
     non-HR queries get rejected (is_hr=False, the canned redirect message)
     through the full live pipeline, including a focused non-HR stress list
     beyond the eval dataset's own light (7-case) non_hr coverage.
  3. The three real leave-action flows (apply leave, check leave balance,
     leave status) work end-to-end against a REAL logged-in employee
     account's REAL erp-api data, through the live server, reusing the SAME
     conversation_id across turns to exercise multi-turn slot-filling
     exactly as the Angular client would (this also doubles as a live check
     of the conversation-continuity fix — the second turn must build on the
     first, not reset it).

Nothing here ever submits a real leave application: the apply-leave flow
stops the moment the server emits a "leave_confirmation" event ("Shall I
submit this request?") — the confirming turn is never sent.

Requires:
  - helixta-api running locally (default http://127.0.0.1:8002;
    override with LIVE_API_URL)
  - erp-api running locally and reachable (default http://localhost:8001;
    override with LIVE_ERP_API_URL)
  - Env vars LIVE_TEST_USER_EMAIL / LIVE_TEST_USER_PASSWORD for a real
    role_id=5 (employee, not manager) account — the login flow's real
    ai_assist_jwt_token is used, so every request here is indistinguishable
    from real app traffic.

Run: python tests/live_intent_sweep.py
Writes: <repo>/reports/live_intent_sweep_<timestamp>.xlsx
"""

import asyncio
import datetime
import json
import os
import sys
import time

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

from dotenv import load_dotenv
load_dotenv()

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

from tests.fixtures.intent_eval_dataset import INTENT_EVAL_DATASET

API_URL = os.getenv("LIVE_API_URL", "http://127.0.0.1:8002")
ERP_API_URL = os.getenv("LIVE_ERP_API_URL", "http://localhost:8001")

# ---------------------------------------------------------------------------
# Extra non-HR stress list — the eval dataset only carries 7 non_hr cases;
# this focuses specifically on the user's "non-HR context should reject"
# concern with a broader, more diverse set of off-topic queries.
# ---------------------------------------------------------------------------
NON_HR_STRESS_CASES = [
    "What's the weather like today?",
    "Who won the cricket world cup?",
    "Can you write me a Python script to sort a list?",
    "What's a good recipe for chicken curry?",
    "Recommend me a good movie to watch tonight",
    "What is the capital of France?",
    "Tell me a joke",
    "What's the stock price of Tesla?",
    "How do I fix a flat tire?",
    "Who is the president of the United States?",
    "What's 245 multiplied by 37?",
    "Can you help me plan a birthday party?",
    "What's the best way to learn guitar?",
    "Translate 'good morning' to French",
    "What time is it in Tokyo right now?",
    "Write me a poem about the ocean",
    "What's the latest iPhone model?",
    "How far is the moon from earth?",
]

_MAX_TURN_WAIT = 60.0


def _sse_url(path: str) -> str:
    return f"{API_URL}{path}"


async def _login_real_account(email: str, password: str) -> dict:
    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": "live-intent-sweep"},
        )
    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"LIVE_TEST_USER_EMAIL must be a role_id=5 employee account "
            f"(this account has role_id={data.get('role_id')})."
        )
    return {
        "token": data["ai_assist_jwt_token"],
        "user_id": data["id"],
        "company_id": data["company_id"],
        "name": data.get("name"),
    }


async def _stream_turn(client: httpx.AsyncClient, token: str, query: str, conversation_id: str) -> dict:
    """POSTs one turn to /hr-assist-stream and returns a summary dict:
    intent, is_hr, answer text, event types seen, and the raw done event."""
    events = []
    async with client.stream(
        "POST", _sse_url("/hr-assist-stream"),
        headers={"Authorization": f"Bearer {token}"},
        json={"query": query, "conversation_id": conversation_id},
        timeout=_MAX_TURN_WAIT,
    ) as resp:
        if resp.status_code != 200:
            body = await resp.aread()
            return {
                "intent": None, "is_hr": None, "answer": f"(HTTP {resp.status_code}: {body[:300]})",
                "event_types": [], "done": None, "http_status": resp.status_code,
            }
        async for line in resp.aiter_lines():
            if line.startswith("data: "):
                try:
                    events.append(json.loads(line[6:]))
                except json.JSONDecodeError:
                    pass

    intent_event = next((e for e in events if e.get("type") == "intent"), None)
    done_event = next((e for e in events if e.get("type") == "done"), None)
    event_types = [e.get("type") for e in events]

    if done_event:
        intent = done_event.get("intent")
        is_hr = done_event.get("is_hr")
        if is_hr is None and intent is not None:
            # A cache hit's "done" event (main.py's _serve_cache_hit) only
            # carries intent + cached:true, not is_hr — by design, since a
            # cache replay has no fresh classification to report. Derive it
            # the same way the classifier itself defines is_hr, rather than
            # reading the field's absence as an actual False/failure.
            is_hr = intent != "non_hr"
        answer = (done_event.get("data") or {}).get("answer") or done_event.get("message", "")
    elif intent_event:
        intent = intent_event.get("intent")
        is_hr = intent_event.get("is_hr")
        answer = "(blocked before a 'done' event — see event_types, likely a guardrail failure)"
    else:
        intent = None
        is_hr = None
        answer = "(no intent/done event received)"

    return {
        "intent": intent, "is_hr": is_hr, "answer": answer,
        "event_types": event_types, "done": done_event, "http_status": 200,
    }


# ---------------------------------------------------------------------------
# Category 1: full 180-case dataset, live, one fresh conversation per case
# ---------------------------------------------------------------------------

async def _run_dataset_sweep(client: httpx.AsyncClient, token: str, results: list) -> None:
    total = len(INTENT_EVAL_DATASET)
    for i, case in enumerate(INTENT_EVAL_DATASET):
        query, expected_intent = case["query"], case["intent"]
        expected_is_hr = expected_intent != "non_hr"
        conv_id = f"live-sweep-dataset-{i}-{int(time.time())}"
        try:
            r = await _stream_turn(client, token, query, conv_id)
        except Exception as e:
            r = {"intent": None, "is_hr": None, "answer": f"(exception: {e})", "http_status": None}

        intent_ok = r["intent"] == expected_intent
        is_hr_ok = r["is_hr"] == expected_is_hr
        results.append({
            "category": "Full Dataset (180 cases, all 24 intents)",
            "query": query,
            "expected_intent": expected_intent,
            "expected_is_hr": expected_is_hr,
            "actual_intent": r["intent"],
            "actual_is_hr": r["is_hr"],
            "answer": (r["answer"] or "")[:400],
            "passed": intent_ok and is_hr_ok,
            "source": case.get("source", ""),
        })
        if (i + 1) % 20 == 0 or (i + 1) == total:
            passed_so_far = sum(1 for x in results if x["category"].startswith("Full Dataset") and x["passed"])
            print(f"  ...dataset sweep {i + 1}/{total}  ({passed_so_far}/{i + 1} passed so far)")


# ---------------------------------------------------------------------------
# Category 2: non-HR stress list
# ---------------------------------------------------------------------------

async def _run_non_hr_stress(client: httpx.AsyncClient, token: str, results: list) -> None:
    total = len(NON_HR_STRESS_CASES)
    for i, query in enumerate(NON_HR_STRESS_CASES):
        conv_id = f"live-sweep-nonhr-{i}-{int(time.time())}"
        try:
            r = await _stream_turn(client, token, query, conv_id)
        except Exception as e:
            r = {"intent": None, "is_hr": None, "answer": f"(exception: {e})", "http_status": None}

        passed = r["is_hr"] is False
        results.append({
            "category": "Non-HR Stress (should reject)",
            "query": query,
            "expected_intent": "non_hr",
            "expected_is_hr": False,
            "actual_intent": r["intent"],
            "actual_is_hr": r["is_hr"],
            "answer": (r["answer"] or "")[:400],
            "passed": passed,
            "source": "authored",
        })
    print(f"  ...non-HR stress sweep {total}/{total} done")


# ---------------------------------------------------------------------------
# Category 3: real leave-action flows against real erp-api employee data
# ---------------------------------------------------------------------------

LEAVE_BALANCE_LIVE_CASES = [
    "What is my leave balance?",
    "How many sick leaves do I have left?",
    "check my leave quota",
]

LEAVE_STATUS_LIVE_CASES = [
    "What is the status of my leave requests?",
    "show me my applied leave",
]

# (initial query, canned follow-up answers keyed by a keyword found in the
# assistant's next question — stops as soon as a leave_confirmation event
# appears, and NEVER sends an affirmative confirmation turn).
APPLY_LEAVE_LIVE_SCENARIOS = [
    {
        # Far-future, unlikely-to-collide date — this account has real
        # pending leave data, and _find_conflicting_leave correctly blocks
        # an overlapping date (verified separately); that's product
        # correctness, not something this scenario is testing, so pick a
        # date clear of anything else applied for during this test session.
        "label": "Apply casual leave for 2026-12-01",
        "initial": "I want to apply for casual leave on 2026-12-01",
        "followups": [
            ("type of leave", "casual leave"),
            ("full day or half day", "full day"),
            ("first half or second half", "first half"),
            ("reason", "personal work"),
            ("date", "2026-12-01"),
        ],
    },
    {
        "label": "Apply sick leave for 2026-12-15",
        "initial": "apply sick leave for 2026-12-15",
        "followups": [
            ("type of leave", "sick leave"),
            ("full day or half day", "full day"),
            ("first half or second half", "first half"),
            ("reason", "not feeling well"),
            ("date", "2026-12-15"),
        ],
    },
]


def _pick_followup(question: str, followups: list) -> str:
    """followups is an ordered list of (phrase, answer) — checked in order
    since some questions (e.g. 'full day or half day') would also match a
    looser 'date' substring check, so more specific phrases must come first."""
    q = question.lower()
    for phrase, answer in followups:
        if phrase in q:
            return answer
    return "yes"  # generic fallback — never used for the actual confirmation turn


async def _run_leave_balance_live(client: httpx.AsyncClient, account: dict, results: list) -> None:
    for i, query in enumerate(LEAVE_BALANCE_LIVE_CASES):
        conv_id = f"live-sweep-balance-{i}-{int(time.time())}"
        r = await _stream_turn(client, account["token"], query, conv_id)
        passed = r["intent"] == "leave_balance" and r["is_hr"] is True and "leave_balance" in r["event_types"]
        results.append({
            "category": "Leave Balance (real erp-api data)",
            "query": query,
            "expected_intent": "leave_balance",
            "expected_is_hr": True,
            "actual_intent": r["intent"],
            "actual_is_hr": r["is_hr"],
            "answer": (r["answer"] or "")[:400],
            "passed": passed,
            "source": "live",
        })
    print(f"  ...leave balance live sweep {len(LEAVE_BALANCE_LIVE_CASES)}/{len(LEAVE_BALANCE_LIVE_CASES)} done")


async def _run_leave_status_live(client: httpx.AsyncClient, account: dict, results: list) -> None:
    for i, query in enumerate(LEAVE_STATUS_LIVE_CASES):
        conv_id = f"live-sweep-status-{i}-{int(time.time())}"
        r = await _stream_turn(client, account["token"], query, conv_id)
        passed = r["intent"] == "leave_status" and r["is_hr"] is True
        results.append({
            "category": "Leave Status (real erp-api data)",
            "query": query,
            "expected_intent": "leave_status",
            "expected_is_hr": True,
            "actual_intent": r["intent"],
            "actual_is_hr": r["is_hr"],
            "answer": (r["answer"] or "")[:400],
            "passed": passed,
            "source": "live",
        })
    print(f"  ...leave status live sweep {len(LEAVE_STATUS_LIVE_CASES)}/{len(LEAVE_STATUS_LIVE_CASES)} done")


async def _run_apply_leave_live(client: httpx.AsyncClient, account: dict, results: list) -> None:
    for scenario in APPLY_LEAVE_LIVE_SCENARIOS:
        conv_id = f"live-sweep-apply-{scenario['label'][:20]}-{int(time.time())}".replace(" ", "-")
        transcript = []
        query = scenario["initial"]
        reached_confirmation = False
        final_intent = None
        final_is_hr = None

        for turn in range(1, 6):
            r = await _stream_turn(client, account["token"], query, conv_id)
            transcript.append(f"[Turn {turn}] User: {query}\n  Bot: {r['answer']}")
            final_intent, final_is_hr = r["intent"], r["is_hr"]

            if "leave_confirmation" in r["event_types"]:
                reached_confirmation = True
                break
            if "leave_success" in r["event_types"]:
                # Should be unreachable (we never confirm), but guard anyway.
                break
            query = _pick_followup(r["answer"] or "", scenario["followups"])

        passed = (
            final_intent in ("apply_leave", "leave_success") or reached_confirmation
        ) and final_is_hr is True and reached_confirmation

        results.append({
            "category": "Apply Leave (real erp-api data, multi-turn)",
            "query": scenario["label"],
            "expected_intent": "apply_leave -> leave_confirmation (never submitted)",
            "expected_is_hr": True,
            "actual_intent": final_intent,
            "actual_is_hr": final_is_hr,
            "answer": "\n".join(transcript)[:1500],
            "passed": passed,
            "source": "live",
        })
    print(f"  ...apply-leave live scenarios {len(APPLY_LEAVE_LIVE_SCENARIOS)}/{len(APPLY_LEAVE_LIVE_SCENARIOS)} done")


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

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 = wb.active
    summary.title = "Summary"
    summary["A1"] = "Live Intent Classification + Leave Action Test Sweep"
    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"] = (
        f"Run against the LIVE helixta-api server at {API_URL} — real JWT auth, real "
        f"structured-LLM classification, real erp-api leave data. No leave application "
        f"was ever submitted (apply-leave scenarios stop at the confirmation prompt)."
    )
    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, rows in by_category.items():
        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, rate_cell.font = FAIL_FILL, FAIL_FONT
        else:
            rate_cell.fill, rate_cell.font = PASS_FILL, 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, [42, 10, 10, 10, 12])

    detail = wb.create_sheet("All Results")
    d_headers = ["#", "Category", "Query", "Expected Intent", "Expected is_hr",
                 "Actual Intent", "Actual is_hr", "Result", "Answer / Transcript"]
    for c, h in enumerate(d_headers, start=1):
        detail.cell(row=1, column=c, value=h)
    _style_header_row(detail, 1, len(d_headers))
    for i, r in enumerate(results, start=1):
        row = i + 1
        values = [
            i, r["category"], r["query"], r["expected_intent"], r["expected_is_hr"],
            r["actual_intent"], r["actual_is_hr"], "PASS" if r["passed"] else "FAIL", r["answer"],
        ]
        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, result_cell.font = PASS_FILL, PASS_FONT
        else:
            result_cell.fill, result_cell.font = FAIL_FILL, FAIL_FONT
    detail.freeze_panes = "A2"
    detail.auto_filter.ref = f"A1:I{len(results) + 1}"
    _autofit(detail, [5, 30, 45, 25, 12, 20, 12, 9, 60])

    failures = [r for r in results if not r["passed"]]
    fws = wb.create_sheet("Failures Only")
    for c, h in enumerate(d_headers, start=1):
        fws.cell(row=1, column=c, value=h)
    _style_header_row(fws, 1, len(d_headers))
    if failures:
        for i, r in enumerate(failures, start=1):
            row = i + 1
            values = [
                i, r["category"], r["query"], r["expected_intent"], r["expected_is_hr"],
                r["actual_intent"], r["actual_is_hr"], "FAIL", r["answer"],
            ]
            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 live test cases passed.").font = Font(
            bold=True, color="006100")
    fws.freeze_panes = "A2"
    _autofit(fws, [5, 30, 45, 25, 12, 20, 12, 9, 60])

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


async def _main_async():
    email = os.getenv("LIVE_TEST_USER_EMAIL")
    password = os.getenv("LIVE_TEST_USER_PASSWORD")
    if not email or not password:
        raise RuntimeError("LIVE_TEST_USER_EMAIL and LIVE_TEST_USER_PASSWORD must be set.")

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

    results = []
    async with httpx.AsyncClient() as client:
        print(f"\nChecking helixta-api is reachable at {API_URL}...")
        health = await client.get(
            f"{API_URL}/ping", headers={"Authorization": f"Bearer {account['token']}"}, timeout=15.0
        )
        print(f"  {API_URL}/ping -> {health.status_code}")

        print("\n[1/4] Running full 180-case intent dataset sweep (live LLM classification)...")
        await _run_dataset_sweep(client, account["token"], results)

        print("\n[2/4] Running non-HR stress sweep...")
        await _run_non_hr_stress(client, account["token"], results)

        print("\n[3/4] Running leave-balance / leave-status live scenarios (real erp-api data)...")
        await _run_leave_balance_live(client, account, results)
        await _run_leave_status_live(client, account, results)

        print("\n[4/4] Running apply-leave multi-turn live scenarios (real erp-api data, never submitted)...")
        await _run_apply_leave_live(client, account, results)

    return results


def main():
    results = asyncio.run(_main_async())

    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"live_intent_sweep_{timestamp}.xlsx")
    build_report(results, out_path)

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

    total = len(results)
    passed = sum(1 for r in results if r["passed"])
    print(f"\n{'=' * 78}")
    print(f"Live Intent Classification + Leave Action Sweep — {total} cases")
    print(f"{'=' * 78}")
    for category, rows in by_category.items():
        p = sum(1 for r in rows if r["passed"])
        print(f"  {category:48} {p:3}/{len(rows):<3} passed")
    print(f"{'-' * 78}")
    print(f"  {'TOTAL':48} {passed:3}/{total:<3} passed ({passed / total * 100:.1f}%)")
    print(f"{'=' * 78}")

    failures = [r for r in results if not r["passed"]]
    if failures:
        print(f"\n{len(failures)} FAILING CASES:\n")
        for r in failures:
            print(f"  [{r['category']}] {r['query']!r}")
            print(f"      expected_intent={r['expected_intent']!r} actual_intent={r['actual_intent']!r}"
                  f" | expected_is_hr={r['expected_is_hr']} actual_is_hr={r['actual_is_hr']}")
    else:
        print("\nNo failures.")

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


if __name__ == "__main__":
    main()
