#!/bin/bash
# Claude Code status line — model | cost | api time | context % + autocompact threshold | folder + git branch
# From: https://intlo.com/news/claude-code-status-line
# Install: save as ~/.claude/statusline.sh, chmod +x, then point "statusLine.command" at it in ~/.claude/settings.json
input=$(cat)

j() { echo "$input" | jq -r "$1"; }

MODEL=$(j '.model.display_name // "?"')
COST=$(j '.cost.total_cost_usd // 0')
API_MS=$(j '.cost.total_api_duration_ms // 0')
DIR=$(j '.workspace.current_dir // ""')
PCT=$(j '.context_window.used_percentage // 0' | cut -d. -f1)
SIZE=$(j '.context_window.context_window_size // 200000')
IN=$(j '.context_window.total_input_tokens // 0')
OUT=$(j '.context_window.total_output_tokens // 0')

# Autocompact threshold — Claude Code compacts at roughly this share of the window.
# Override with AUTOCOMPACT_PCT in your shell env if you have tuned it.
AUTOCOMPACT_PCT=${AUTOCOMPACT_PCT:-80}
AUTOCOMPACT=$(( SIZE * AUTOCOMPACT_PCT / 100 ))
USED=$(( IN + OUT ))

# Colors
DIM='\033[2m'; RESET='\033[0m'
ORANGE='\033[38;5;214m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; CYAN='\033[36m'; BLUE='\033[34m'

# Context color by usage
if   [ "$PCT" -ge 85 ]; then CTX_C=$RED
elif [ "$PCT" -ge 60 ]; then CTX_C=$YELLOW
else CTX_C=$GREEN; fi

# Progress bar (10 cells)
FILLED=$(( PCT / 10 )); BAR=""
for i in $(seq 1 10); do
  if [ "$i" -le "$FILLED" ]; then BAR="${BAR}█"; else BAR="${BAR}░"; fi
done

# Git branch
BRANCH=""
if [ -n "$DIR" ] && git -C "$DIR" rev-parse --git-dir >/dev/null 2>&1; then
  BRANCH=$(git -C "$DIR" branch --show-current 2>/dev/null)
fi

fmt_k() { awk -v n="$1" 'BEGIN{ if (n>=1000000) printf "%.1fM", n/1000000; else if (n>=1000) printf "%.0fk", n/1000; else printf "%d", n }'; }
API_S=$(awk -v ms="$API_MS" 'BEGIN{printf "%.0fs", ms/1000}')
COST_F=$(awk -v c="$COST" 'BEGIN{printf "$%.2f", c}')

# Line 1: model, cost, api, context
printf "${ORANGE}%s${RESET} ${DIM}|${RESET} ${GREEN}%s${RESET} ${DIM}|${RESET} ${DIM}api:${RESET}%s ${DIM}|${RESET} ${CTX_C}%s %s%%${RESET} ${DIM}(%s/%s)${RESET} ${DIM}autocompact${RESET} ${BLUE}%s${RESET}\n" \
  "$MODEL" "$COST_F" "$API_S" "$BAR" "$PCT" "$(fmt_k "$USED")" "$(fmt_k "$SIZE")" "$AUTOCOMPACT"

# Line 2: folder + branch
printf "${CYAN}📁 %s${RESET}" "${DIR##*/}"
[ -n "$BRANCH" ] && printf " ${DIM}on${RESET} ${YELLOW} %s${RESET}" "$BRANCH"
printf "\n"
