#!/bin/sh
# tests/mock_login.sh - stand-in for scorpiox-codex-login machine mode.
#
# Prints exactly the contract shape the real CLI prints (human progress lines
# first, one JSON line last), so the plugin's parsers are exercised against the
# production layout rather than an invented one. `--poll` writes a credential
# file into $CODEX_CREDS_PATH when it reports success, so a test can prove the
# plugin re-reads state instead of trusting the CLI's word.
#
# MOCK_FAIL=1  makes --poll fail the way a denied device code does.
# MOCK_NOUSER=1 makes --start return no user_code (a malformed CLI answer).
# MOCK_EXISTS=1 makes --start report "credentials already exist".

CREDS="${CODEX_CREDS_PATH:-/tmp/sx-mock-scratch}"
# A decodable JWT whose payload says exp=1794509681; tests replace it with a
# freshly generated one so the countdown is real.
MOCK_DEFAULT_TOKEN="eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3OTQ1MDk2ODEsImNoYXRncHRfYWNjb3VudF9pZCI6ImFjY3QtZGVmYXVsdCJ9.DEVFAKE"
PEND="${CODEX_PENDING_DIR:-/tmp/sx-mock-scratch}/codex-default.json"
ACC="${CODEX_ACCOUNT:-default}"

li=false; hr=false; exp=0
if [ -f "$CREDS" ]; then
  if grep -q 'access_token' "$CREDS" 2>/dev/null; then li=true; fi
  if grep -q 'refresh_token' "$CREDS" 2>/dev/null; then hr=true; fi
fi
pend=false
if [ -f "$PEND" ]; then pend=true; fi

# The real CLI reports expires_at 0 because auth.json has no expiry field; the
# plugin is what decodes the token. Keep that behaviour so the suite proves it.
case "$1" in
  --status)
    printf 'Checking Codex credentials...\n'
    printf '{"ok":true,"provider":"codex","name":"Codex (OpenAI)","flow":"device_code","account":"%s","logged_in":%s,"path":"%s","expires_at":0,"expired":false,"has_refresh":%s,"pending":%s,"profile":"codex","profile_exists":false,"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1"}\n' \
      "$ACC" "$li" "$CREDS" "$hr" "$pend"
    ;;
  --start)
    # --force is the only thing that makes an existing credential file a
    # non-error, so honour it here the way the real CLI does.
    _force=0
    for _a in "$@"; do [ "$_a" = "--force" ] && _force=1; done
    if [ "$MOCK_EXISTS" = "1" ] && [ "$_force" != "1" ]; then
      printf '{"ok":false,"provider":"codex","error":"exists","detail":"credentials already exist; pass --force to replace"}\n'
      exit 1
    fi
    if [ "$MOCK_NOUSER" = "1" ]; then
      printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","interval":5,"expires_in":900}\n'
      exit 0
    fi
    mkdir -p "$(dirname "$PEND")" 2>/dev/null
    printf '{"device_auth_id":"dev-mock-1","user_code":"ABCD-1234","interval":5,"force":%s,"created":%s}\n' \
      "${MOCK_FORCE:-0}" "$(date +%s)" > "$PEND"
    printf 'Requesting a device code from OpenAI...\n'
    printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","user_code":"ABCD-1234","interval":5,"expires_in":900,"hint":"Open the link, enter the code, approve. This page checks automatically."}\n'
    ;;
  --poll)
    if [ "$MOCK_FAIL" = "1" ]; then
      printf '{"ok":false,"provider":"codex","error":"denied","detail":"authorization failed or was denied; start again"}\n'
      exit 1
    fi
    if [ "$MOCK_DONE" = "1" ]; then
      cat > "$CREDS" << CREDEOF
{
  "OPENAI_API_KEY": null,
  "tokens": {
    "id_token": "${MOCK_ID_TOKEN:-$MOCK_ACCESS_TOKEN}",
    "access_token": "${MOCK_ACCESS_TOKEN:-$MOCK_DEFAULT_TOKEN}",
    "refresh_token": "rt-from-mock-poll",
    "account_id": "acct-mock"
  },
  "last_refresh": "${MOCK_LAST_REFRESH:-2026-11-12T18:00:00.000000Z}"
}
CREDEOF
      rm -f "$PEND"
      printf '{"ok":true,"provider":"codex","state":"done","logged_in":true,"path":"%s","profile":"codex","profile_created":false}\n' "$CREDS"
    else
      printf 'Polling OpenAI...\n'
      printf '{"ok":true,"provider":"codex","state":"pending","interval":5}\n'
    fi
    ;;
  --cancel)
    rm -f "$PEND"
    printf '{"ok":true,"provider":"codex","cancelled":true}\n'
    ;;
  *)
    printf 'mock: unknown flag %s\n' "$1" >&2
    exit 2
    ;;
esac
exit 0
