#!/bin/bash
# slurp stdin without forking `cat` (read -d '' returns 1 at EOF, which is fine)
IFS= read -r -d '' input

# --- ANSI helpers ---
RESET=$'\033[0m'
DIM=$'\033[2m'
BLUE=$'\033[34m'
CYAN=$'\033[36m'
BOLD_YELLOW=$'\033[1;33m'
BOLD_RED=$'\033[1;31m'
BOLD_REV_RED=$'\033[1;7;31m'
BOLD_MAGENTA=$'\033[1;35m'
REVERSE=$'\033[7m'

# colorize_quota: two orthogonal signals on a rate-limit window.
#   colour        = forecast. Margin M = remaining quota(%) - remaining time(% of window).
#                   M >= 0 means the current burn rate lands at or under 100% by reset;
#                   M < 0 means we hit the wall early, by roughly |M|% of the window.
#                   -5 is a dead zone: early in a window M is slightly negative just from noise.
#   reverse block = present fact. >=90% used means "out of quota right now", regardless of
#                   how soon it resets, so it must not be masked by a healthy forecast.
# Falls back to absolute thresholds when resets_at is missing (no window to reason about).
colorize_quota() {
  local used=$1 left=$2 window=$3 text=$4 colour="" rem_pct margin
  if [ -n "$left" ]; then
    rem_pct=$(( 100 * left / window ))
    [ "$rem_pct" -gt 100 ] && rem_pct=100
    margin=$(( (100 - used) - rem_pct ))
    if   [ "$margin" -lt -20 ]; then colour=$BOLD_RED
    elif [ "$margin" -lt  -5 ]; then colour=$BOLD_YELLOW
    fi
  else
    if   [ "$used" -ge 80 ]; then colour=$BOLD_RED
    elif [ "$used" -ge 50 ]; then colour=$BOLD_YELLOW
    fi
  fi

  if [ "$used" -ge 90 ]; then
    printf '%s%s %s %s' "$colour" "$REVERSE" "$text" "$RESET"
  elif [ -n "$colour" ]; then
    printf '%s%s%s' "$colour" "$text" "$RESET"
  else
    printf '%s' "$text"
  fi
}

# colorize_ctx: context has a 3rd tier -> >=90 reverse red block, >=80 bold red, >=60 bold yellow
colorize_ctx() {
  local val=$1 text=$2
  if [ "$val" -ge 90 ]; then
    printf '%s %s %s' "$BOLD_REV_RED" "$text" "$RESET"
  elif [ "$val" -ge 80 ]; then
    printf '%s%s%s' "$BOLD_RED" "$text" "$RESET"
  elif [ "$val" -ge 60 ]; then
    printf '%s%s%s' "$BOLD_YELLOW" "$text" "$RESET"
  else
    printf '%s' "$text"
  fi
}

# --- Single jq pass: all fields joined by US (0x1f), which cannot appear in the values ---
IFS=$'\x1f' read -r -d '' \
  CUR_DIR NAME MODEL EFFORT CTX_PCT FIVE_H WEEK RESETS_AT WEEK_RESETS_AT \
  < <(jq -j '[
        .workspace.current_dir             // "",
        .session_name                      // "",
        .model.display_name                // "",
        .effort.level                      // "",
        .context_window.used_percentage    // 0,
        .rate_limits.five_hour.used_percentage  // "",
        .rate_limits.seven_day.used_percentage  // "",
        .rate_limits.five_hour.resets_at        // "",
        .rate_limits.seven_day.resets_at        // ""
      ] | map(tostring) | join("\u001f")' <<< "$input") || true

# --- Label: session name if set, else current directory ---
DIR="${CUR_DIR%/}"
DIR="${DIR##*/}"
LABEL="${NAME:-$DIR}"

# --- Model + effort ---
MODEL="${MODEL/ context/}"
if [ -n "$EFFORT" ]; then
  case "$EFFORT" in
    low)    EFFORT_STR="${BLUE}${EFFORT}${RESET}" ;;
    medium) EFFORT_STR="${CYAN}${EFFORT}${RESET}" ;;
    xhigh)  EFFORT_STR="${BOLD_YELLOW}${EFFORT}${RESET}" ;;
    max)    EFFORT_STR="${BOLD_MAGENTA}${EFFORT}${RESET}" ;;
    *)      EFFORT_STR="$EFFORT" ;;
  esac
  MODEL="$MODEL, $EFFORT_STR"
fi

# --- Metrics ---
CTX_PCT="${CTX_PCT%%.*}"   # truncate, matching the previous `cut -d. -f1`
CTX_PCT="${CTX_PCT:-0}"

NOW=${EPOCHSECONDS:-$(date +%s)}

is_num() { case "$1" in ''|*[!0-9]*) return 1 ;; *) return 0 ;; esac; }

# --- Cross-session quota cache -----------------------------------------------
# Claude Code only refreshes rate_limits on an API exchange: an idle session keeps
# serving the same snapshot forever. Measured across 10 open sessions: up to 5.8 days
# of drift, one of them reporting 7d at 9% while the true figure was 27%. Since quotas
# are account-wide, whichever session holds the freshest snapshot publishes it and the
# others read it.
#
# Freshness key = five_hour.resets_at * 1000 + five_hour.used_percentage:
#   resets_at increases from one 5h window to the next; within a window used_% is
#   monotonically increasing. Verified empirically -- sorting real snapshots by this
#   key makes the 7-day series strictly monotonic, including the tie-break case.
QUOTA_CACHE="$HOME/.claude/statusline-quota"

CUR_5U=""; CUR_7U=""
[ -n "$FIVE_H" ] && printf -v CUR_5U '%.0f' "$FIVE_H"
[ -n "$WEEK" ]   && printf -v CUR_7U '%.0f' "$WEEK"

CUR_KEY=0
is_num "$CUR_5U" && is_num "$RESETS_AT" && CUR_KEY=$(( RESETS_AT * 1000 + CUR_5U ))

# A malformed cache line scores 0 and simply loses, so corruption self-heals.
CACHE_KEY=0
C_5U=""; C_5R=""; C_7U=""; C_7R=""
if [ -r "$QUOTA_CACHE" ]; then
  IFS=$'\t' read -r C_5U C_5R C_7U C_7R < "$QUOTA_CACHE" || true
  is_num "$C_5U" && is_num "$C_5R" && CACHE_KEY=$(( C_5R * 1000 + C_5U ))
fi

if [ "$CACHE_KEY" -gt "$CUR_KEY" ]; then
  # Someone else saw a newer snapshot -- adopt it wholesale (it is one coherent read).
  FIVE_H="$C_5U"; RESETS_AT="$C_5R"
  WEEK="$C_7U";   WEEK_RESETS_AT="$C_7R"
elif [ "$CUR_KEY" -gt "$CACHE_KEY" ]; then
  # We are ahead -- publish. Equal keys write nothing: ~40 statusline runs/minute
  # across all sessions, and all but a handful are exact repeats.
  # The cache is rewritten whole, never appended to, so it stays one line forever.
  # Only the temp file could leak, if we were killed between the write and the mv --
  # plausible here, since a statusline that overruns its timeout gets signalled.
  TMP="$QUOTA_CACHE.$$"
  trap 'rm -f "$TMP"' EXIT
  trap 'rm -f "$TMP"; exit 130' INT TERM HUP
  if printf '%s\t%s\t%s\t%s\n' "$CUR_5U" "$RESETS_AT" "$CUR_7U" "$WEEK_RESETS_AT" > "$TMP" 2>/dev/null; then
    mv -f "$TMP" "$QUOTA_CACHE" 2>/dev/null || rm -f "$TMP" 2>/dev/null
  fi
fi

# Past resets_at the retained value describes a window that no longer exists -- but the
# staleness is itself informative. An elapsed five_hour.resets_at means no local session
# has hit the API since (any of them would have published within one refresh), and a 5h
# window only starts on a message -- verified: resets_at lands on :00/:20/:30/:50, so it
# tracks first-message time, not a fixed grid. Hence no window is running and usage is
# genuinely 0. The same silence carries the 7d figure: nothing was spent, so the
# remembered value still holds. Both get '~' -- deduced, not measured.
# Colours stay on: these numbers are trustworthy, so a 90% week must still shout.
# Sole assumption: nothing spent off this machine (claude.ai, the app, another box).
TILDE_5=""; TILDE_7=""
if is_num "$RESETS_AT" && [ "$RESETS_AT" -le "$NOW" ]; then
  FIVE_H=0; RESETS_AT=""; TILDE_5="~"   # no active window -> nothing to count down to
  [ -n "$WEEK" ] && TILDE_7="~"
fi
if is_num "$WEEK_RESETS_AT" && [ "$WEEK_RESETS_AT" -le "$NOW" ]; then
  WEEK=0; WEEK_RESETS_AT=""; TILDE_7="~"
fi

# FIVE_LEFT / WEEK_LEFT: seconds until reset, clamped at 0. Empty only when resets_at is
# absent, which is what tells colorize_quota to fall back to absolute thresholds.
REMAINING=""
FIVE_LEFT=""
if is_num "$RESETS_AT"; then
  FIVE_LEFT=$(( RESETS_AT - NOW ))
  [ "$FIVE_LEFT" -lt 0 ] && FIVE_LEFT=0
  if [ "$FIVE_LEFT" -gt 0 ]; then
    HH=$(( FIVE_LEFT / 3600 ))
    MM=$(( (FIVE_LEFT % 3600) / 60 ))
    printf -v REMAINING ' %s(%dh%02d)%s' "$DIM" "$HH" "$MM" "$RESET"
  fi
fi

WEEK_REMAINING=""
WEEK_LEFT=""
if is_num "$WEEK_RESETS_AT"; then
  WEEK_LEFT=$(( WEEK_RESETS_AT - NOW ))
  [ "$WEEK_LEFT" -lt 0 ] && WEEK_LEFT=0
  if [ "$WEEK_LEFT" -gt 0 ]; then
    DD=$(( WEEK_LEFT / 86400 ))
    HH=$(( (WEEK_LEFT % 86400) / 3600 ))
    if [ "$DD" -gt 0 ]; then
      WEEK_REMAINING=" ${DIM}(${DD}d ${HH}h)${RESET}"
    else
      # Under a day, switch to the 5h window's HhMM format. Truncating to whole hours
      # would render the final hour as "(0h)", which reads as "already reset" while up
      # to 59 minutes of waiting remain -- the one error this display must not make.
      MM=$(( (WEEK_LEFT % 3600) / 60 ))
      printf -v WEEK_REMAINING ' %s(%dh%02d)%s' "$DIM" "$HH" "$MM" "$RESET"
    fi
  fi
fi

# Context: warn >=60 (yellow), crit >=80 (red), >=90 (reverse red block)
CTX_STR="Ctx: $(colorize_ctx "$CTX_PCT" "${CTX_PCT}%")"

LIMITS=""
if [ -n "$FIVE_H" ]; then
  printf -v FIVE_INT '%.0f' "$FIVE_H"
  LIMITS=" | $(colorize_quota "$FIVE_INT" "$FIVE_LEFT" 18000 "${TILDE_5}${FIVE_INT}%")${REMAINING}"
fi
if [ -n "$WEEK" ]; then
  printf -v WEEK_INT '%.0f' "$WEEK"
  LIMITS="$LIMITS | 7d: $(colorize_quota "$WEEK_INT" "$WEEK_LEFT" 604800 "${TILDE_7}${WEEK_INT}%")${WEEK_REMAINING}"
fi
printf '%s%s | %s | %s\n' "$CTX_STR" "$LIMITS" "$MODEL" "$LABEL"
