#!/bin/sh
# tests/mock_token.sh - stand-in for scorpiox-opencode-fetchtoken.
#
# The real CLI reads ~/.config/opencode/auth.json and prints
#   {"access_token":"...","org_id":"...","expires_at":1234567890}
# The plugin only ever looks at access_token presence and expires_at, so this
# mock mirrors that shape and reads the same credential file the login mock
# writes, which makes a "refresh after login" test behave like a real node.
#
#   MOCK_TOKEN_FAIL=1   exit non-zero with an error on stderr (no token)

CREDS="${OPENCODE_CREDS_PATH:-/nonexistent-auth.json}"

case "$1" in
  --help|-h)
    printf 'usage: scorpiox-opencode-fetchtoken [-local|-config|-tcp|-remote]\n'
    ;;
  -local|""|-config)
    if [ "$MOCK_TOKEN_FAIL" = "1" ]; then
        printf 'error: auth file not found: %s\n' "$CREDS" >&2
        exit 1
    fi
    if [ ! -f "$CREDS" ]; then
        printf 'error: auth file not found: %s\n' "$CREDS" >&2
        exit 1
    fi
    python3 - "$CREDS" <<'PY'
import json, sys, time
try:
    with open(sys.argv[1]) as f:
        d = json.load(f)
except Exception:
    d = {}
tok = d.get("access_token") or ""
exp = d.get("expires_at") or 0
if not exp and d.get("expires_in"):
    exp = int(time.time()) + int(d["expires_in"])
if not tok:
    sys.stderr.write("error: no access_token in auth file\n")
    sys.exit(1)
print(json.dumps({"access_token": tok,
                  "org_id": d.get("org_id") or "",
                  "expires_at": int(exp)}))
PY
    ;;
  *)
    printf 'error: unknown mode %s\n' "$1" >&2
    exit 2
    ;;
esac
