"""Drives Helix AI's real graph over generated conversations and records every
turn to JSONL. The race model classifies and answers; erp-api and web search
are mocked; nothing is written to any real system.

    venv/Scripts/python -m evals.accuracy.runner --n 1000 --out <file.jsonl> [--concurrency 16]

Safety, set up BEFORE any service module is imported:
  * erp_client._request is replaced by mock_erp.fake_request - writes are
    recorded and answered locally, never sent (the LR-69 rule);
  * DATABASE_URL points at a throwaway SQLite file and the approval audit log
    is a no-op, so no row reaches the real database;
  * redis.Redis is fakeredis - one in-memory server, so multi-turn flows keep
    their state without touching a real Redis;
  * web search returns canned results; the queries the model asked for are
    recorded, which is what the search checks grade.
"""
import argparse
import asyncio
import contextvars
import json
import logging
import os
import sys
import tempfile
import time
import traceback

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ROOT)
from dotenv import load_dotenv  # noqa: E402

load_dotenv(os.path.join(ROOT, ".env"))
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(tempfile.gettempdir(), "helix_eval.sqlite3")
os.environ["OUTPUT_MODERATION_ENABLED"] = "false"
if os.environ.get("EVAL_PYDEPS"):
    sys.path.append(os.environ["EVAL_PYDEPS"])  # fakeredis, installed outside the venv

import fakeredis  # noqa: E402
import redis  # noqa: E402

_FAKE_SERVER = fakeredis.FakeServer()


def _fake_redis(*args, **kwargs):
    return fakeredis.FakeRedis(server=_FAKE_SERVER, decode_responses=kwargs.get("decode_responses", False))


redis.Redis = _fake_redis
redis.StrictRedis = _fake_redis

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

erp_client._request = mock_erp.fake_request
mock_erp.pin_today()  # the mock's world is 28 Oct 2026, whatever day the run starts

import services.ai_service as ai_service  # noqa: E402
import services.audit_log_service as audit_log_service  # noqa: E402
from services.chat_service import history_text  # noqa: E402
from services.hr_graph import hr_graph  # noqa: E402
from services import graph_checkpointer, flow_interrupts  # noqa: E402
from schema.agent import HRState  # noqa: E402
# With LANGGRAPH_CHECKPOINTER on, the tables live in the throwaway SQLite file.
if getattr(hr_graph, "checkpointer", None) is not None:
    graph_checkpointer._meta.create_all(hr_graph.checkpointer.engine)
from services.nlp_service import fast_classify, mentions_summary  # noqa: E402

from evals.accuracy.cases import generate  # noqa: E402

audit_log_service._write = lambda **fields: None

_TURN = contextvars.ContextVar("eval_turn", default=None)


class _UpstreamTrouble(logging.Handler):
    """Tags the running turn when a log line shows race-api throttling or
    failing (429/5xx, a timeout, "failed (allowing through)"): those turns
    degrade quietly - a policy lookup that hit 429 answers "I do not have
    this information" - and must be graded as infrastructure, not accuracy."""
    _MARKS = ("429", "Too Many Requests", " 502", " 503", " 504", "ReadTimeout", "ConnectTimeout",
              "PoolTimeout", "RAG query failed", "moderation failed", "LLM stream failed",
              "LLM failed", "failed, using the fallback")

    def emit(self, record):
        rec = _TURN.get()
        if rec is None:
            return
        try:
            msg = record.getMessage()
        except Exception:
            return
        if any(m in msg for m in self._MARKS):
            rec["upstream_trouble"].append(msg[:200])


logging.getLogger().addHandler(_UpstreamTrouble(level=logging.WARNING))


async def _stub_search(query, k=ai_service.RACE_SEARCH_RESULT_COUNT):
    rec = _TURN.get()
    if rec is not None:
        rec["search_queries"].append(query)
    return [{"title": f"Result for {query}", "url": "https://example.invalid/eval",
             "content": f"(Evaluation stub - no live data was fetched for: {query})"}]


ai_service._call_race_brave_search = _stub_search

_real_fake_request = mock_erp.fake_request


async def _tracked_request(method, path, *args, **kwargs):
    rec = _TURN.get()
    if rec is not None:
        rec["erp_calls"].append(f"{method} {path.split('?')[0]}")
        if method.upper() != "GET":
            rec["writes"].append(f"{method} {path}")
    return await _real_fake_request(method, path, *args, **kwargs)


erp_client._request = _tracked_request

_HISTORY_MESSAGES = 20          # main._load_chat_history: Redis keeps 20 messages
_SUMMARY_EXCHANGES = 20         # main._SUMMARY_HISTORY_EXCHANGES
_TURN_TIMEOUT = float(os.getenv("EVAL_TURN_TIMEOUT", "240"))


async def run_turn(query, context, last_intent, persona, conversation_id, company_id):
    """One turn, built like main._ai_stream builds it."""
    nlp_intent, _, nlp_confidence = fast_classify(query)
    pre_intent = nlp_intent if (nlp_intent and nlp_confidence >= 0.5) else "general"
    state = {
        # main's per-turn reset, and the flows that pause this turn (Phase 5)
        **{key: None for key in HRState.__annotations__ if key not in flow_interrupts.PERSISTED_KEYS},
        "interrupt_flows": flow_interrupts.enabled_flows(hr_graph),
        "query": query, "context": context, "intent": pre_intent, "is_hr": True,
        "is_database_related": False, "has_date_expression": False, "moderation": {},
        "output_guardrail": {}, "response_text": "", "error": None, "usage_events": [],
        "bearer_token": mock_erp.make_token(persona), "company_id": company_id,
        "conversation_id": conversation_id, "is_manager_jwt": persona == "manager",
        "last_intent": last_intent, "is_manager": None,
        "general_chat_enabled": False, "general_chat_over_limit": False,
    }
    rec = {"classify_intent": None, "done_intent": None, "blocked": False, "guardrail_categories": None,
           "answer": "", "data": None, "event_types": [], "searched": False, "search_queries": [],
           "erp_calls": [], "writes": [], "errors": [], "usage_tokens": 0, "upstream_trouble": []}
    token = _TURN.set(rec)
    t0 = time.time()
    try:
        async def _consume():
            # As main._checkpoint_run_kwargs: a thread only when the graph saves state.
            run_kwargs = ({} if getattr(hr_graph, "checkpointer", None) is None else
                          {"config": graph_checkpointer.thread_config(company_id, conversation_id),
                           "durability": "exit"})
            run_input = (await flow_interrupts.turn_input(hr_graph, run_kwargs["config"], state)
                         if state["interrupt_flows"] else state)
            async for event in hr_graph.astream(run_input, stream_mode="custom", **run_kwargs):
                etype = event.get("type")
                rec["event_types"].append(etype)
                if etype == "intent" and rec["classify_intent"] is None:
                    rec["classify_intent"] = event.get("intent")
                elif etype == "searching":
                    # Only the web: policy_rag_node sends "Checking policy documents...".
                    if "web" in str(event.get("message") or "Searching the web").lower():
                        rec["searched"] = True
                elif etype == "error":
                    rec["errors"].append(event.get("message"))
                elif etype == "guardrail" and event.get("status") == "failed" and rec["done_intent"] is None:
                    rec["blocked"] = True
                    rec["guardrail_categories"] = event.get("categories")
                    rec["done_intent"] = event.get("intent") or "blocked"
                    rec["answer"] = event.get("message") or ""
                    rec["data"] = {"answer": rec["answer"],
                                   **({"access_notice": event["access_notice"]} if event.get("access_notice") else {})}
                elif etype == "done" and rec["done_intent"] is None:
                    rec["done_intent"] = event.get("intent")
                    rec["data"] = event.get("data") or {}
                    rec["answer"] = (rec["data"].get("answer") if isinstance(rec["data"], dict) else "") \
                        or event.get("message") or ""
                    for u in event.get("usage_events") or []:
                        rec["usage_tokens"] += int((u.get("usage") or {}).get("total_tokens") or 0)
        await asyncio.wait_for(_consume(), _TURN_TIMEOUT)
    except asyncio.TimeoutError:
        rec["errors"].append(f"TIMEOUT after {_TURN_TIMEOUT:.0f}s")
    except Exception as e:
        rec["errors"].append(f"EXCEPTION {type(e).__name__}: {e}")
        rec["traceback"] = traceback.format_exc()[-2000:]
    finally:
        _TURN.reset(token)
    rec["searched"] = rec["searched"] or bool(rec["search_queries"])
    rec["latency_s"] = round(time.time() - t0, 2)
    return rec


async def run_case(case, company_id):
    conv = f"eval-{case['id']}"
    history, last_intent, out = [], None, []
    for i, turn in enumerate(case["turns"]):
        q = turn["q"]
        if mentions_summary(q):
            context = history[-2 * _SUMMARY_EXCHANGES:]
        else:
            context = history[-_HISTORY_MESSAGES:]
        rec = await run_turn(q, list(context), last_intent, case["persona"], conv, company_id)
        rec.update({"case_id": case["id"], "kind": case["kind"], "persona": case["persona"], "turn": i,
                    "q": q, "lane": turn["lane"], "expect": turn["expect"],
                    "topics": turn.get("topics"), "after": turn.get("after")})
        out.append(rec)
        data = rec["data"] if isinstance(rec["data"], dict) else {"answer": rec["answer"]}
        history += [{"role": "user", "content": q},
                    {"role": "assistant", "content": history_text(data) or rec["answer"]}]
        last_intent = "blocked" if rec["blocked"] and not rec["done_intent"] else (rec["done_intent"] or last_intent)
    return out


def _jsonable(o):
    if isinstance(o, set):
        return sorted(o)
    return str(o)


async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=1000)
    ap.add_argument("--seed", type=int, default=20261028)
    ap.add_argument("--out", required=True)
    ap.add_argument("--concurrency", type=int, default=16)
    ap.add_argument("--start", type=int, default=0, help="skip the first N cases")
    args = ap.parse_args()

    cases = generate(args.n, args.seed)[args.start:]
    done_ids = set()
    if os.path.exists(args.out):
        with open(args.out, encoding="utf-8") as f:
            for line in f:
                try:
                    done_ids.add(json.loads(line)["case_id"])
                except Exception:
                    pass
    todo = [c for c in cases if c["id"] not in done_ids]
    print(f"cases: {len(cases)}  already done: {len(done_ids)}  to run: {len(todo)}", flush=True)

    sem = asyncio.Semaphore(args.concurrency)
    lock = asyncio.Lock()
    started = time.time()
    finished = 0

    async def one(idx, case):
        nonlocal finished
        async with sem:
            # A distinct numeric "user id" per case keeps every store's keys apart.
            recs = await run_case(case, company_id=900000 + int(case["id"][1:]))
        async with lock:
            with open(args.out, "a", encoding="utf-8") as f:
                for r in recs:
                    f.write(json.dumps(r, default=_jsonable, ensure_ascii=False) + "\n")
            finished += 1
            if finished % 25 == 0 or finished == len(todo):
                el = time.time() - started
                print(f"[{finished}/{len(todo)}] {el/60:.1f} min elapsed, "
                      f"~{el/finished*(len(todo)-finished)/60:.1f} min left", flush=True)

    await asyncio.gather(*(one(i, c) for i, c in enumerate(todo)))
    print("writes recorded (mocked, never sent):", len(mock_erp.WRITES))
    print("unknown erp paths:", sorted(set(map(str, mock_erp.UNKNOWN_PATHS)))[:20])


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