#!/usr/bin/env bash
input=$(cat)

CACHE_FILE="${HOME}/.claude/rate-limits-cache.json"
now=$(date +%s)

mapfile -d '' -t input_fields < <(printf '%s' "$input" | jq -j '
  [
    (if (.model.display_name // "" | length) > 0 then .model.display_name else .model.id end),
    .workspace.current_dir,
    (.workspace.current_dir // ""),
    (.context_window.used_percentage // ""),
    (.rate_limits.five_hour.used_percentage // ""),
    (.rate_limits.five_hour.resets_at // ""),
    (.rate_limits.seven_day.used_percentage // ""),
    (.rate_limits.seven_day.resets_at // "")
  ] | .[] | tostring, "\u0000"
')
model=${input_fields[0]:-}
cwd_display=${input_fields[1]:-}
cwd_raw=${input_fields[2]:-}
used=${input_fields[3]:-}
five_live=${input_fields[4]:-}
five_resets=${input_fields[5]:-}
week_live=${input_fields[6]:-}
week_resets=${input_fields[7]:-}
effort_raw=$(jq -r '.effortLevel // empty' "${HOME}/.claude/settings.json" 2>/dev/null)
effort_label=""
case "$effort_raw" in
  low)    effort_label="(low)" ;;
  medium) effort_label="(med)" ;;
  high)   effort_label="(high)" ;;
  xhigh)  effort_label="(xhigh)" ;;
  *)      [ -n "$effort_raw" ] && effort_label="($effort_raw)" ;;
esac
cwd=${cwd_display/#\/home\/user/~}

# Update cache: merge-update — only overwrite keys we have live data for.
# If resets_at is absent, default to now + window size (5h or 7d) so the
# cached value remains usable until the next natural reset.
if [ -n "$five_live" ] || [ -n "$week_live" ]; then
    tmp="${CACHE_FILE}.tmp.$$"
    existing=$([ -f "$CACHE_FILE" ] && cat "$CACHE_FILE" || echo '{}')
    echo "$existing" | jq \
        --argjson now "$now" \
        --arg five_pct "$five_live" \
        --arg five_resets "$five_resets" \
        --arg week_pct "$week_live" \
        --arg week_resets "$week_resets" \
        '
        if ($five_pct | length) > 0 then
            .five_hour = {
                pct: ($five_pct | tonumber),
                resets_at: (if ($five_resets | length) > 0 then ($five_resets | tonumber) else ($now + 18000) end)
            }
        else . end |
        if ($week_pct | length) > 0 then
            .seven_day = {
                pct: ($week_pct | tonumber),
                resets_at: (if ($week_resets | length) > 0 then ($week_resets | tonumber) else ($now + 604800) end)
            }
        else . end
        ' > "$tmp" && mv "$tmp" "$CACHE_FILE"
fi

# Read effective values: prefer live, fall back to cache (only if window not yet expired)
five=""
week=""

if [ -n "$five_live" ]; then
    five="$five_live"
elif [ -f "$CACHE_FILE" ]; then
    cached_resets=$(jq -r '.five_hour.resets_at // 0' "$CACHE_FILE" 2>/dev/null)
    if [ -n "$cached_resets" ] && [ "$cached_resets" -gt "$now" ] 2>/dev/null; then
        five=$(jq -r '.five_hour.pct // empty' "$CACHE_FILE" 2>/dev/null)
    fi
fi

if [ -n "$week_live" ]; then
    week="$week_live"
elif [ -f "$CACHE_FILE" ]; then
    cached_resets=$(jq -r '.seven_day.resets_at // 0' "$CACHE_FILE" 2>/dev/null)
    if [ -n "$cached_resets" ] && [ "$cached_resets" -gt "$now" ] 2>/dev/null; then
        week=$(jq -r '.seven_day.pct // empty' "$CACHE_FILE" 2>/dev/null)
    fi
fi

# Build time-remaining helper: seconds -> "?h?m"
fmt_remaining() {
    local secs=$(( $1 - now ))
    [ "$secs" -le 0 ] && echo "0m" && return
    local h=$(( secs / 3600 ))
    local m=$(( (secs % 3600) / 60 ))
    if [ "$h" -ge 24 ]; then
        local d=$(( h / 24 ))
        local rh=$(( h % 24 ))
        echo "${d}d${rh}h"
    elif [ "$h" -gt 0 ]; then
        echo "${h}h${m}m"
    else
        echo "${m}m"
    fi
}

# Map a percentage (0-100) to an ANSI color escape: green -> yellow -> red
# Usage: pct_color <pct>  → prints the escape sequence string
pct_color() {
    local pct="${1:-0}"
    local n
    n=$(printf '%.0f' "$pct" 2>/dev/null || echo 0)
    if   [ "$n" -ge 90 ]; then printf '\033[01;31m'   # bright red
    elif [ "$n" -ge 75 ]; then printf '\033[00;31m'   # red
    elif [ "$n" -ge 60 ]; then printf '\033[00;33m'   # yellow
    elif [ "$n" -ge 40 ]; then printf '\033[01;33m'   # bright yellow
    else                       printf '\033[00;32m'   # green
    fi
}
RESET='\033[00m'

# Build ctx suffix for row 1
ctx_suffix=""
if [ -n "$used" ]; then
    ctx_color=$(pct_color "$used")
    ctx_suffix="  \033[00;33mctx:${ctx_color}$(printf '%.0f' "$used")%${RESET}"
fi

# Build line 2: rate limits only
line2=""
if [ -n "$five" ]; then
    five_r=""
    five_resets_eff=""
    if [ -n "$five_resets" ]; then
        five_resets_eff="$five_resets"
    elif [ -f "$CACHE_FILE" ]; then
        five_resets_eff=$(jq -r '.five_hour.resets_at // empty' "$CACHE_FILE" 2>/dev/null)
    fi
    [ -n "$five_resets_eff" ] && five_r="($(fmt_remaining "$five_resets_eff") left)"
    five_color=$(pct_color "$five")
    line2="\033[00;35m5h:${five_color}$(printf '%.0f' "$five")%${RESET}${five_r:+ $five_r}"
fi
if [ -n "$week" ]; then
    week_r=""
    week_resets_eff=""
    if [ -n "$week_resets" ]; then
        week_resets_eff="$week_resets"
    elif [ -f "$CACHE_FILE" ]; then
        week_resets_eff=$(jq -r '.seven_day.resets_at // empty' "$CACHE_FILE" 2>/dev/null)
    fi
    [ -n "$week_resets_eff" ] && week_r="($(fmt_remaining "$week_resets_eff") left)"
    week_color=$(pct_color "$week")
    line2="${line2:+$line2 }\033[00;35m7d:${week_color}$(printf '%.0f' "$week")%${RESET}${week_r:+ $week_r}"
fi

left=$(printf '\033[01;32m%s%s\033[00m:\033[01;34m%s\033[00m' \
    "$model" "$effort_label" "$cwd")

PY3=$(command -v python3 || echo /usr/bin/python3)
ERR_LOG="${HOME}/.claude/statusline-error.log"
cost_out=$(echo "$input" | "$PY3" /home/user/.claude/statusline-cost.sh 2>"$ERR_LOG")
if [ -s "$ERR_LOG" ]; then
    { echo "=== $(date -Iseconds) ==="; cat "$ERR_LOG"; } >> "${HOME}/.claude/statusline-error.log.history"
fi
rm -f "$ERR_LOG"
cost_row1=$(printf '%s' "$cost_out" | head -n1)
cost_row2=$(printf '%s' "$cost_out" | tail -n+2)
printf '%s  %s%b' "$left" "$cost_row1" "$ctx_suffix"
[ -n "$cost_row2" ] && printf '\n%s' "$cost_row2"
[ -n "$line2" ] && printf '\n%b' "$line2"
