#!/usr/bin/env python3
"""DimerIQ example client. Python 3.10+, standard library only. No write retries."""
import argparse, json, os, sys, urllib.request, urllib.error, urllib.parse
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

def request(method, path, body=None):
    base = os.environ["DIMERIQ_BASE_URL"].rstrip("/")
    u = urllib.parse.urlsplit(base)
    if u.scheme != "https" or u.username or u.password or u.query or u.fragment:
        raise ValueError("Use the approved HTTPS app base URL.")
    token = os.environ["OSPRI_ACCESS_TOKEN"]
    headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
    try:
        with urllib.request.build_opener(NoRedirect).open(req, timeout=45) as response:
            return json.load(response)
    except urllib.error.HTTPError as e:
        # Status only by default: error bodies can repeat private request data.
        raise RuntimeError(f"DimerIQ returned HTTP {e.code}. Check the documented error guide.") from None

if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("operation", choices=["list-runs", "get-run", "start-panel", "pause", "resume", "candidates", "save-decision"])
    p.add_argument("--run-id")
    p.add_argument("--input", help="Path to a reviewed JSON input file")
    a = p.parse_args()
    if a.operation in ["get-run", "pause", "resume", "candidates"] and not a.run_id:
        p.error("--run-id is required")
    if a.operation in ["start-panel", "save-decision"] and not a.input:
        p.error("--input is required; inspect the JSON before submitting")
    if a.operation == "list-runs": result = request("GET", "/api/science/jobs?panel=true")
    elif a.operation == "get-run": result = request("GET", "/api/science/jobs/" + urllib.parse.quote(a.run_id, safe=""))
    else:
        routes = {"start-panel":"start", "pause":"stop", "resume":"resume", "candidates":"intermediates", "save-decision":"decision"}
        if a.input:
            with open(a.input, encoding="utf-8") as f: body = json.load(f)
        else: body = {"job_id":a.run_id}
        if a.operation == "candidates": body.update(limit=20, offset=0, detail_view="checks")
        result = request("POST", "/api/science/workflow/discovery/" + routes[a.operation], body)
    print(json.dumps(result, indent=2))
