#!/usr/bin/env bash
# Veritrace CLI for the Claude Code skill. Subcommands: login, create, status, download, topup.
# Auth: device login -> token saved at ~/.veritrace/token (mode 600). Never prints the token.
set -euo pipefail

API="${VERITRACE_API_URL:-https://veritrace.cloud}"
TOKEN_DIR="$HOME/.veritrace"
TOKEN_FILE="$TOKEN_DIR/token"

die() { echo "error: $*" >&2; exit 1; }
have_jq() { command -v jq >/dev/null 2>&1; }
json() { if have_jq; then jq -r "$1"; else die "jq is required (brew install jq)"; fi; }

read_token() { [ -f "$TOKEN_FILE" ] && cat "$TOKEN_FILE" || true; }

cmd_login() {
  mkdir -p "$TOKEN_DIR"; chmod 700 "$TOKEN_DIR"
  local existing; existing="$(read_token)"
  if [ -n "$existing" ]; then
    # Validate by hitting the cheap authed identity endpoint.
    if curl -sf -H "Authorization: Bearer $existing" "$API/api/leadengine/me" >/dev/null 2>&1; then
      echo "Already logged in."; return 0
    fi
  fi

  local start; start="$(curl -sf -X POST "$API/api/leadengine/auth/device/start")" || die "could not start device login"
  local device user verurl interval
  device="$(printf '%s' "$start" | json '.device_code')"
  user="$(printf '%s' "$start" | json '.user_code')"
  verurl="$(printf '%s' "$start" | json '.verification_url_complete')"
  interval="$(printf '%s' "$start" | json '.interval')"

  echo ""
  echo "  To connect Claude Code to your Veritrace account:"
  echo "    1. Open: $verurl"
  echo "    2. Sign in and approve this code:  $user"
  echo ""
  command -v open >/dev/null 2>&1 && open "$verurl" >/dev/null 2>&1 || true

  echo -n "Waiting for approval"
  while true; do
    sleep "${interval:-5}"
    echo -n "."
    local poll; poll="$(curl -s -X POST "$API/api/leadengine/auth/device/poll" \
      -H 'content-type: application/json' -d "{\"device_code\":\"$device\"}")" || true
    local status; status="$(printf '%s' "$poll" | json '.status // "pending"')"
    case "$status" in
      approved)
        local tok; tok="$(printf '%s' "$poll" | json '.access_token')"
        [ -n "$tok" ] && [ "$tok" != "null" ] || die "no token in approval response"
        printf '%s' "$tok" > "$TOKEN_FILE"; chmod 600 "$TOKEN_FILE"
        echo ""; echo "Logged in. Token saved to $TOKEN_FILE"; return 0;;
      denied)  echo ""; die "request was denied";;
      expired) echo ""; die "code expired — run login again";;
      *) : ;; # pending
    esac
  done
}

require_token() {
  local t; t="$(read_token)"
  [ -n "$t" ] || { cmd_login; t="$(read_token)"; }
  printf '%s' "$t"
}

cmd_create() {
  local preset=custom buyer="" geo="" count=0 email=half
  while [ $# -gt 0 ]; do case "$1" in
    --preset) preset="$2"; shift 2;;
    --buyer) buyer="$2"; shift 2;;
    --geo) geo="$2"; shift 2;;
    --count) count="$2"; shift 2;;
    --email) email="$2"; shift 2;;
    *) die "unknown arg $1";;
  esac; done
  [ "$count" -gt 0 ] || die "--count required"
  local tok; tok="$(require_token)"
  local body; body="$(printf '{"presetId":"%s","buyerLine":"%s","geo":"%s","count":%s,"emailRequirement":"%s"}' \
    "$preset" "$buyer" "$geo" "$count" "$email")"
  local resp code
  resp="$(curl -s -w '\n%{http_code}' -X POST "$API/api/leadengine/create-job" \
    -H "Authorization: Bearer $tok" -H 'content-type: application/json' -d "$body")"
  code="$(printf '%s' "$resp" | tail -n1)"; resp="$(printf '%s' "$resp" | sed '$d')"
  if [ "$code" = "402" ]; then
    echo "QUOTA/SUBSCRIPTION GATE (402):"; printf '%s\n' "$resp" | json '.message'
    echo "Top-up:  bash scripts/veritrace.sh topup"; return 2
  fi
  [ "$code" = "200" ] || die "create failed ($code): $resp"
  printf '%s\n' "$resp"
  echo "Job: $(printf '%s' "$resp" | json '.jobId')" >&2
}

cmd_status() {
  local id="${1:?job id required}"; local tok; tok="$(require_token)"
  curl -sf "$API/api/leadengine/job-status?id=$id" -H "Authorization: Bearer $tok" \
    | { have_jq && jq '{status:.job.status, stage:.job.stage, delivered:.summary.delivered, verifiedEmails:.summary.verifiedEmails, remaining:.quota.remaining}' || cat; }
}

cmd_download() {
  local id="${1:?job id required}"; local out="${2:-leads.csv}"; local tok; tok="$(require_token)"
  curl -sf "$API/api/leadengine/download-csv?jobId=$id" -H "Authorization: Bearer $tok" -o "$out"
  echo "Saved $out"
}

cmd_topup() {
  local packs="${1:-1}"; local tok; tok="$(require_token)"
  curl -sf -X POST "$API/api/leadengine/top-up" -H "Authorization: Bearer $tok" \
    -H 'content-type: application/json' -d "{\"packs\":$packs}" \
    | { have_jq && jq -r '.checkoutUrl' || cat; }
}

sub="${1:-}"; shift || true
case "$sub" in
  login) cmd_login "$@";;
  create) cmd_create "$@";;
  status) cmd_status "$@";;
  download) cmd_download "$@";;
  topup) cmd_topup "$@";;
  *) echo "usage: veritrace.sh {login|create|status <id>|download <id> [out]|topup [packs]}" >&2; exit 1;;
esac
