import json, subprocess, sys, time, urllib.request, urllib.error, http.cookiejar
from urllib.parse import urlencode
BASE="https://playground.qubera.ai"; S="/tmp/claude-1000/-home-mande-repo-quber/bc2f817a-5c6c-4515-9621-2302b82f7f68/scratchpad"
doc_id=int(sys.argv[1])
ssm=lambda n: subprocess.check_output(["aws","ssm","get-parameter","--name",n,"--with-decryption","--region","us-east-1","--query","Parameter.Value","--output","text"]).decode().strip()
jar=http.cookiejar.CookieJar(); opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
def req(path, data=None, method=None, ctype="application/json", timeout=120):
    r=urllib.request.Request(BASE+path, data=data, method=method or ("POST" if data is not None else "GET"), headers={"Content-Type": ctype})
    with opener.open(r, timeout=timeout) as resp: return resp.status, resp.read()
try: req("/login", urlencode({"username": ssm("/quber/PLAYGROUND_LOGIN_USER"), "password": ssm("/quber/PLAYGROUND_LOGIN_PASSWORD"), "next": "/"}).encode(), ctype="application/x-www-form-urlencoded")
except urllib.error.HTTPError as e: print("sign-in", e.code)
for _ in range(60):
    try:
        if req("/healthz", timeout=10)[0]==200: break
    except Exception: pass
    time.sleep(5)
qs=open(f"{S}/questions.txt").read()
st, body=req("/api/batch", json.dumps({"doc_id": doc_id, "questions": qs, "want": "value"}).encode())
run=json.loads(body); jid=run["job_id"]; print("batch", jid, "total", run["total"], flush=True)
for _ in range(360):
    s=json.loads(req(f"/api/batch/{jid}")[1])
    if not s["running"]: break
    time.sleep(10)
print("done", s["done"], "failed", s["failed"])
json.dump(s, open(f"{S}/hosted-batch-{doc_id}.json","w"), indent=1)
