#!/bin/sh
# tests/mock_refresh.sh - stand-in for scorpiox-codex-refreshtoken.
#
# Rewrites the credential file in place with a token whose exp claim is
# MOCK_NEW_EXP (or now+7200 when unset), prints human progress to stdout, and
# exits 0. MOCK_FAIL=1 makes it exit 1 without touching the file, which is how
# a rejected refresh-token grant behaves.
#
# The point of the mock is that it prints token material on stdout - the real
# CLI does too with --verbose - so the suite can prove the plugin never echoes
# it back.

CREDS=""
prev=0
while [ $# -gt 0 ]; do
  case "$1" in
    --credentials-file) CREDS="$2"; shift 2 ;;
    --force|-f) shift ;;
    *) shift ;;
  esac
done
[ -n "$CREDS" ] || CREDS="${CODEX_CREDS_PATH:-/nonexistent}"

if [ ! -f "$CREDS" ]; then
  printf 'error: cannot read %s\n' "$CREDS" >&2
  exit 1
fi

if [ "$MOCK_FAIL" = "1" ]; then
  printf 'error: refresh rejected by the provider\n' >&2
  exit 1
fi

NEW_EXP="${MOCK_NEW_EXP:-$(( $(date +%s) + 7200 ))}"
printf 'Codex OAuth Token Auto-Refresh Tool\n\n'
printf 'Found Codex config: %s\n' "$CREDS"
printf 'Rotated token: %s\n' "super-secret-rotated-token-value"
printf 'New token expires: %s\n' "$NEW_EXP"

python3 - "$CREDS" "$NEW_EXP" << 'PYEOF'
import base64, json, sys, time
path, exp = sys.argv[1], int(sys.argv[2])
payload = {"exp": exp, "chatgpt_account_id": "acct-mock"}
b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
tok = "eyJhbGciOiJIUzI1NiJ9." + b + ".SIG"
try:
    with open(path, "r", encoding="utf-8") as f:
        doc = json.load(f)
except Exception:
    doc = {}
toks = doc.get("tokens") or {}
toks["access_token"] = tok
toks["refresh_token"] = "rt-rotated-by-mock"
doc["tokens"] = toks
doc["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%S.000000Z", time.gmtime())
with open(path, "w", encoding="utf-8") as f:
    json.dump(doc, f, indent=2)
    f.write("\n")
PYEOF
printf 'Updated auth.json\n'
exit 0
