#!/usr/bin/env bash
set -euo pipefail
REMOTE_URL="${JEANNIE_REMOTE_URL:-http://127.0.0.1:8787}"
REMOTE_TOKEN="${JEANNIE_REMOTE_TOKEN:-${JEANNIE_SERVER_TOKEN:-}}"
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
    export JEANNIE_REMOTE_URL="${REMOTE_URL}" REMOTE_TOKEN
    python3 - <<'PY'
import json, os, sys, urllib.error, urllib.request
url = os.environ["JEANNIE_REMOTE_URL"].rstrip("/")
headers = {}
if os.environ.get("REMOTE_TOKEN"):
    headers["Authorization"] = "Bearer " + os.environ["REMOTE_TOKEN"]
request = urllib.request.Request(url + "/v1/commands", headers=headers, method="GET")
try:
    with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(request, timeout=15) as response:
        payload = json.loads(response.read())
except urllib.error.HTTPError as exc:
    print(exc.read().decode(errors="replace"), file=sys.stderr)
    raise SystemExit(1)
except urllib.error.URLError as exc:
    print(f"jeannie remote: cannot reach {url}: {exc.reason}", file=sys.stderr)
    raise SystemExit(1)
print(f"Jeannie remote API commands ({url}):")
for command in payload.get("commands", []):
    print(f"  {command}")
PY
    exit 0
fi
if [[ $# -lt 1 ]]; then
    echo "Usage: ./jeannie remote <jeannie-command> [args...]" >&2
    exit 2
fi
export JEANNIE_REMOTE_URL="${REMOTE_URL}" REMOTE_TOKEN
python3 - "$@" <<'PY'
import json, os, sys, time, urllib.error, urllib.request
url = os.environ["JEANNIE_REMOTE_URL"].rstrip("/")
command, *args = sys.argv[1:]
headers = {"Content-Type": "application/json"}
if os.environ.get("REMOTE_TOKEN"):
    headers["Authorization"] = "Bearer " + os.environ["REMOTE_TOKEN"]
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def request(method, path, body=None):
    payload = None if body is None else json.dumps(body).encode()
    req = urllib.request.Request(url + path, data=payload, headers=headers, method=method)
    try:
        with opener.open(req, timeout=15) as response:
            return response.status, json.loads(response.read())
    except urllib.error.HTTPError as exc:
        print(exc.read().decode(errors="replace"), file=sys.stderr)
        return exc.code, {}
    except urllib.error.URLError as exc:
        print(f"jeannie remote: cannot reach {url}: {exc.reason}", file=sys.stderr)
        return 599, {}
status, result = request("POST", "/v1/execute", {"command": command, "args": args})
if status != 202:
    sys.exit(1)
execution_id = result["id"]
poll_delay = 1.0
while True:
    status, result = request("GET", "/v1/executions/" + execution_id)
    if status in (429, 503):
        time.sleep(poll_delay)
        poll_delay = min(poll_delay * 2, 5.0)
        continue
    if status != 200:
        sys.exit(1)
    if result["status"] in ("succeeded", "failed"):
        output = result.get("output", "")
        if output:
            print(output, end="" if output.endswith("\n") else "\n")
        sys.exit(int(result.get("exit_code", 0)))
    poll_delay = 1.0
    time.sleep(poll_delay)
PY
