#!/usr/bin/env python3
"""Copy the Sep29 edge suites (E1a/E1b/E2/E3/E4) with every scenario entering JevRouter instead of Reception.
Personas and evaluators are shared with the originals, so scores compare directly with the Reception runs.
Usage: python3 eval-assets-oct01-jevrouter.py   -> writes eval-assets-oct01-jevrouter.ids.json"""
import json, subprocess, tempfile
P = "019ef714-7882-7dd3-9793-e2eca47954a5"
def api(method, path, body=None):
    args = ["node", "platform-api.mjs", method, f"/api/projects/{P}/evals{path}"]
    if body is not None:
        f = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False); json.dump(body, f); f.close(); args.append(f.name)
    out = subprocess.run(args, capture_output=True, text=True, cwd="/var/www/html/KoreAI/scripts").stdout
    status, text = out.split("\n", 1)
    if not status.startswith("2"): raise SystemExit(f"{method} {path} -> {status} {text[:300]}")
    return json.loads(text)
src = json.load(open("eval-assets-sep29-edge.ids.json"))
SKIP = {"tenantId", "projectId", "id", "_id", "_v", "__v", "createdAt", "updatedAt", "createdBy", "version", "requiredToolOrder"}
ids, scen_map = {}, {}
lst = api("GET", "/scenarios?limit=500"); lst = lst.get("scenarios") or lst.get("data") or []
existing = {s["name"]: s["id"] for s in lst}  # idempotent re-runs reuse earlier copies
for key in ("set_E1a", "set_E1b", "set_E2", "set_E3", "set_E4"):
    s = api("GET", f"/sets/{src[key]}")["evalSet"]
    for sid in s["scenarioIds"]:
        if sid in scen_map: continue
        sc = api("GET", f"/scenarios/{sid}")["scenario"]
        body = {k: v for k, v in sc.items() if k not in SKIP and not k.startswith("_")}
        body.update(entryAgent="JevRouter", name=sc["name"] + " [JevRouter]")
        scen_map[sid] = existing.get(body["name"]) or api("POST", "/scenarios", body)["scenario"]["id"]
    body = {k: v for k, v in s.items() if k not in SKIP and not k.startswith("_") and v is not None}
    body.update(name=s["name"] + " [JevRouter]", scenarioIds=[scen_map[x] for x in s["scenarioIds"]],
                description=s.get("description", "").replace("through Reception", "through JevRouter"))
    ids[key] = api("POST", "/sets", body)["evalSet"]["id"]
    print(key, ids[key])
ids["scenarios"] = scen_map
json.dump(ids, open("eval-assets-oct01-jevrouter.ids.json", "w"), indent=1)
