"""Smoke test for evals/accuracy/mock_erp.py.

    venv/Scripts/python -m evals.accuracy.smoke_mock_erp

1. Calls every erp_client getter (and every write) for both personas through
   the mock, asserting the documented shape comes back.
2. Runs the read-only consumers that parse those bodies - balance, holidays,
   attendance range, shift, punch details, team views, regularizations,
   reporting manager, eligibility - with every LLM entry point stubbed, and
   asserts no exception and that key FACTS values reach the answer.

No network: erp_client._request is the mock, and the LLM calls are stubs.
"""
from __future__ import annotations

import asyncio
import json
import os
import sys
import traceback

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)
os.environ.setdefault("ERP_API_URL", "http://mock-erp.invalid")

import services.erp_client as erp_client  # noqa: E402
from evals.accuracy import mock_erp  # noqa: E402

# Import every consumer up front so the LLM stubs below reach the names they
# imported from ai_service.
import services.ai_service as ai_service  # noqa: E402
import services.hr_graph as hr_graph  # noqa: E402
import services.leave_action_service as leave_action_service  # noqa: E402
import services.attendance as attendance  # noqa: E402
import services.attendance_explain as attendance_explain  # noqa: E402
import services.punch_details as punch_details  # noqa: E402
import services.shift_query as shift_query  # noqa: E402
import services.individual_report as individual_report  # noqa: E402
import services.leave_approval as leave_approval  # noqa: E402
import services.leave_eligibility_service as leave_eligibility_service  # noqa: E402
import services.my_regularisation_view as my_regularisation_view  # noqa: E402
import services.regularisation_approval as regularisation_approval  # noqa: E402
import services.regularisation_cancel as regularisation_cancel  # noqa: E402
import services.regularisation_node as regularisation_node  # noqa: E402
import services.reporting_manager as reporting_manager  # noqa: E402

FACTS = mock_erp.FACTS
EMP, MGR = "employee", "manager"
LLM_CALLS = []


# ── LLM stubs ────────────────────────────────────────────────────────────────
async def _stub_call_llm(prompt, *a, **k):
    LLM_CALLS.append(str(prompt)[:80])
    return {"choices": [{"message": {"content": "{}"}}],
            "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}}


async def _stub_call_llm_stream(*a, **k):
    LLM_CALLS.append("stream")
    yield {"type": "chunk", "content": "[stub llm answer]"}


async def _stub_async_none(*a, **k):
    LLM_CALLS.append("other")
    return None


_STUBS = {"_call_llm": _stub_call_llm, "_call_llm_stream": _stub_call_llm_stream,
          "_call_deepseek": _stub_call_llm, "_call_openai": _stub_call_llm,
          "_call_race": _stub_call_llm}


def stub_llms():
    for name, mod in list(sys.modules.items()):
        if not name.startswith("services") or mod is None:
            continue
        for attr, stub in _STUBS.items():
            if hasattr(mod, attr):
                setattr(mod, attr, stub)


# ── harness bits ─────────────────────────────────────────────────────────────
class Writer:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def text(self):
        return json.dumps(self.events, default=str, ensure_ascii=False)


def state_for(persona, query, intent, **extra):
    st = {
        "query": query, "intent": intent, "context": [], "is_hr": True,
        "bearer_token": mock_erp.make_token(persona),
        "company_id": str(mock_erp.PERSONAS[persona]["user_id"]),
        "true_company_id": mock_erp.COMPANY_ID,
        "conversation_id": f"smoke-{persona}-{intent}-{abs(hash(query)) % 10**8}",
        "usage_events": [], "last_intent": None, "is_manager": persona == "manager",
        "is_manager_jwt": persona == "manager", "is_hr_role": False,
        "moderation": {}, "output_guardrail": {}, "response_text": "", "error": None,
        "has_date_expression": False, "is_database_related": False,
        "general_chat_enabled": False, "general_chat_over_limit": False,
    }
    st.update(extra)
    return st


RESULTS = []


def check(name, cond, detail=""):
    RESULTS.append((name, bool(cond), detail))
    print(f"  [{'PASS' if cond else 'FAIL'}] {name}" + (f"  -- {detail}" if not cond and detail else ""))


async def run_node(name, fn, persona, query, intent, expect=(), **extra):
    w = Writer()
    try:
        out = await fn(state_for(persona, query, intent, **extra), w)
    except Exception as exc:  # noqa: BLE001
        traceback.print_exc()
        check(f"{name} [{persona}] runs", False, f"{type(exc).__name__}: {exc}")
        return ""
    blob = w.text() + json.dumps(out, default=str, ensure_ascii=False)
    check(f"{name} [{persona}] runs", True)
    for want in expect:
        check(f"{name} [{persona}] mentions {want!r}", want.lower() in blob.lower(),
              _answer_of(w, out))
    return blob


def _answer_of(w, out):
    done = [e for e in w.events if e.get("type") == "done"]
    msg = (done[-1].get("message") if done else None) or (out or {}).get("response_text")
    return (str(msg) or "")[:400]


def _ok(r):
    return isinstance(r, dict) and r.get("http_status") == 200 and isinstance(r.get("body"), dict)


def _data(r):
    return (r.get("body") or {}).get("data")


# ── 1. every getter ──────────────────────────────────────────────────────────
async def getters():
    print("\n== erp_client getters ==")
    for p in (EMP, MGR):
        t = mock_erp.make_token(p)
        f = FACTS[p]
        r = await erp_client.ping(t)
        check(f"ping [{p}]", _ok(r))
        r = await erp_client.get_leave_context(t)
        check(f"leave_context [{p}]", _data(r)["name"] == f["name"]
              and _data(r)["is_manager"] is (p == MGR))
        r = await erp_client.get_leave_balance(t)
        d = _data(r)
        check(f"leave_balance [{p}] quota + policy split",
              d["leave_quota"]["casual_leave"]["remaining"] == f["leave_balance_by_slug"]["casual_leave"]["remaining"]
              and "regularization_policy" in d["leave_settings"]
              and all(x["slug"] != "regularization" for x in d["leave_settings"]["leave_type"]))
        r = await erp_client.get_leave_abbreviations(t)
        check(f"abbreviations [{p}]", _data(r)["CL"] == "Casual Leave")
        r = await erp_client.get_leave_holidays(t)
        check(f"holidays [{p}]", _data(r)["total_holidays"] == FACTS["holiday_count_2026"])
        r = await erp_client.get_pending_leaves(t)
        check(f"pending_leaves [{p}]", all(x["status_name"] == "pending" for x in _data(r)["leaves"])
              and len(_data(r)["leaves"]) == len(f["my_pending_leaves"]))
        r = await erp_client.get_pending_leaves(t, applied_leave_date="2026-11-02")
        check(f"pending_leaves date filter [{p}]", len(_data(r)["leaves"]) == (1 if p == EMP else 0))
        r = await erp_client.get_leave_status(t)
        check(f"leave_status (unused route) [{p}]", _ok(r))
        for st in ("all", "pending", "approved", "cancelled", "rejected"):
            r = await erp_client.get_applied_leaves(t, leave_status=st)
            rows = _data(r)["leaves"]
            check(f"applied_leaves {st} [{p}]", st == "all" or all(x["status_name"] == st for x in rows))
        # manager-only routes
        if p == MGR:
            for st in erp_client.TEAM_LEAVE_STATUS_FILTERS:
                r = await erp_client.get_team_leaves(t, leave_status=st)
                check(f"team_leaves {st} [{p}]", _ok(r) and "leaves" in _data(r))
            r = await erp_client.get_team_pending_leaves(t)
            check(f"team_pending_leaves [{p}]",
                  len(_data(r)["leaves"]) == len(f["team_pending_leaves"]))
            r = await erp_client.get_team_pending_leaves(t, employee_name="Priya")
            check(f"team_pending by name [{p}]", _data(r)["action_required"] == "select_employee"
                  and _data(r)["search_matched"] is True)
            r = await erp_client.get_team_pending_leaves(t, employee_name="Zorro")
            check(f"team_pending unknown name [{p}]", _data(r)["search_matched"] is False
                  and len(_data(r)["employees"]) == 6)
            r = await erp_client.get_team_pending_leaves(t, employee_id=4103)
            check(f"team_pending by id [{p}]", _data(r)["employee"]["name"] == "Dileep Anumula")
            r = await erp_client.get_team_members(t)
            check(f"team_members [{p}]", [m["employee_name"] for m in _data(r)["members"]] == f["team_members"])
            r = await erp_client.get_team_attendance_summary(t)
            check(f"attendance_summary today [{p}]", _data(r)["summary_cards"]["total_team"]["value"] == 6)
            r = await erp_client.get_team_attendance_summary(t, date="2026-10-23")
            check(f"attendance_summary 23 Oct [{p}]",
                  _data(r)["missing_punch_details"]["employees"][0]["employee_name"] == "Dileep Anumula")
            r = await erp_client.get_pending_regularizations(t)
            check(f"pending_regularizations [{p}]",
                  _data(r)["total_pending_regularizations"] == len(f["team_pending_regularizations"]))
            r = await erp_client.get_attendance_punch_details(t, employee_id=4105, attendance_date="2026-10-28")
            check(f"punch_details team member [{p}]", _data(r)["punch_status"] == "incomplete")
            r = await erp_client.get_attendance_status_range(t, from_date="2026-10-01", to_date="2026-10-31",
                                                             employee_id=4102)
            check(f"status_range team member [{p}]", len(_data(r)["records"]) == 31)
            r = await erp_client.get_active_shift(t)
            check(f"active_shift manager no-target menu [{p}]", _data(r)["action_required"] == "select_employee")
            r = await erp_client.get_active_shift(t, employee_id=4101)
            check(f"active_shift team member [{p}]", _data(r)["shift"]["shift_name"] == "General Shift")
        else:
            r = await erp_client.get_team_leaves(t, leave_status="pending")
            check(f"team_leaves refused [{p}]", r["http_status"] == 403 and r["body"]["success"] is False)
            r = await erp_client.get_team_members(t)
            check(f"team_members refused [{p}]", r["http_status"] == 403)
            r = await erp_client.get_team_attendance_summary(t)
            check(f"attendance_summary refused [{p}]", r["http_status"] == 403)
            r = await erp_client.get_pending_regularizations(t)
            check(f"pending_regularizations refused [{p}]", r["http_status"] == 403)
            r = await erp_client.get_active_shift(t)
            check(f"active_shift own [{p}]", _data(r)["shift"]["shift_name"] == f["shift"]["name"])
            r = await erp_client.get_active_shift(t, employee_name="Priya Sharma")
            check(f"active_shift other refused [{p}]", r["http_status"] == 403)
        r = await erp_client.get_attendance_punch_details(t, attendance_date="2026-10-07" if p == EMP else "2026-10-09")
        check(f"punch_details own half day [{p}]", _data(r)["attendance"]["attendance"] == "PA")
        r = await erp_client.get_punch_details(t, date="2026-10-14")
        check(f"get_punch_details [{p}]", _ok(r) and "punches" in _data(r))
        r = await erp_client.get_punch_time(t, date="2026-10-28")
        check(f"get_punch_time today [{p}]", _data(r)["attendance"] is None)
        r = await erp_client.get_attendance_status_range(t, from_date="2026-10-01", to_date="2026-10-31")
        recs = {x["date"]: x["status"] for x in _data(r)["records"]}
        check(f"status_range month [{p}]", recs["2026-10-28"] is None and recs["2026-10-03"] == "Off"
              and all(recs[k] == v for k, v in f["attendance_notable"].items() if v != "Not Recorded"))
        r = await erp_client.get_attendance_status(t, "2026-10-07", "2026-10-07")
        check(f"attendance_status baked query [{p}]", _data(r)["type"] == "single")
        r = await erp_client.get_attendance_query(t, "2026-08-01", "2026-10-28")
        check(f"attendance_query summary >31d [{p}]", _data(r)["type"] == "summary")
        r = await erp_client.get_attendance_explanation(t, "2026-10-14")
        check(f"attendance_explanation [{p}]", _ok(r))
        for st in (None, "pending", "approved", "rejected", "cancelled"):
            r = await erp_client.get_my_regularizations(t, status=st)
            check(f"my_regularizations {st or 'all'} [{p}]", _ok(r) and "regularizations" in _data(r))


async def writes():
    print("\n== writes (recorded, never sent) ==")
    mock_erp.WRITES.clear()
    e, m = mock_erp.make_token(EMP), mock_erp.make_token(MGR)
    r = await erp_client.apply_leave(e, "casual_leave", "2026-11-05", "2026-11-05", reason="Personal")
    check("apply_leave ok", r["body"]["success"] and isinstance(r["body"]["data"], list))
    r = await erp_client.apply_leave(e, "casual_leave", "2026-11-02", "2026-11-02", reason="dup")
    check("apply_leave duplicate -> 400 body", r["http_status"] == 400 and not r["body"]["success"])
    r = await erp_client.cancel_leave(e, 9101, "Plans changed")
    check("cancel_leave ok", r["body"]["success"] and r["body"]["data"]["leave_id"] == 9101)
    r = await erp_client.approve_leave_request(m, 9102)
    check("approve_leave_request ok", r["body"]["data"]["status_name"] == "approved")
    r = await erp_client.reject_leave_request(m, 9103, "Release week, please move it")
    check("reject_leave_request ok", r["body"]["data"]["status_name"] == "rejected")
    r = await erp_client.approve_leave_request(e, 9102)
    check("approve by employee refused (400 body)", r["body"]["success"] is False)
    r = await erp_client.post_regularization(e, payload={"apply_date": "2026-10-07", "from_time": "09:30",
                                                         "to_time": "18:30", "reason": "Forgot to punch"})
    check("post_regularization ok", r["body"]["success"])
    r = await erp_client.approve_regularization(m, 5601)
    check("approve_regularization ok", r["body"]["data"]["status_name"] == "approved")
    r = await erp_client.reject_regularization(m, 5602, "No evidence")
    check("reject_regularization ok", r["body"]["data"]["status_name"] == "rejected")
    r = await erp_client.cancel_regularization(e, 5501, "Applied by mistake")
    check("cancel_regularization ok", r["body"]["data"]["status_name"] == "cancelled")
    check("WRITES recorded", len(mock_erp.WRITES) == 10, str(len(mock_erp.WRITES)))
    try:
        await erp_client._request("GET", "/api/v1/ai/does/not/exist", e)
        check("unknown path raises", False)
    except erp_client.ErpApiUnavailable:
        check("unknown path raises ErpApiUnavailable", "GET /api/v1/ai/does/not/exist" in mock_erp.UNKNOWN_PATHS)
    mock_erp.UNKNOWN_PATHS.clear()


# ── 2. consumers ─────────────────────────────────────────────────────────────
async def consumers():
    print("\n== consumers ==")
    fe, fm = FACTS[EMP], FACTS[MGR]

    # leave balance (leave_action_service)
    await run_node("leave balance", leave_action_service.leave_action_node, EMP,
                   "what is my leave balance", "leave_balance", expect=("7.5",))
    await run_node("casual balance", leave_action_service.leave_action_node, EMP,
                   "how many casual leaves do I have left", "leave_balance",
                   expect=("7.5 casual leave", "out of 12"))
    await run_node("sick balance", leave_action_service.leave_action_node, MGR,
                   "how many sick leaves do I have", "leave_balance", expect=("8",))
    await run_node("leave status", leave_action_service.leave_action_node, EMP,
                   "show my pending leave requests", "leave_status", expect=("9101",))

    # holidays (hr_graph._holiday_answer)
    for p in (EMP, MGR):
        st = state_for(p, "", "policy")
        a = await hr_graph._holiday_answer(st, "how many holidays this year")
        check(f"holiday count [{p}]", f"{FACTS['holiday_count_2026']} holidays" in a
              and f"{FACTS['holidays_upcoming']} are still to come" in a, a)
        a = await hr_graph._holiday_answer(st, "when is the next holiday")
        check(f"next holiday [{p}]", "Diwali" in a and "Sun, 08 Nov 2026" in a, a)
        a = await hr_graph._holiday_answer(st, "is 25 dec a holiday")
        check(f"is it a holiday [{p}]", "Christmas" in a, a)

    # attendance range (attendance_node)
    await run_node("attendance range", attendance.attendance_node, EMP,
                   "show my attendance from 1 oct 2026 to 28 oct 2026", "attendance",
                   expect=("Half Day Absent", "Missing Punch", "Not Recorded", "Absent"))
    await run_node("attendance single", attendance.attendance_node, EMP,
                   "what was my attendance on 7 oct 2026", "attendance", expect=("Half Day Absent",))
    await run_node("attendance today", attendance.attendance_node, MGR,
                   "what is my attendance today", "attendance", expect=("Not Recorded",))

    # shift
    await run_node("shift", shift_query.shift_query_node, EMP, "what is my shift timing", "shift_query",
                   expect=("General Shift", "09:30", "18:30"))
    await run_node("weekly off", shift_query.shift_query_node, EMP, "what is my weekly off", "shift_query",
                   expect=("Saturday", "Sunday"))
    await run_node("shift", shift_query.shift_query_node, MGR, "what is my shift timing", "shift_query",
                   expect=("Management Shift", "10:00"))

    # punch details
    await run_node("punch details", punch_details.punch_details_node, EMP,
                   "show my punch details for 7 oct 2026", "punch_details", expect=("09:",))
    await run_node("punch details today", punch_details.punch_details_node, MGR,
                   "show my punch in time today", "punch_details", expect=("10:",))

    # manager team views
    await run_node("team members", hr_graph.team_members_node, MGR, "who is in my team", "team_members",
                   expect=tuple(fm["team_members"]))
    await run_node("team members", hr_graph.team_members_node, EMP, "who is in my team", "team_members")
    await run_node("team leaves", hr_graph.team_leave_query_node, MGR,
                   "show pending leave requests of my team", "team_leave_query",
                   expect=("Priya Sharma", "Dileep Anumula", "Ravi Kumar"))
    await run_node("team leaves", hr_graph.team_leave_query_node, EMP,
                   "show pending leave requests of my team", "team_leave_query")
    await run_node("team attendance", hr_graph.team_attendance_summary_node, MGR,
                   "team attendance summary for today", "team_attendance_summary",
                   expect=("Arjun Nair",))
    await run_node("individual report", individual_report.individual_report_node, MGR,
                   "show pending leaves of Dileep Anumula", "individual_report",
                   expect=("Dileep Anumula",))
    await run_node("leave approval list", leave_approval.leave_approval_node, MGR,
                   "approve Priya Sharma's leave", "leave_approval", expect=("Priya Sharma",))

    # regularizations
    await run_node("my regularizations", my_regularisation_view.my_regularisation_view_node, EMP,
                   "show my regularization requests", "my_regularisation_view", expect=("5501",))
    await run_node("team regularizations", regularisation_approval.regularisation_approval_node, MGR,
                   "show pending regularization requests of my team", "regularisation_approval",
                   expect=("Dileep Anumula", "Meera Iyer"))
    await run_node("cancel regularization", regularisation_cancel.regularisation_cancel_node, EMP,
                   "cancel my regularization request", "regularisation_cancel", expect=("5501",))
    await run_node("regularization eligibility", regularisation_node.regularisation_eligibility_node, EMP,
                   "regularize 7 oct 2026", "regularisation_eligibility",
                   expect=("eligible", "1 of 3 used"))

    # reporting manager, eligibility, explain
    await run_node("reporting manager", reporting_manager.reporting_manager_node, EMP,
                   "who is my reporting manager", "reporting_manager", expect=(fe["reporting_manager"],))
    await run_node("reporting manager", reporting_manager.reporting_manager_node, MGR,
                   "who is my reporting manager", "reporting_manager", expect=(fm["reporting_manager"],))
    await run_node("leave eligibility", leave_eligibility_service.leave_eligibility_node, EMP,
                   "am I eligible for earned leave", "leave_eligibility", expect=("Earned Leave",))
    await run_node("attendance explain", attendance_explain.attendance_explain_node, EMP,
                   "why was I marked half day absent on 7 oct 2026", "attendance_explain",
                   expect=("Half Day Absent",))


async def main():
    mock_erp.install()
    mock_erp.pin_today()
    stub_llms()
    mock_erp.reset()
    await getters()
    await writes()
    await consumers()
    failed = [r for r in RESULTS if not r[1]]
    print(f"\n== {len(RESULTS) - len(failed)}/{len(RESULTS)} checks passed; "
          f"LLM stub calls: {len(LLM_CALLS)}; unknown erp paths: {sorted(set(mock_erp.UNKNOWN_PATHS))} ==")
    if failed:
        print("FAILED:")
        for n, _, d in failed:
            print(f"  - {n}: {d}")
    return 1 if failed or mock_erp.UNKNOWN_PATHS else 0


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