#!/usr/bin/env bash
# Claude Code status line with Bedrock quota monitoring.
# Shows model, cost, quota windows (3h/day/week), and context window usage.
#
# Quota limits are read from CloudWatch (published by the Quota Enforcer Lambda).
# Env var overrides still supported as fallback: BEDROCK_QUOTA_3H, BEDROCK_QUOTA_DAY, BEDROCK_QUOTA_WEEK
#
# Install: set in ~/.claude/settings.json:
#   "statusLine": { "type": "command", "command": "bash <path-to-this-script>" }

input=$(cat)

model=$(echo "$input" | jq -r '.model.display_name // "Claude"')
model_id=$(echo "$input" | jq -r '.model.id // ""')
cost_usd=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
ctx_size=$(echo "$input" | jq -r '.context_window.context_window_size // 0')
used_pct=$(echo "$input" | jq -r '.context_window.used_percentage // 0')

ctx_current=$(echo "$input" | jq -r '
  .context_window.current_usage |
  ((.input_tokens // 0) + (.cache_read_input_tokens // 0) + (.cache_creation_input_tokens // 0))
')

is_bedrock=false
if echo "$model_id" | grep -qE '^(eu|us)\.|\.anthropic\.' 2>/dev/null; then
  is_bedrock=true
fi

format_tokens() {
  local n=$1
  if [ "$n" -ge 1000000 ]; then
    printf "%.1fM" "$(echo "scale=2; $n / 1000000" | bc)"
  elif [ "$n" -ge 1000 ]; then
    printf "%.0fk" "$(echo "scale=1; $n / 1000" | bc)"
  else
    printf "%d" "$n"
  fi
}

make_bar() {
  local pct=${1:-0}
  local width=${2:-20}
  local filled=$(( (pct * width + 50) / 100 ))
  [ "$filled" -gt "$width" ] && filled=$width
  local empty=$((width - filled))
  local bar=""
  for ((i=0; i<filled; i++)); do bar+="█"; done
  for ((i=0; i<empty; i++));  do bar+="░"; done
  printf '%s' "$bar"
}

# ── Quota indicator (Bedrock only) ────────────────────────────
# Reads the cache file written by the SessionStart hook.
# Limits come from CloudWatch (published by Lambda), with env var fallback.
get_quota_indicator() {
  [ "$is_bedrock" = true ] || return

  local cache="/tmp/bedrock-quota-cache-$(whoami).json"
  [ -f "$cache" ] || return

  local cost_3h cost_day cost_week limit_3h limit_day limit_week

  # Read spend and limits from cache (limits may be null if Lambda hasn't published them yet)
  cost_3h=$(jq -r '.cost_3h // 0' "$cache" 2>/dev/null)       || return
  cost_day=$(jq -r '.cost_day // 0' "$cache" 2>/dev/null)      || return
  cost_week=$(jq -r '.cost_week // 0' "$cache" 2>/dev/null)    || return

  limit_3h=$(jq -r '.limit_3h // empty' "$cache" 2>/dev/null)
  limit_day=$(jq -r '.limit_day // empty' "$cache" 2>/dev/null)
  limit_week=$(jq -r '.limit_week // empty' "$cache" 2>/dev/null)

  # Fallback to env vars, then to Terraform defaults
  limit_3h=${limit_3h:-${BEDROCK_QUOTA_3H:-6.00}}
  limit_day=${limit_day:-${BEDROCK_QUOTA_DAY:-15.00}}
  limit_week=${limit_week:-${BEDROCK_QUOTA_WEEK:-50.00}}

  # Calculate percentages
  local pct_3h pct_day pct_week
  pct_3h=$(awk "BEGIN { l=$limit_3h; printf \"%.0f\", (l > 0 ? ($cost_3h / l) * 100 : 0) }")
  pct_day=$(awk "BEGIN { l=$limit_day; printf \"%.0f\", (l > 0 ? ($cost_day / l) * 100 : 0) }")
  pct_week=$(awk "BEGIN { l=$limit_week; printf \"%.0f\", (l > 0 ? ($cost_week / l) * 100 : 0) }")

  # Find the highest percentage to determine alert level
  local max_pct=$pct_3h
  [ "$pct_day" -gt "$max_pct" ] 2>/dev/null && max_pct=$pct_day
  [ "$pct_week" -gt "$max_pct" ] 2>/dev/null && max_pct=$pct_week

  # Only show quota section if any window is at 40%+ (keep status line clean when low)
  if [ "$max_pct" -lt 40 ]; then
    return
  fi

  # Build indicator — show all three windows
  local icon
  if [ "$max_pct" -ge 100 ]; then
    icon="🚫"
  elif [ "$max_pct" -ge 80 ]; then
    icon="🔴"
  elif [ "$max_pct" -ge 50 ]; then
    icon="🟡"
  else
    icon="🟢"
  fi

  # Format: 3h:62% day:45% wk:28%  (only show windows at 20%+)
  local parts=""
  [ "$pct_3h" -ge 20 ] 2>/dev/null && parts="${parts}3h:${pct_3h}% "
  [ "$pct_day" -ge 20 ] 2>/dev/null && parts="${parts}day:${pct_day}% "
  [ "$pct_week" -ge 20 ] 2>/dev/null && parts="${parts}wk:${pct_week}%"

  # Trim trailing space
  parts=$(echo "$parts" | sed 's/ *$//')

  printf '%s %s' "$icon" "$parts"
}

# ── Render ────────────────────────────────────────────────────

ctx_pct=$(printf "%.0f" "$used_pct")
ctx_bar=$(make_bar "$ctx_pct" 20)
ctx_label="$(format_tokens "$ctx_current")/$(format_tokens "$ctx_size")"

if [ "$is_bedrock" = true ]; then
  cost_str=$(printf "$%.2f" "$cost_usd")
  quota=$(get_quota_indicator)

  if [ -n "$quota" ]; then
    printf '%s │ API %s │ %s │ %s %d%% %s\n' "$model" "$cost_str" "$quota" "$ctx_bar" "$ctx_pct" "$ctx_label"
  else
    printf '%s │ API %s │ %s %d%% %s\n' "$model" "$cost_str" "$ctx_bar" "$ctx_pct" "$ctx_label"
  fi
else
  printf '%s │ Pro │ %s %d%% %s\n' "$model" "$ctx_bar" "$ctx_pct" "$ctx_label"
fi
