#!/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 [[ $# -lt 1 ]]; then
    echo "Usage: ./jeannie remote <read-only-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"]
while True:
    status, result = request("GET", "/v1/executions/" + execution_id)
    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)))
    time.sleep(0.5)
PY
