#!/usr/bin/env bash
# ~/.claude/statusline-command.sh
# Statusline for Claude Code: folder · branch · model · context bar
# Input: JSON via stdin

input=$(cat)

# --- Data extraction ---
cwd=$(echo "$input" | jq -r '.workspace.current_dir // .cwd // ""')
folder=$(basename "$cwd")

model=$(echo "$input" | jq -r '.model.display_name // .model.id // "?"')

used_pct=$(echo "$input" | jq -r '.context_window.used_percentage // empty')

# Context window size label (e.g. "200k", "1M")
ctx_size=$(echo "$input" | jq -r '.context_window.context_window_size // 0')
if   [ "$ctx_size" -ge 1000000 ] 2>/dev/null; then ctx_label="$(( ctx_size / 1000000 ))M"
elif [ "$ctx_size" -ge 1000 ]    2>/dev/null; then ctx_label="$(( ctx_size / 1000 ))k"
else ctx_label="${ctx_size}"
fi

# Git branch (fast, skips optional locks)
branch=""
if [ -n "$cwd" ] && [ -d "$cwd/.git" ] || git -C "$cwd" rev-parse --git-dir >/dev/null 2>&1; then
  branch=$(GIT_OPTIONAL_LOCKS=0 git -C "$cwd" symbolic-ref --short HEAD 2>/dev/null \
           || GIT_OPTIONAL_LOCKS=0 git -C "$cwd" rev-parse --short HEAD 2>/dev/null)
fi

# --- Progress bar (10 cells) ---
BAR_FULL="▰"
BAR_EMPTY="▱"
bar=""
if [ -n "$used_pct" ]; then
  filled=$(echo "$used_pct" | awk '{printf "%d", ($1 / 10 + 0.5)}')
  [ "$filled" -gt 10 ] && filled=10
  [ "$filled" -lt 0  ] && filled=0
  empty=$(( 10 - filled ))
  for _ in $(seq 1 $filled);  do bar="${bar}${BAR_FULL}";  done
  for _ in $(seq 1 $empty);   do bar="${bar}${BAR_EMPTY}"; done
  pct_label="$(printf '%.0f' "$used_pct")%"
else
  bar="▱▱▱▱▱▱▱▱▱▱"
  pct_label="?"
fi

# --- Color support ---
if [ -t 1 ] || [ "${COLORTERM:-}" != "" ] || [ "${TERM:-}" != "dumb" ]; then
  C_RESET="\033[0m"
  C_FOLDER="\033[1;36m"   # bold cyan
  C_BRANCH="\033[1;33m"   # bold yellow
  C_MODEL="\033[1;35m"    # bold magenta
  C_BAR="\033[1;32m"      # bold green
  C_DIM="\033[2m"         # dim (for separators)
else
  C_RESET=""; C_FOLDER=""; C_BRANCH=""; C_MODEL=""; C_BAR=""; C_DIM=""
fi

SEP="${C_DIM} · ${C_RESET}"

# --- Assemble line ---
line="${C_FOLDER}${folder}${C_RESET}"

if [ -n "$branch" ]; then
  line="${line}${SEP}${C_BRANCH}${branch}${C_RESET}"
fi

# Model + optional context window size
if [ -n "$ctx_label" ] && [ "$ctx_label" != "0" ]; then
  line="${line}${SEP}${C_MODEL}${model} [${ctx_label}]${C_RESET}"
else
  line="${line}${SEP}${C_MODEL}${model}${C_RESET}"
fi

line="${line}${SEP}${C_BAR}${bar}${C_RESET} ${pct_label}"

printf "%b\n" "$line"
