#!/bin/sh
# Claude Code statusLine command（3行表示）
# 1行目: モデル名 | effort | ブランチ(またはフォルダ) | セッション変更行数
# 2行目: ctx | 5h(セッション) | 7d(全体・全モデル)
# 3行目: Fable週間使用率（オレンジ・最下段）
#
# 5h/7d(全体) と Fable専用の値は、Claude Code の statusLine stdin には含まれない
# （stdin の rate_limits はアカウント全体の集計のみでモデル別の内訳が無い）ため、
# 実機検証済みの公式使用量API (api.anthropic.com/api/oauth/usage) をKeychainの
# OAuthトークンで叩いて取得する。API呼び出しは高頻度描画に対してコスト/レイテンシが
# 問題になるため、60秒キャッシュ + バックグラウンド更新（描画はブロックしない）にする。
# API/トークン取得に失敗した場合は stdin の rate_limits（アカウント全体の5h/7d）に
# フォールバックし、Fable行は「Fable 7d: -」として表示を継続する（描画は落とさない）。

input=$(cat)

# --- モデル名 ---
model=$(echo "$input" | jq -r '.model.display_name // "Unknown"')

# --- effortレベル ---
effort=$(echo "$input" | jq -r '.effort.level // empty')

# --- コンテキスト使用率 ---
used_pct=$(echo "$input" | jq -r '.context_window.used_percentage // empty')

# --- レート制限 (stdin由来・フォールバック用。アカウント全体の集計値) ---
five_pct=$(echo "$input"   | jq -r '.rate_limits.five_hour.used_percentage // empty')
five_reset=$(echo "$input" | jq -r '.rate_limits.five_hour.resets_at // empty')
seven_pct=$(echo "$input"  | jq -r '.rate_limits.seven_day.used_percentage // empty')
seven_reset=$(echo "$input"| jq -r '.rate_limits.seven_day.resets_at // empty')

# --- 使用量API キャッシュ (session / weekly_all / Fable専用 weekly_scoped) ---
# トークンやAPIレスポンスはこのプロセス内でのみ扱い、echo・ログ出力はしない。
CACHE_DIR="$HOME/.claude/cache"
USAGE_CACHE="$CACHE_DIR/usage_api_cache.json"
USAGE_ATTEMPT="$CACHE_DIR/usage_api_cache.attempt"
mkdir -p "$CACHE_DIR" 2>/dev/null

need_refresh=1
if [ -f "$USAGE_ATTEMPT" ]; then
  last_attempt=$(stat -f %m "$USAGE_ATTEMPT" 2>/dev/null || stat -c %Y "$USAGE_ATTEMPT" 2>/dev/null || echo 0)
  now_ts=$(date +%s)
  attempt_age=$((now_ts - last_attempt))
  if [ "$attempt_age" -lt 60 ]; then
    need_refresh=0
  fi
fi

if [ "$need_refresh" -eq 1 ]; then
  (
    touch "$USAGE_ATTEMPT" 2>/dev/null
    _uapi_token=$(security find-generic-password -s "Claude Code-credentials" -w 2>/dev/null | python3 -c "
import sys, json
try:
    print(json.load(sys.stdin).get('claudeAiOauth', {}).get('accessToken', ''))
except Exception:
    print('')
" 2>/dev/null)
    if [ -n "$_uapi_token" ]; then
      _uapi_resp=$(curl -s --max-time 2 "https://api.anthropic.com/api/oauth/usage" \
        -H "Authorization: Bearer $_uapi_token" \
        -H "anthropic-beta: oauth-2025-04-20" 2>/dev/null)
      if [ -n "$_uapi_resp" ]; then
        _uapi_tmp="$USAGE_CACHE.tmp.$$"
        printf '%s' "$_uapi_resp" > "$_uapi_tmp" 2>/dev/null && mv -f "$_uapi_tmp" "$USAGE_CACHE" 2>/dev/null
      fi
    fi
    unset _uapi_token _uapi_resp
  ) >/dev/null 2>&1 &
fi

api_session_pct=""
api_weekly_all_pct=""
api_fable_pct=""
if [ -f "$USAGE_CACHE" ]; then
  api_session_pct=$(jq -r '.limits[]? | select(.kind=="session") | .percent // empty' "$USAGE_CACHE" 2>/dev/null | head -n1)
  api_weekly_all_pct=$(jq -r '.limits[]? | select(.kind=="weekly_all") | .percent // empty' "$USAGE_CACHE" 2>/dev/null | head -n1)
  api_fable_pct=$(jq -r '.limits[]? | select(.kind=="weekly_scoped" and .scope.model.display_name=="Fable") | .percent // empty' "$USAGE_CACHE" 2>/dev/null | head -n1)
fi

# 表示用: APIキャッシュがあればそれを優先、無ければ stdin の rate_limits にフォールバック
five_display_pct="${api_session_pct:-$five_pct}"
seven_display_pct="${api_weekly_all_pct:-$seven_pct}"

# --- gitブランチ / 作業フォルダ名 ---
cwd=$(echo "$input" | jq -r '.cwd // empty')
git_branch=""
folder_name=""
if [ -n "$cwd" ]; then
  git_branch=$(git -C "$cwd" symbolic-ref --short HEAD 2>/dev/null)
  folder_name=$(basename "$cwd")
fi

# --- セッション変更行数 (transcript から +/- 行を集計) ---
transcript=$(echo "$input" | jq -r '.transcript_path // empty')
added_lines=0
removed_lines=0
if [ -n "$transcript" ] && [ -f "$transcript" ]; then
  added_lines=$(python3 -c "
import re
try:
    data = open('$transcript').read()
    objs = re.findall(r'\"new_string\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"', data)
    print(sum(s.count('\\\\n') + 1 for s in objs if s))
except:
    print(0)
" 2>/dev/null)
  removed_lines=$(python3 -c "
import re
try:
    data = open('$transcript').read()
    objs = re.findall(r'\"old_string\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"', data)
    print(sum(s.count('\\\\n') + 1 for s in objs if s))
except:
    print(0)
" 2>/dev/null)
fi

# バー生成関数 (幅10マス)
make_bar() {
  pct="$1"
  filled=$(echo "$pct" | awk '{printf "%d", int($1/10 + 0.5)}')
  empty=$((10 - filled))
  bar=""
  i=0
  while [ $i -lt $filled ]; do bar="${bar}▓"; i=$((i+1)); done
  i=0
  while [ $i -lt $empty  ]; do bar="${bar}░"; i=$((i+1)); done
  printf "%s" "$bar"
}

# リセットまでの残り時間 ("Xm" / "XhYYm" / "XdYYh")
time_until() {
  reset_epoch="$1"
  if [ -z "$reset_epoch" ]; then return; fi
  now=$(date +%s)
  diff=$((reset_epoch - now))
  if [ $diff -le 0 ]; then
    printf "now"
    return
  fi
  d=$((diff / 86400))
  h=$(( (diff % 86400) / 3600 ))
  m=$(( (diff % 3600) / 60 ))
  if [ $d -gt 0 ]; then
    printf "%dd%02dh" "$d" "$h"
  elif [ $h -gt 0 ]; then
    printf "%dh%02dm" "$h" "$m"
  else
    printf "%dm" "$m"
  fi
}

# ANSI カラー
RESET="\033[0m"
BOLD="\033[1m"
CYAN="\033[36m"
MAGENTA="\033[35m"
DIM="\033[2m"
GREEN="\033[32m"
RED="\033[31m"
ORANGE="\033[38;5;214m"

# 色選択: 使用率に応じて変化
color_for_pct() {
  pct="$1"
  level=$(echo "$pct" | awk '{printf "%d", int($1)}')
  if [ "$level" -ge 85 ]; then
    printf "\033[31m"   # 赤
  elif [ "$level" -ge 60 ]; then
    printf "\033[33m"   # 黄
  else
    printf "\033[32m"   # 緑
  fi
}

# メーター1個分を出力 (ラベル / 使用率 / リセットepoch)
print_meter() {
  label="$1"; pct="$2"; reset_at="$3"
  if [ -z "$pct" ]; then return; fi
  bar=$(make_bar "$pct")
  col=$(color_for_pct "$pct")
  pct_int=$(echo "$pct" | awk '{printf "%.0f", $1}')
  printf "${DIM}%s${RESET} ${col}%s${RESET} ${col}%s%%${RESET}" "$label" "$bar" "$pct_int"
  remaining=$(time_until "$reset_at")
  if [ -n "$remaining" ]; then
    printf " ${DIM}(rst %s)${RESET}" "$remaining"
  fi
}

# ===== 1行目: モデル / effort / 場所 / diff =====

printf "${BOLD}${CYAN}%s${RESET}" "$model"

if [ -n "$effort" ]; then
  printf "  ${BOLD}%s${RESET}" "$effort"
fi

# 場所: ブランチがフォルダ名を含む(またはその逆)なら重複を避けてブランチのみ表示
if [ -n "$git_branch" ]; then
  case "$git_branch" in
    *"$folder_name"*) show_folder="" ;;
    *)
      case "$folder_name" in
        *"$git_branch"*) show_folder="" ;;
        *) show_folder="$folder_name" ;;
      esac
      ;;
  esac
  if [ -n "$show_folder" ]; then
    printf "  ${DIM}%s${RESET}" "$show_folder"
  fi
  printf "  ${MAGENTA}⎇%s${RESET}" "$git_branch"
elif [ -n "$folder_name" ]; then
  printf "  ${DIM}%s${RESET}" "$folder_name"
fi

if [ -n "$added_lines" ] && [ "$added_lines" != "0" ] 2>/dev/null; then
  printf "  ${GREEN}+%s${RESET}" "$added_lines"
  if [ -n "$removed_lines" ] && [ "$removed_lines" != "0" ] 2>/dev/null; then
    printf "${DIM}/${RESET}${RED}-%s${RESET}" "$removed_lines"
  fi
fi

printf "\n"

# ===== 2行目: ctx / 5h(セッション) / 7d(全体・全モデル) =====

first=1
for meter in ctx five seven; do
  case "$meter" in
    ctx)   label="ctx";      pct="$used_pct";          reset_at="" ;;
    five)  label="5h";       pct="$five_display_pct";  reset_at="$five_reset" ;;
    seven) label="7d(全体)"; pct="$seven_display_pct"; reset_at="$seven_reset" ;;
  esac
  if [ -z "$pct" ]; then continue; fi
  if [ $first -eq 0 ]; then printf "   "; fi
  print_meter "$label" "$pct" "$reset_at"
  first=0
done

printf "\n"

# ===== 3行目: Fable週間使用率（オレンジ・最下段） =====
# APIキャッシュが取得できていれば実測値、失敗時は "-" でフォールバック表示（描画は落とさない）

printf "${ORANGE}Fable 7d${RESET} "
if [ -n "$api_fable_pct" ]; then
  fable_bar=$(make_bar "$api_fable_pct")
  fable_col=$(color_for_pct "$api_fable_pct")
  fable_int=$(echo "$api_fable_pct" | awk '{printf "%.0f", $1}')
  printf "${fable_col}%s${RESET} ${fable_col}%s%%${RESET}" "$fable_bar" "$fable_int"
else
  printf "${DIM}-${RESET}"
fi
printf "\n"
