"""Delete one hosted document and re-upload the same PDF with its metadata through the playground API."""
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, key, filename, title, folder, filing_type, year, period, version, track = sys.argv[1:11]
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 answered", e.code)
t0 = time.time()
for _ in range(60):
    try:
        if req("/healthz", timeout=10)[0] == 200: break
    except Exception: pass
    time.sleep(5)
print(f"app healthy after {int(time.time()-t0)}s")
docs = {d["id"]: d for d in json.loads(req("/api/documents")[1])}
d = docs.get(int(doc_id))
print("existing row:", {k: d.get(k) for k in ("id","filename","title","folder","filing_type","year","period","version")} if d else None)
if d and d["filename"] != filename:
    sys.exit(f"refusing: id {doc_id} is {d['filename']}, not {filename}")
if d:
    st, body = req(f"/api/documents/{doc_id}", method="DELETE")
    print("delete", st, body[:200].decode())
pdf = open(f"{S}/hosted-pdfs/{key}.pdf","rb").read()
params = {"filename": filename, "title": title, "folder": folder, "filing_type": filing_type, "year": year, "period": period}
if version: params["version"] = version
if track: params["track"] = track
st, body = req("/api/upload?" + urlencode(params), pdf, ctype="application/pdf")
job = json.loads(body); jid = job["job_id"]; print("job", jid, "stage", job["stage"])
t1 = time.time(); last = None; seen = 0
for _ in range(720):
    s = json.loads(req(f"/api/jobs/{jid}?tail=200")[1])
    if s["stage"] != last:
        print(f"  {int(time.time()-t1):4d}s stage -> {s['stage']}", flush=True); last = s["stage"]
    log = s.get("log") or []
    for line in log[seen:]:
        print("       |", line[:160], flush=True)
    seen = len(log)
    if s["stage"] in ("done","failed"): break
    time.sleep(10)
print(f"RESULT: {s['stage']} in {int(time.time()-t1)}s; error={s.get('error')}; doc_id={s.get('doc_id')}")
