#!/usr/bin/env bash
# Tokken check — see your own AI coding spend, with nothing installed.
#
#   curl -fsSL https://tokken.site/check.sh | bash
#
# What this does, all of it:
#   1. Runs the same readers the Tokken collector runs: ccusage for Claude
#      Code, and tokentracker-cli for Codex and Pi (only if this machine has
#      Codex or Pi logs at all).
#   2. Shapes their output with the collector's own filters — JQ_ROWS and
#      JQ_CODEX below are copied verbatim from collect.sh, and a test fails if
#      the two ever drift, so this report and the dashboard count the same way.
#   3. Compresses the result and opens your browser at tokken.site/check#d=…
#
# What it never does: install anything, schedule anything, ask for a token, or
# send your usage anywhere. The data rides after the "#" in the URL, and a
# browser never sends that part to any server. The page reads it there, then
# wipes it from the address bar.
#
# Files it touches: npx's own package cache (~/.npm), and — only if you use
# Codex or Pi — tokentracker's read cursors under ~/.tokentracker. Nothing else.
#
# The whole script is one function called on the last line, so bash has read
# all of it before anything runs. Every reader gets </dev/null for the same
# reason: under `curl | bash`, stdin IS this script, and a program that reads
# stdin would otherwise swallow the rest of it.

set -o pipefail

# Same pins as the collector (TT_CCUSAGE_SPEC / TT_TOKENTRACKER_SPEC in
# collect.sh); a test holds them equal.
TT_CCUSAGE_SPEC="ccusage@20.0.22"
TT_TOKENTRACKER_SPEC="tokentracker-cli@0.83.8"

# Turn one ccusage `daily --json` payload into flat rows. Verbatim from
# collect.sh — see the comment there for the two shapes it normalizes.
JQ_ROWS='[ .daily[]? as $d
  | ( $d.modelBreakdowns // ( ($d.models // {}) | to_entries | map(.value + {modelName: .key}) ) ) as $mbs
  | $mbs[]? as $m
  | {
      tool: $tool, date: $d.date, model: ($m.modelName // "unknown"),
      input_tokens: ($m.inputTokens // 0),
      output_tokens: (($m.outputTokens // 0) + ($m.reasoningOutputTokens // 0)),
      cache_creation_tokens: ($m.cacheCreationTokens // 0),
      cache_read_tokens: ($m.cacheReadTokens // 0),
      cost_usd: ( $m.cost // ( ($d.costUSD // 0) * ( ($m.totalTokens // 0) / ( ($d.totalTokens // 1) | if . == 0 then 1 else . end ) ) ) ),
      accuracy: "exact"
    } ]'

# Turn tokentracker-cli's local queue into rows. Verbatim from collect.sh — see
# the comment there: last line per bucket wins, reasoning is already inside
# output, and cost is left at 0 for the page to price.
JQ_CODEX='[ inputs
  | fromjson?
  | select(type == "object")
  | select(.source == $source or ($prefix != "" and ((.source // "") | tostring | startswith($prefix))))
  | select((.hour_start // "") != "")
]
| reduce .[] as $r ({}; .[([($r.source // ""), ($r.model // "unknown"), $r.hour_start] | tojson)] = $r)
| [ .[] ]
| map(
    (.input_tokens // 0) as $in0
  | (.cached_input_tokens // 0) as $cr
  | (.cache_creation_input_tokens // 0) as $cw
  | (.output_tokens // 0) as $out
  | (.total_tokens // 0) as $tot
  | (if ($cr > 0 and $in0 >= $cr and $tot == ($in0 + $out)) then ($in0 - $cr) else $in0 end) as $in
  | { date: (.hour_start | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601 | strflocaltime("%Y-%m-%d")),
      model: (.model // "unknown"),
      input_tokens: $in, output_tokens: $out,
      cache_creation_tokens: $cw, cache_read_tokens: $cr } )
| map(select($since == "" or .date >= $since))
| group_by([.date, .model])
| map({ tool: $tool, date: .[0].date, model: .[0].model,
        input_tokens: (map(.input_tokens) | add),
        output_tokens: (map(.output_tokens) | add),
        cache_creation_tokens: (map(.cache_creation_tokens) | add),
        cache_read_tokens: (map(.cache_read_tokens) | add),
        cost_usd: 0, accuracy: "estimated" })'

# The page's wire format: one compact array per row, so a year of history fits
# in a URL. Field order is pinned by src/lib/check-payload.ts (CHECK_FIELDS).
JQ_PACK='{ v: 1, tools: $tools,
  rows: ( add // [] | map([ .tool, .date, .model,
    .input_tokens, .output_tokens, .cache_creation_tokens, .cache_read_tokens,
    .cost_usd, (if .accuracy == "exact" then 1 else 0 end) ]) ) }'

say() { printf '%s\n' "$*" >&2; }

tokken_check() {
  # Seams for tests; nobody else needs to set these.
  local ccusage_cmd="${TOKKEN_CHECK_CCUSAGE_CMD:-npx -y $TT_CCUSAGE_SPEC}"
  local tokentracker_cmd="${TOKKEN_CHECK_TOKENTRACKER_CMD:-npx -y $TT_TOKENTRACKER_SPEC}"
  local queue="${TOKKEN_CHECK_TOKENTRACKER_QUEUE:-$HOME/.tokentracker/tracker/queue.jsonl}"
  local tools="${TOKKEN_CHECK_TOOLS:-claude:claude-code tokentracker:codex tokentracker:pi}"
  local origin="${TOKKEN_CHECK_ORIGIN:-https://www.tokken.site}"
  local max_url="${TOKKEN_CHECK_MAX_URL:-60000}"

  local need
  for need in jq gzip base64; do
    if ! command -v "$need" >/dev/null 2>&1; then
      say "Tokken check needs '$need', which isn't installed."
      [ "$need" = jq ] && say "Install it with: brew install jq   (or: sudo apt install jq)"
      return 1
    fi
  done
  if [ -z "${TOKKEN_CHECK_CCUSAGE_CMD:-}" ] && ! command -v npx >/dev/null 2>&1; then
    say "Tokken check needs Node.js (for npx). Install it from https://nodejs.org and run this again."
    return 1
  fi

  local tmp
  tmp="$(mktemp -d)" || return 1
  # shellcheck disable=SC2064  # expand now: $tmp is local
  trap "rm -rf '$tmp'" EXIT

  say ""
  say "Tokken check — reading your usage on this machine. Nothing is installed or sent."
  say ""

  local pair sub tool state json rc
  local tt_ran="" tt_rc=0
  : > "$tmp/states"
  for pair in $tools; do
    sub="${pair%%:*}"
    tool="${pair##*:}"
    state="error"

    if [ "$sub" = "tokentracker" ]; then
      # Same test as the collector: no logs for this tool, skip it.
      local tt_prefix="" has_logs=""
      case "$tool" in
        codex)
          local codex_home="${CODEX_HOME:-$HOME/.codex}"
          has_logs="$(find "$codex_home/sessions" "$codex_home/archived_sessions" \
                      -name 'rollout-*.jsonl' -print -quit 2>/dev/null)"
          ;;
        pi)
          local pi_dir="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
          has_logs="$(find "$pi_dir/sessions" -name '*.jsonl' -print -quit 2>/dev/null)"
          tt_prefix="pi-"
          ;;
      esac
      if [ -z "$has_logs" ]; then
        printf '%s none\n' "$tool" >> "$tmp/states"
        continue
      fi
      say "  Reading ${tool}... (the first read can take a minute on a busy machine)"
      # `sync` only, never `init`; no device token and no base URL, so its own
      # upload stays off. Telemetry off via its documented opt-out. Once per
      # run: one sync parses every tool into the same queue.
      if [ -z "$tt_ran" ]; then
        tt_ran=1
        # shellcheck disable=SC2086  # the command must word-split
        if TOKENTRACKER_NO_TELEMETRY=1 DO_NOT_TRACK=1 \
           $tokentracker_cmd sync </dev/null >/dev/null 2>"$tmp/tokentracker.err"; then
          tt_rc=0
        else
          tt_rc=1
        fi
      fi
      if [ "$tt_rc" = 0 ]; then
        if [ ! -f "$queue" ]; then
          state="none"
        elif jq -n -R --arg tool "$tool" --arg source "$tool" --arg prefix "$tt_prefix" \
               --arg since "" "$JQ_CODEX" "$queue" > "$tmp/rows-$tool.json" 2>/dev/null; then
          state="ok"
        else
          rm -f "$tmp/rows-$tool.json"
        fi
      fi
    else
      say "  Reading ${tool}..."
      # shellcheck disable=SC2086  # the command must word-split
      if json="$($ccusage_cmd "$sub" daily --json --offline </dev/null 2>"$tmp/$tool.err")"; then
        if printf '%s' "$json" | jq --arg tool "$tool" "$JQ_ROWS" > "$tmp/rows-$tool.json" 2>/dev/null; then
          state="ok"
        else
          rm -f "$tmp/rows-$tool.json"
        fi
      else
        rc=$?
        # 127: the reader isn't on this machine — not an error worth showing.
        [ "$rc" = 127 ] && state="none"
      fi
    fi

    if [ "$state" = ok ] && [ "$(jq 'length' "$tmp/rows-$tool.json")" = 0 ]; then
      state="empty"
    fi
    local errf="$tmp/$tool.err"
    [ "$sub" = tokentracker ] && errf="$tmp/tokentracker.err"
    [ "$state" = error ] && say "  Couldn't read ${tool}: $(tail -n 1 "$errf" 2>/dev/null)"
    printf '%s %s\n' "$tool" "$state" >> "$tmp/states"
  done

  local tools_json
  tools_json="$(jq -R -n '[inputs | split(" ") | {(.[0]): .[1]}] | add // {}' < "$tmp/states")"

  if ls "$tmp"/rows-*.json >/dev/null 2>&1; then
    jq -s -c --argjson tools "$tools_json" "$JQ_PACK" "$tmp"/rows-*.json > "$tmp/payload.json"
  else
    jq -n -c --argjson tools "$tools_json" "[] | $JQ_PACK" > "$tmp/payload.json"
  fi

  local rows
  rows="$(jq '.rows | length' "$tmp/payload.json")"
  if [ "$rows" = 0 ]; then
    say ""
    say "No Claude Code or Codex usage found on this machine."
    return 0
  fi
  say "  Found $(jq -r '[.rows[][1]] | unique | length' "$tmp/payload.json") days of usage."

  # base64url without padding: the URL-safe alphabet, so nothing needs escaping.
  local code url
  code="$(gzip -9 -n -c "$tmp/payload.json" | base64 | tr -d '\n=' | tr '+/' '-_')"
  url="$origin/check#d=$code"

  local opener="${TOKKEN_CHECK_OPEN:-}"
  if [ -z "$opener" ]; then
    if [ "$(uname -s)" = Darwin ] && command -v open >/dev/null 2>&1; then
      opener="open"
    elif command -v xdg-open >/dev/null 2>&1; then
      opener="xdg-open"
    fi
  fi

  say ""
  # shellcheck disable=SC2086  # the opener may carry arguments
  if [ -n "$opener" ] && [ "${#url}" -le "$max_url" ] \
     && $opener "$url" </dev/null >/dev/null 2>&1; then
    say "Opened your report in the browser."
    return 0
  fi

  # No browser here (an SSH session) or a history too long for a URL: hand the
  # code over for the page's paste box instead.
  local clip
  for clip in pbcopy wl-copy "xclip -selection clipboard" "xsel --clipboard --input"; do
    if command -v "${clip%% *}" >/dev/null 2>&1 \
       && printf '%s' "$code" | $clip >/dev/null 2>&1; then
      say "Your report code is on the clipboard. Open $origin/check?paste=1 and paste it."
      return 0
    fi
  done
  say "Open $origin/check?paste=1 and paste this code:"
  say ""
  printf '%s\n' "$code"
}

tokken_check "$@"
