#!/bin/bash
# Installs a live Claude Code status line:
#   ● branch │ Session: id │ model │ ctx ■■■ 32% │ 5h ■ 4% ↻03:20 │ wk ■■■■■ 65% │ Est. usage: $6.44
#
# What it changes (nothing else):
#   1. Writes ~/.claude/statusline-command.sh (backs up an existing one first)
#   2. Sets "statusLine" in ~/.claude/settings.json (backs up the file first; other settings are kept)
# It does not touch your terminal, fonts or shell config.
set -euo pipefail

DIR="$HOME/.claude"
SCRIPT="$DIR/statusline-command.sh"
SETTINGS="$DIR/settings.json"
STAMP=$(date +%Y%m%d-%H%M%S)
mkdir -p "$DIR"

# 1. The status line script
[ -f "$SCRIPT" ] && cp "$SCRIPT" "$SCRIPT.bak-$STAMP" && echo "Backed up old script → $SCRIPT.bak-$STAMP"
cat > "$SCRIPT" <<'STATUSLINE_EOF'
#!/bin/bash
# Claude Code status line (one line), re-run every second via statusLine.refreshInterval:
#   ● branch │ Session: id │ model │ ctx ■■  15% │ 5h ■■■  25% ↻01:40 │ wk ■■■■■  65% │ Est. usage: $0.10
input=$(cat)
US=$'\x1f'

fields='[.workspace.current_dir // .cwd // "", .model.display_name // "", .session_id // "",
  .cost.total_cost_usd // "", .context_window.used_percentage // "",
  .rate_limits.five_hour.used_percentage // "", .rate_limits.five_hour.resets_at // "",
  .rate_limits.seven_day.used_percentage // ""]'
if command -v jq >/dev/null 2>&1; then
  raw=$(echo "$input" | jq -r "$fields | map(tostring) | join(\"$US\")" 2>/dev/null)
else
  raw=$(echo "$input" | python3 -I -c '
import sys, json
d = json.load(sys.stdin)
def g(p):
    v = d
    for k in p.split("."):
        v = v.get(k) if isinstance(v, dict) else None
    return "" if v is None else str(v)
vals = [g(p) for p in ["workspace.current_dir", "model.display_name", "session_id",
        "cost.total_cost_usd", "context_window.used_percentage", "rate_limits.five_hour.used_percentage",
        "rate_limits.five_hour.resets_at", "rate_limits.seven_day.used_percentage"]]
if not vals[0]: vals[0] = g("cwd")
print("\x1f".join(vals))' 2>/dev/null)
fi
IFS="$US" read -r cwd model sid cost ctx five five_reset week <<< "$raw"
[ -z "$cwd" ] && cwd=$(pwd)

now=$(date +%s)
E=$'\033'
DIM="$E[2m"; RESET="$E[0m"
sep=" ${DIM}│${RESET} "
BAR_WIDTH=8

# Level colour: green <50%, yellow 50-79%, orange 80-89%, red 90-94%, bright red 95%+
level() {
  local n=$1
  if   [ "$n" -ge 95 ]; then echo 196
  elif [ "$n" -ge 90 ]; then echo 203
  elif [ "$n" -ge 80 ]; then echo 208
  elif [ "$n" -ge 50 ]; then echo 185
  else echo 41; fi
}
# Lighter shade of each level colour, used for the moving shine
glow() { case $1 in 41) echo 121 ;; 185) echo 229 ;; 208) echo 222 ;; 203) echo 217 ;; *) echo 210 ;; esac; }

# Bar of centred squares (■) on a dark track, vertically centred on the text. Animation, one frame per refresh:
# a light shine sweeps across the fill, and the leading edge breathes bright/dim.
# At 95%+ the whole fill blinks to grab attention.
bar() {
  local n=$1 c g cells i shine out="" ch
  c=$(level "$n"); g=$(glow "$c")
  cells=$(( (n * BAR_WIDTH + 50) / 100 ))
  [ "$n" -gt 0 ] && [ "$cells" -eq 0 ] && cells=1
  [ "$cells" -gt "$BAR_WIDTH" ] && cells=$BAR_WIDTH
  shine=$(( now % (cells + 3) ))
  for ((i = 0; i < cells; i++)); do
    ch=$c
    if [ "$n" -ge 95 ]; then [ $((now % 2)) -eq 0 ] && ch=$g
    elif [ "$i" -eq "$shine" ]; then ch=$g
    elif [ "$i" -eq $((cells - 1)) ]; then [ $((now % 2)) -eq 0 ] && ch=$g; fi
    out+="$E[38;5;${ch}m■"
  done
  for ((i = cells; i < BAR_WIDTH; i++)); do out+="$E[38;5;236m■"; done
  printf '%s%s' "$out" "$RESET"
}

# resets_at (epoch seconds/ms or ISO-8601) -> "01:40" (hh:mm left)
until_reset() {
  local v="$1" epoch s
  if [[ "$v" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
    epoch=${v%%.*}; [ "${#epoch}" -gt 11 ] && epoch=$((epoch / 1000))
  else
    epoch=$(python3 -I -c 'import sys,datetime; print(int(datetime.datetime.fromisoformat(sys.argv[1].replace("Z","+00:00")).timestamp()))' "$v" 2>/dev/null) || return
  fi
  s=$((epoch - now)); [ "$s" -lt 0 ] && s=0
  printf '%02d:%02d' $((s / 3600)) $((s % 3600 / 60))
}

# ● branch (folder name outside a git repo); the dot pulses to show the session is live
branch=$(git --no-optional-locks -C "$cwd" symbolic-ref --short HEAD 2>/dev/null \
  || git --no-optional-locks -C "$cwd" rev-parse --short HEAD 2>/dev/null)
dot=$([ $((now % 2)) -eq 0 ] && echo 41 || echo 29)
out="$E[38;5;${dot}m●${RESET} ${branch:-$(basename "$cwd")}"

[ -n "$sid" ]   && out+="${sep}Session: ${sid:0:8}"
[ -n "$model" ] && out+="${sep}${model}"

# label ■■■■■ N% — bar and number share the level colour
seg() { local n; n=$(printf '%.0f' "$2"); printf '%s %s %s%3s%%%s' "$1" "$(bar "$n")" "$E[38;5;$(level "$n")m" "$n" "$RESET"; }

[ -n "$ctx" ]  && out+="${sep}$(seg ctx "$ctx")"
if [ -n "$five" ]; then
  out+="${sep}$(seg 5h "$five")"
  [ -n "$five_reset" ] && r=$(until_reset "$five_reset") && [ -n "$r" ] && out+=" ${DIM}↻${r}${RESET}"
fi
[ -n "$week" ] && out+="${sep}$(seg wk "$week")"

[ -n "$cost" ] && out+="${sep}Est. usage: \$$(printf '%.2f' "$cost")"

printf '%s' "$out"
STATUSLINE_EOF
chmod +x "$SCRIPT"
echo "✓ Wrote $SCRIPT"

# 2. settings.json → statusLine (refreshInterval 1 = update every second)
[ -f "$SETTINGS" ] || echo '{}' > "$SETTINGS"
cp "$SETTINGS" "$SETTINGS.bak-$STAMP"
if command -v jq >/dev/null 2>&1; then
  jq --arg cmd "bash $SCRIPT" '.statusLine = {type: "command", command: $cmd, refreshInterval: 1}' \
    "$SETTINGS" > "$SETTINGS.tmp" && mv "$SETTINGS.tmp" "$SETTINGS"
elif command -v python3 >/dev/null 2>&1; then
  python3 -I - "$SETTINGS" "bash $SCRIPT" <<'PY'
import json, sys
path, cmd = sys.argv[1], sys.argv[2]
with open(path) as f: data = json.load(f)
data["statusLine"] = {"type": "command", "command": cmd, "refreshInterval": 1}
with open(path, "w") as f: json.dump(data, f, indent=2); f.write("\n")
PY
else
  echo "Couldn't find jq or python3. Add this to $SETTINGS yourself:"
  echo "  \"statusLine\": {\"type\": \"command\", \"command\": \"bash $SCRIPT\", \"refreshInterval\": 1}"
  exit 1
fi
echo "✓ Updated $SETTINGS (backup: $SETTINGS.bak-$STAMP)"

# 3. Test with sample data
now=$(date +%s)
echo
echo "Preview with sample data:"
printf '%s' "{\"session_id\":\"1fb4ade2-test\",\"model\":{\"display_name\":\"Opus 5.5\"},\"workspace\":{\"current_dir\":\"$PWD\"},\"cost\":{\"total_cost_usd\":6.44},\"context_window\":{\"used_percentage\":32},\"rate_limits\":{\"five_hour\":{\"used_percentage\":4,\"resets_at\":$((now + 12000))},\"seven_day\":{\"used_percentage\":65}}}" \
  | bash "$SCRIPT"
echo
echo
echo "Done. It appears at the bottom of Claude Code within a second (bars show after the first reply)."
echo "Undo: restore $SETTINGS.bak-$STAMP"
