#!/usr/bin/env bash
# Claude Code statusline v2 — Aria
# Receives Claude Code's session JSON on stdin. Read-only display; must never
# crash the bar, so every field degrades gracefully when absent.
#
# Layout (compact, "nicht überladen"):
#   {mode-dot} {mode} · ⏱ {live} · {model} · {dir} · {branch} · 🧠 {brain}
# Optional prefix: ⚠200k+ when the context window is near full.
set -uo pipefail

input=$(cat)

j() { printf '%s' "$input" | python3 -c "import sys,json
try: d=json.load(sys.stdin)
except Exception: sys.exit(0)
$1" 2>/dev/null || true; }

model=$(j "print(d.get('model',{}).get('display_name','') or '')")
cwd=$(j "print(d.get('workspace',{}).get('current_dir','') or d.get('cwd','') or '')")
dur_ms=$(j "print(int(d.get('cost',{}).get('total_duration_ms',0) or 0))")
over200k=$(j "print('1' if d.get('exceeds_200k_tokens') else '')")

# --- Aria autonomy mode (assist/auto/yolo) from state file ---
mode=$(cat /root/aria/state/mode 2>/dev/null | tr -d '[:space:]' || echo "")
case "$mode" in
  assist) dot="🔵" ;;
  auto)   dot="🟢" ;;
  yolo)   dot="🔴" ;;
  *)      dot="⚪" ; mode="${mode:-?}" ;;
esac

# --- Effort / mode badge (Aria-maintained convention) ---
# Claude Code's statusLine JSON does NOT expose the effort tier or plan-mode,
# so these can't be auto-detected. Aria writes /root/aria/state/effort when
# Kais declares a mode (e.g. "ultracode, xhigh, mit workflows"). Absent file =
# no badge shown (honest: we don't guess).
effort=$(cat /root/aria/state/effort 2>/dev/null | head -c 40 | tr -d '\n' || echo "")

# --- Live session duration (from cost.total_duration_ms) ---
live=""
if [ "${dur_ms:-0}" -gt 0 ] 2>/dev/null; then
  s=$(( dur_ms / 1000 )); h=$(( s / 3600 )); m=$(( (s % 3600) / 60 ))
  if [ "$h" -gt 0 ]; then live="${h}h${m}m"; else live="${m}m"; fi
fi

# --- Git branch (if cwd is a repo) ---
branch=""
if [ -n "$cwd" ] && git -C "$cwd" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  branch=$(git -C "$cwd" branch --show-current 2>/dev/null || echo "")
fi

# --- Brain freshness (relative time of last vault commit) ---
brain=""
if [ -d /root/aria/brain/.git ]; then
  brain=$(git -C /root/aria/brain log -1 --format='%cr' 2>/dev/null \
    | sed -E 's/ ago//; s/^a /1 /; s/^an /1 /; s/ seconds?/s/; s/ minutes?/m/; s/ hours?/h/; s/ days?/d/; s/ weeks?/w/; s/ //g')
fi

# --- Compose ---
parts=()
[ -n "$mode" ]   && parts+=("${dot} ${mode}")
[ -n "$effort" ] && parts+=("⚡ ${effort}")
[ -n "$live" ]   && parts+=("⏱ ${live}")
[ -n "$model" ]  && parts+=("$model")
[ -n "$cwd" ]    && parts+=("$(basename "$cwd")")
[ -n "$branch" ] && parts+=("$branch")
[ -n "$brain" ]  && parts+=("🧠 ${brain}")

# Join with " · ". Do NOT use IFS=' · ' — bash joins on the first IFS char only.
line=""
for p in "${parts[@]}"; do
  if [ -z "$line" ]; then line="$p"; else line="${line} · ${p}"; fi
done
[ -n "$over200k" ] && line="⚠ 200k+ · ${line}"
printf '%s' "$line"

exit 0
