#!/bin/sh
# tests/mock_login.sh - stand-in for scorpiox-opencode-login machine mode.
#
# Emits exactly the contract shape the real CLI emits (one JSON line last, all
# human output before it), so the plugin's parsers are exercised against the
# production layout rather than an invented one. The device exchange is
# simulated: --poll writes a credential file into $OPENCODE_CREDS_PATH and
# removes the pending marker when MOCK_APPROVE=1, which is what the real CLI
# does after the user approves in the browser.
#
#   MOCK_START_FAIL=1   --start answers the "credentials already exist" error
#   MOCK_APPROVE=1      --poll completes the flow
#   MOCK_DENY=1         --poll answers a terminal denial
#   MOCK_NO_PENDING=1   --poll answers no_pending even if a marker exists

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

# pyget <file> <key>  -> the value, or empty string when absent/unreadable
pyget() {
    python3 - "$1" "$2" <<'PY'
import json, sys
try:
    with open(sys.argv[1]) as f:
        d = json.load(f)
except Exception:
    d = {}
v = d.get(sys.argv[2]) if isinstance(d, dict) else None
if v is None:
    print("")
elif isinstance(v, bool):
    print("true" if v else "false")
else:
    print(v)
PY
}

jstr() { # jstr <value> -> "value" or null
    if [ -z "$1" ]; then printf 'null'; else printf '"%s"' "$1"; fi
}

case "$1" in
  --status)
    _li=false; _hr=false; _exp=0; _org=""; _pend=false
    if [ -f "$CREDS" ]; then
        _tok=$(pyget "$CREDS" access_token)
        [ -n "$_tok" ] && _li=true
        _rt=$(pyget "$CREDS" refresh_token)
        [ -n "$_rt" ] && _hr=true
        _exp=$(pyget "$CREDS" expires_at)
        [ -z "$_exp" ] && _exp=0
        _org=$(pyget "$CREDS" org_id)
    fi
    [ -f "$PEND" ] && _pend=true
    printf 'scorpiox-opencode-login 1.0.0 (SXLOGIN-MACHINE-V1)\n'
    printf '{"ok":true,"provider":"opencode","name":"OpenCode","flow":"device_code",'
    printf '"account":%s,"logged_in":%s,"path":"%s",' "$(jstr "$_org")" "$_li" "$CREDS"
    printf '"expires_at":%s,"expired":false,"has_refresh":%s,"pending":%s,' "$_exp" "$_hr" "$_pend"
    printf '"profile":"superopencode","profile_exists":false,"named_accounts":false,'
    printf '"protocol":"SXLOGIN-MACHINE-V1"}\n'
    ;;
  --start)
    if [ "$MOCK_START_FAIL" = "1" ]; then
        printf '{"ok":false,"provider":"opencode","error":"exists","detail":"credentials already exist; pass --force to replace"}\n'
        exit 0
    fi
    if [ "$MOCK_START_NETFAIL" = "1" ]; then
        printf '{"ok":false,"provider":"opencode","error":"network","detail":"device code request failed"}\n'
        exit 0
    fi
    mkdir -p "$(dirname "$PEND")" 2>/dev/null || :
    printf '{"device_code":"oc-mock-device-code-must-not-leak","interval":5,"force":0,"created":%s}\n' \
        "$(date +%s)" > "$PEND"
    printf '{"ok":true,"provider":"opencode","flow":"device_code",'
    printf '"verify_url":"https://opencode.ai/console/device?user_code=ABCD-EFGH&client_id=opencode-cli",'
    printf '"user_code":"ABCD-EFGH","expires_in":900}\n'
    ;;
  --poll)
    if [ "$MOCK_APPROVE" = "1" ]; then
        mkdir -p "$(dirname "$CREDS")" 2>/dev/null || :
        # one redirection for the whole block: in POSIX sh a redirect attaches
        # to a single command, so three separate printfs would write two lines
        # to stdout and only the last one to the credential file.
        {
            printf '{"access_token":"oc-mock-access-token-must-not-leak",'
            printf '"refresh_token":"oc-mock-refresh-token-must-not-leak","token_type":"Bearer",'
            printf '"expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \
                "$(( $(date +%s) + 2591999 ))"
        } > "$CREDS"
        rm -f "$PEND"
        printf 'Logged in successfully!\n'
        printf '{"ok":true,"provider":"opencode","state":"done","logged_in":true,'
        printf '"path":"%s","profile":"superopencode","profile_created":false}\n' "$CREDS"
        exit 0
    fi
    if [ "$MOCK_DENY" = "1" ]; then
        rm -f "$PEND"
        printf '{"ok":false,"provider":"opencode","error":"denied","detail":"access_denied"}\n'
        exit 0
    fi
    if [ ! -f "$PEND" ] || [ "$MOCK_NO_PENDING" = "1" ]; then
        printf '{"ok":false,"provider":"opencode","error":"no_pending","detail":"run --start first"}\n'
        exit 0
    fi
    printf '{"ok":true,"provider":"opencode","state":"pending","interval":5}\n'
    ;;
  --cancel)
    rm -f "$PEND"
    printf '{"ok":true,"provider":"opencode","cancelled":true}\n'
    ;;
  *)
    printf '{"ok":false,"provider":"opencode","error":"usage","detail":"unknown flag"}\n'
    ;;
esac
