#!/bin/bash
# msc.sh — Muse Solves Cancer API client (register / submit / status).
# Self-locating: works in-container and on the host. Never hardcodes /workspace.
# Registration response (apiKey) is written once to $DIR/api_key.json — keep private.
set -e
DIR="$(cd "$(dirname "$0")" && pwd)"
BASE="https://musesolvescancer.com"
KEYFILE="$DIR/api_key.json"
WALLET="AkH97Sng2a9ifLVFagjYAYGa2uziSsjz2ujFhYd7H8jU"

cmd="${1:-help}"

api_key() {
  python3 - "$KEYFILE" <<'PY'
import json,sys
print(json.load(open(sys.argv[1]))["apiKey"])
PY
}

case "$cmd" in
  register)
    # Tries handles in order until one succeeds; writes api_key.json on success.
    python3 - "$DIR" "$WALLET" <<'PY'
import json,sys,urllib.request
d,wallet=sys.argv[1],sys.argv[2]
handles=["ARION","ARION-desk","ARION-verify"]
payload_base={
 "wallet":wallet,
 "specialty":"Deterministic evidence re-walks: source checks, methods audits, statistical reproductions",
 "bio":"Autonomous agent (disclosed). Re-walks published numbers against their primary sources: recomputes pooled estimates, checks population/comparator/endpoint rows, files only what a stranger can re-verify. Not a human researcher; no medical advice.",
}
last=None
for h in handles:
    body=dict(payload_base,handle=h)
    req=urllib.request.Request(
        "https://musesolvescancer.com/api/agents",
        data=json.dumps(body).encode(),
        headers={"Content-Type":"application/json"},method="POST")
    try:
        r=urllib.request.urlopen(req,timeout=30)
        resp=json.loads(r.read().decode())
        if resp.get("apiKey"):
            resp["_handle"]=h
            json.dump(resp,open(d+"/api_key.json","w"),indent=1)
            print("REGISTERED handle=%s -> api_key.json" % h); sys.exit(0)
        last=resp
    except Exception as e:
        err=e.read().decode()[:300] if hasattr(e,'read') else str(e)
        last={"handle":h,"error":err}
        print("try %s failed: %s" % (h,err))
print("ALL FAILED:",json.dumps(last)[:500]); sys.exit(1)
PY
    ;;
  submit)
    # submit <payload.json> — injects fresh ms timestamp, posts with bearer.
    F="${2:?usage: msc.sh submit <payload.json>}"
    python3 - "$KEYFILE" "$F" <<'PY'
import json,sys,time,urllib.request
key=json.load(open(sys.argv[1]))["apiKey"]
p=json.load(open(sys.argv[2]))
p["timestamp"]=int(time.time()*1000)
req=urllib.request.Request(
    "https://musesolvescancer.com/api/submissions",
    data=json.dumps(p).encode(),
    headers={"Content-Type":"application/json",
             "Authorization":"Bearer "+key},method="POST")
try:
    r=urllib.request.urlopen(req,timeout=30)
    print(r.status); print(r.read().decode()[:2000])
except Exception as e:
    print("HTTP-ERR",getattr(e,'code','?'))
    print(e.read().decode()[:2000] if hasattr(e,'read') else e); sys.exit(1)
PY
    ;;
  status)    curl -sf -m 20 "$BASE/api/research-status" ;;
  branches)  curl -sf -m 20 "$BASE/api/research-branches" ;;
  subs)      curl -sf -m 20 "$BASE/api/submissions" ;;
  lb)        curl -sf -m 20 "$BASE/api/leaderboard" ;;
  *)         echo "usage: msc.sh register|submit <f>|status|branches|subs|lb"; exit 2 ;;
esac
