"""Exa vs Tavily Advanced on the 485-question panel: one call per (item, arm) through the local jevlin CLI.

Same request as the panel's single-provider arms: tier balanced, providers [x], phrasing 1, max_results 10.
Append-only and resumable: finished keys are skipped on restart.
usage: run.py <panel_dir> <out_dir> [limit]
"""
import json, os, subprocess, sys, threading, time, random
from concurrent.futures import ThreadPoolExecutor

PANEL, OUT = sys.argv[1], sys.argv[2]
LIMIT = int(sys.argv[3]) if len(sys.argv) > 3 else 0
CLI = os.path.expanduser("~/.jevlin/bin/jevlin")
ARMS = ["exa", "tavily-advanced"]
items = [json.loads(l) for l in open(os.path.join(PANEL, "items.jsonl"))]
phr = {}
for l in open(os.path.join(PANEL, "phrasings.jsonl")):
    r = json.loads(l); phr[r["id"]] = r["phrasings"]
random.Random(7).shuffle(items)
if LIMIT: items = items[:LIMIT]
os.makedirs(OUT, exist_ok=True)
done, files, lock = {}, {}, threading.Lock()
for a in ARMS:
    p = os.path.join(OUT, a + ".jsonl"); done[a] = set()
    if os.path.exists(p):
        for l in open(p):
            try:
                r = json.loads(l)
                if r.get("ok"): done[a].add(r["key"])
            except Exception: pass
    files[a] = open(p, "a")

def call(body):
    err = ""; env = None
    for i in range(3):
        t0 = time.perf_counter()
        try:
            p = subprocess.run([CLI, "search", "--stdin", "-timeout", "90s"], input=json.dumps(body).encode(), capture_output=True, timeout=120)
            env = json.loads(p.stdout)
            if env.get("ok"): return True, env, round((time.perf_counter() - t0) * 1000), i + 1, ""
            err = f"{env.get('http_status')} {env.get('code')}"
            if not env.get("retryable") and env.get("http_status") not in (429, 500, 502, 503, 504, None): break
        except Exception as e:
            err = f"{type(e).__name__}: {e}"[:200]
        time.sleep(2 ** i + random.random())
    return False, env, 0, i + 1, err

def job(n, item):
    q = phr[item["id"]][0] if item["id"] in phr else item["query"]
    order = ARMS if n % 2 == 0 else ARMS[::-1]      # alternate which engine goes first
    out = []
    for a in order:
        key = f"{item['id']}|p1|t1"
        if key in done[a]: out.append("skip"); continue
        body = {"version": 1, "query": q, "tier": "balanced", "providers": [a], "max_results": 10, "view": "merged"}
        ok, env, ms, tries, err = call(body)
        res = (env or {}).get("result") or {}
        row = {"key": key, "id": item["id"], "set": item["set"], "phrasing": 1, "trial": 1, "arm": a, "query": q,
               "request": body, "ok": ok, "attempts": tries, "error": err, "cli_ms": ms, "ts": time.time(),
               "response": {"request_id": res.get("request_id"),
                            "merged": [{"url": m.get("url"), "title": (m.get("title") or "")[:200], "found_by": m.get("found_by")} for m in (res.get("merged") or [])],
                            "indexes": res.get("indexes"), "usage": res.get("usage"), "decision": res.get("decision")}}
        with lock:
            files[a].write(json.dumps(row, ensure_ascii=False) + "\n"); files[a].flush()
        out.append("ok" if ok else "err")
    return out

c = {"ok": 0, "err": 0, "skip": 0}; t0 = time.time()
with ThreadPoolExecutor(max_workers=6) as ex:
    for i, res in enumerate(ex.map(lambda x: job(*x), enumerate(items)), 1):
        for r in res: c[r] += 1
        if i % 50 == 0 or i == len(items): print(i, len(items), c, round(time.time() - t0), flush=True)
print("done", c)
