#!/usr/bin/env bash
# Cursor CLI status line — context limits %, plan usage %, refresh time
set -euo pipefail

payload=$(cat)
CACHE_FILE="${HOME}/.cursor/statusline-usage-cache.json"
CACHE_TTL=30

# --- context from stdin payload ---
MODEL=$(echo "$payload" | jq -r '.model.display_name // .model.displayName // "Cursor"')
USED=$(echo "$payload" | jq -r '.context_window.used_percentage // empty')
REMAINING=$(echo "$payload" | jq -r '.context_window.remaining_percentage // empty')

if [[ -z "$USED" && -n "$REMAINING" ]]; then
  USED=$(awk -v r="$REMAINING" 'BEGIN { printf "%.0f", 100 - r }')
elif [[ -z "$USED" ]]; then
  USED=0
fi
if [[ -z "$REMAINING" ]]; then
  REMAINING=$(awk -v u="$USED" 'BEGIN { printf "%.0f", 100 - u }')
fi

USED_INT=${USED%.*}
REMAINING_INT=${REMAINING%.*}

# color by context usage
ctx_color() {
  local pct=$1
  if (( pct < 50 )); then printf '\033[32m'
  elif (( pct < 65 )); then printf '\033[33m'
  elif (( pct < 80 )); then printf '\033[38;5;208m'
  else printf '\033[31m'
  fi
}

BAR_WIDTH=10
FILLED=$((USED_INT * BAR_WIDTH / 100))
EMPTY=$((BAR_WIDTH - FILLED))
BAR=""
(( FILLED > 0 )) && printf -v FILL "%${FILLED}s" && BAR="${FILL// /▓}"
(( EMPTY > 0 )) && printf -v PAD "%${EMPTY}s" && BAR="${BAR}${PAD// /░}"

CCTX=$(ctx_color "$USED_INT")
RESET='\033[0m'
DIM='\033[2m'

# --- plan usage + monthly reset (cached 30s) ---
# Uses cursor-agent auth (~/.config/cursor/auth.json), NOT the IDE login.
PLAN_TIER=""
USAGE_PCT=""
API_PCT=""
RESET_DATE=""
RESET_DAYS=""
now_epoch=$(date +%s)
cache_fresh=false

get_cli_token() {
  local auth_file="${XDG_CONFIG_HOME:-${HOME}/.config}/cursor/auth.json"
  if [[ -f "$auth_file" ]]; then
    jq -r '.accessToken // empty' "$auth_file" 2>/dev/null || true
  fi
}

calc_reset_from_end() {
  local end_iso=$1
  [[ -z "$end_iso" ]] && return 1

  RESET_DATE=$(date -d "${end_iso}" '+%b %-d' 2>/dev/null || date -d "${end_iso}" '+%b %d')
  local reset_epoch
  reset_epoch=$(date -d "${end_iso}" '+%s' 2>/dev/null || echo 0)
  if (( reset_epoch > now_epoch )); then
    RESET_DAYS=$(( (reset_epoch - now_epoch + 86399) / 86400 ))
  else
    RESET_DAYS=0
  fi
}

load_plan_cache() {
  PLAN_TIER=$(jq -r '.plan_tier // empty' "$CACHE_FILE" 2>/dev/null || true)
  USAGE_PCT=$(jq -r '.usage_pct // empty' "$CACHE_FILE" 2>/dev/null || true)
  API_PCT=$(jq -r '.api_pct // empty' "$CACHE_FILE" 2>/dev/null || true)
  local cached_end
  cached_end=$(jq -r '.billing_cycle_end // empty' "$CACHE_FILE" 2>/dev/null || true)
  if [[ -n "$cached_end" ]]; then
    calc_reset_from_end "$cached_end"
  else
    RESET_DATE=$(jq -r '.reset_date // empty' "$CACHE_FILE" 2>/dev/null || true)
    RESET_DAYS=$(jq -r '.reset_days // empty' "$CACHE_FILE" 2>/dev/null || true)
  fi
}

if [[ -f "$CACHE_FILE" ]]; then
  cache_ts=$(jq -r '.fetched_at // 0' "$CACHE_FILE" 2>/dev/null || echo 0)
  if (( now_epoch - cache_ts < CACHE_TTL )); then
    cache_fresh=true
    load_plan_cache
  fi
fi

if [[ "$cache_fresh" == false ]]; then
  TOKEN=$(get_cli_token)

  if [[ -n "$TOKEN" ]]; then
    tmp_summary=$(mktemp)
    if /usr/bin/curl -sS --max-time 2 \
      -H "Authorization: Bearer ${TOKEN}" \
      "https://api2.cursor.sh/auth/usage-summary" \
      -o "$tmp_summary" 2>/dev/null && jq -e . "$tmp_summary" >/dev/null 2>&1; then

      PLAN_TIER=$(jq -r '.membershipType // empty' "$tmp_summary")
      USAGE_PCT=$(jq -r '.individualUsage.plan.totalPercentUsed // empty' "$tmp_summary" | awk '{printf "%.0f", $1}')
      API_PCT=$(jq -r '.individualUsage.plan.apiPercentUsed // empty' "$tmp_summary" | awk '{printf "%.0f", $1}')
      billing_cycle_end=$(jq -r '.billingCycleEnd // empty' "$tmp_summary")
      if [[ -n "$billing_cycle_end" ]]; then
        calc_reset_from_end "$billing_cycle_end"
      fi

      mkdir -p "$(dirname "$CACHE_FILE")"
      jq -n \
        --argjson fetched_at "$now_epoch" \
        --arg plan_tier "${PLAN_TIER}" \
        --arg usage_pct "${USAGE_PCT}" \
        --arg api_pct "${API_PCT}" \
        --arg reset_date "${RESET_DATE}" \
        --arg reset_days "${RESET_DAYS}" \
        --arg billing_cycle_end "${billing_cycle_end}" \
        '{
          fetched_at: $fetched_at,
          plan_tier: ($plan_tier | if . == "" then null else . end),
          usage_pct: ($usage_pct | if . == "" then null else . end),
          api_pct: ($api_pct | if . == "" then null else . end),
          billing_cycle_end: ($billing_cycle_end | if . == "" then null else . end),
          reset_date: ($reset_date | if . == "" then null else . end),
          reset_days: ($reset_days | if . == "" then null else (. | tonumber) end)
        }' \
        > "$CACHE_FILE" 2>/dev/null || true
    fi
    rm -f "$tmp_summary"
  fi
fi

# --- refresh timestamp ---
REFRESHED=$(date '+%H:%M:%S')

# --- output ---
printf "${DIM}%s${RESET} │ ${CCTX}ctx %s %s%%${RESET} ${DIM}(%s%% left)${RESET}" \
  "$MODEL" "$BAR " "$USED_INT" "$REMAINING_INT"

if [[ -n "$USAGE_PCT" ]]; then
  CUSAGE=$(ctx_color "$USAGE_PCT")
  if [[ -n "$PLAN_TIER" && -n "$API_PCT" ]]; then
    printf " │ ${CUSAGE}%s %s%%${RESET} ${DIM}(api %s%%)${RESET}" "$PLAN_TIER" "$USAGE_PCT" "$API_PCT"
  elif [[ -n "$PLAN_TIER" ]]; then
    printf " │ ${CUSAGE}%s %s%%${RESET}" "$PLAN_TIER" "$USAGE_PCT"
  else
    printf " │ ${CUSAGE}plan %s%%${RESET}" "$USAGE_PCT"
  fi
fi

if [[ -n "$RESET_DATE" ]]; then
  if [[ -n "$RESET_DAYS" ]]; then
    printf " │ ${DIM}resets %s (%sd)${RESET}" "$RESET_DATE" "$RESET_DAYS"
  else
    printf " │ ${DIM}resets %s${RESET}" "$RESET_DATE"
  fi
fi

printf " │ ${DIM}↻ %s${RESET}\n" "$REFRESHED"
