#!/usr/bin/env bash
# Claude Code status line: shows current model + session usage.
# Receives session JSON on stdin.
export LC_ALL=C  # jq emits dot-decimal numbers; printf %.4f chokes on them under cs_CZ

input=$(cat)

# Pull every field in one jq pass instead of re-parsing per field. Fields are
# joined with the ASCII unit separator (0x1f): unlike tab, it is NOT an IFS
# whitespace char, so empty fields (e.g. a missing transcript_path) are preserved
# rather than collapsed — keeping the read var alignment intact.
# Order below must match the read var list exactly.
IFS=$'\037' read -r model model_id cost added removed dur_ms big transcript cwd week < <(
  printf '%s' "$input" | jq -r '[
    .model.display_name // "?",
    .model.id // "",
    .cost.total_cost_usd // 0,
    .cost.total_lines_added // 0,
    .cost.total_lines_removed // 0,
    .cost.total_duration_ms // 0,
    .exceeds_200k_tokens // false,
    .transcript_path // "",
    .workspace.current_dir // .cwd // "",
    .rate_limits.seven_day.used_percentage // ""
  ] | map(tostring) | join("")'
)

# ANSI colors reused across segments.
grn=$'\033[32m'; ylw=$'\033[33m'; red=$'\033[31m'; rst=$'\033[0m'

# Working dir + git branch — a live tripwire for the "cwd silently resets to the
# main checkout" hazard: if this shows the main checkout / develop when you expect
# a worktree+feature branch, context drifted. • = uncommitted changes present.
loc=""
if [ -n "$cwd" ]; then
  dir=${cwd##*/}
  branch=$(git -C "$cwd" branch --show-current 2>/dev/null)
  # detached HEAD → fall back to short SHA
  [ -z "$branch" ] && branch=$(git -C "$cwd" rev-parse --short HEAD 2>/dev/null)
  if [ -n "$branch" ]; then
    [ ${#branch} -gt 28 ] && branch="${branch:0:27}…"
    dirt=""
    [ -n "$(git -C "$cwd" status --porcelain 2>/dev/null | head -1)" ] && dirt="•"
    loc=" | 📁 ${dir} 🌿 ${branch}${dirt}"
  else
    loc=" | 📁 ${dir}"
  fi
fi

# Context-window usage %: sum input-side tokens from the latest assistant turn
# in the transcript. Denominator defaults to 200k, auto-bumping to 1M for
# long-context sessions; override with CC_CONTEXT_LIMIT.
pct=""
if [ -n "$transcript" ] && [ -f "$transcript" ]; then
  used=$(tail -n 200 "$transcript" 2>/dev/null \
    | jq -rs '[.[] | select((.message.usage // empty) | has("input_tokens")) | .message.usage]
        | last
        | (.input_tokens + (.cache_creation_input_tokens // 0) + (.cache_read_input_tokens // 0)) // 0' \
    2>/dev/null)
  used=${used:-0}
  if [ "$used" -gt 0 ] 2>/dev/null; then
    if   [ -n "$CC_CONTEXT_LIMIT" ];        then limit=$CC_CONTEXT_LIMIT
    elif [[ "$model_id" == *"[1m]"* ]];     then limit=1000000
    else                                         limit=200000
    fi
    p=$(( used * 100 / limit ))
    [ "$p" -gt 100 ] && p=100
    if   [ "$p" -lt 50 ]; then col=$'\033[32m'   # green  – plenty left
    elif [ "$p" -lt 80 ]; then col=$'\033[33m'   # yellow – getting full
    else                       col=$'\033[31m'   # red    – nearly full
    fi
    rst=$'\033[0m'
    pct=" | ${col}${p}%${rst}"
  fi
fi

# Weekly (7-day rolling) subscription limit consumed — Pro/Max only, and absent
# until the first API response of the session, so empty-guard it. resets_at is a
# rolling 7-day window, not a calendar week.
wk=""
if [ -n "$week" ]; then
  w=${week%.*}                       # drop decimals → integer for comparisons
  [ -z "$w" ] && w=0
  if   [ "$w" -lt 50 ]; then wcol=$'\033[32m'   # green  – room left
  elif [ "$w" -lt 80 ]; then wcol=$'\033[33m'   # yellow – watch it
  else                       wcol=$'\033[31m'   # red    – near weekly cap
  fi
  rst=$'\033[0m'
  wk=" | 📅 ${wcol}${w}%${rst}"
fi

# Format duration (ms) as Hh Mm Ss, dropping leading zero units.
total_s=$(( dur_ms / 1000 ))
h=$(( total_s / 3600 )); m=$(( (total_s % 3600) / 60 )); s=$(( total_s % 60 ))
if   [ "$h" -gt 0 ]; then dur="${h}h ${m}m"
elif [ "$m" -gt 0 ]; then dur="${m}m ${s}s"
else                      dur="${s}s"
fi

ctx=""
[ "$big" = "true" ] && ctx=" ⚠️ >200k"

delta="${grn}+${added}${rst}/${red}-${removed}${rst}"

printf '🤖 %s%s%s%s | ⏱️ %s | %s | $%.4f%s' \
  "$model" "$loc" "$pct" "$wk" "$dur" "$delta" "$cost" "$ctx"
