"""Inject every corpus email into a live Cooper inbox (screening=hold, firewall_policy=quarantine)
via POST /api/v1/inboxes/:id/inbound, then read it back with GET .../messages/:msgId exactly as an
agent would. Writes cooper_view.json. Needs COOPER_API_KEY and COOPER_INBOX_ID in env."""
import json, os, time, urllib.request, sys
BASE=os.environ.get("COOPER_API_BASE","https://cooperemail.com/api/v1")
K=os.environ["COOPER_API_KEY"]; I=os.environ["COOPER_INBOX_ID"]; RUN=os.environ.get("RUN_ID","r1")
def req(method,path,body=None):
    for a in range(5):
        try:
            r=urllib.request.Request(BASE+path,method=method,data=json.dumps(body).encode() if body is not None else None,
              headers={"Authorization":"Bearer "+K,"content-type":"application/json"})
            with urllib.request.urlopen(r,timeout=30) as resp: return json.load(resp)
        except urllib.error.HTTPError as e:
            if e.code<500: raise RuntimeError(f"{e.code} {e.read()[:300]}")
        except Exception as e: err=e
        time.sleep(2+3*a)
    raise RuntimeError("retries exhausted")
corpus=json.load(open("corpus.json")); out={}
inbox=req("GET",f"/inboxes/{I}")
print("inbox",inbox.get("screening"),inbox.get("firewall_policy"))
for e in corpus:
    body={"from":e["from_"],"subject":e["subject"],"client_id":f"injbench-{RUN}-{e['id']}"}
    if e.get("text"): body["text"]=e["text"]
    if e.get("html"): body["html"]=e["html"]
    m=req("POST",f"/inboxes/{I}/inbound",body)
    got=req("GET",f"/inboxes/{I}/messages/{m['id']}")
    out[e["id"]]=got
    print(e["id"], "held" if "held" in got.get("labels",[]) else "-", got.get("safety",{}).get("score"), (got.get("safety",{}).get("firewall") or {}).get("score"), flush=True)
json.dump(out,open("cooper_view.json","w"),indent=1,ensure_ascii=False)
