#!/bin/bash
set -f

input=$(cat)

if [ -z "$input" ]; then
    printf "Claude"
    exit 0
fi

# ── Colors ──────────────────────────────────────────────
blue='\033[38;2;0;153;255m'
orange='\033[38;2;255;176;85m'
green='\033[38;2;0;175;80m'
cyan='\033[38;2;86;182;194m'
red='\033[38;2;255;85;85m'
yellow='\033[38;2;230;200;0m'
white='\033[38;2;220;220;220m'
magenta='\033[38;2;180;140;255m'
dim='\033[2m'
reset='\033[0m'

sep=" ${dim}│${reset} "

# ── Helpers ─────────────────────────────────────────────
format_tokens() {
    local num=$1
    if [ "$num" -ge 1000000 ]; then
        awk "BEGIN {printf \"%.1fm\", $num / 1000000}"
    elif [ "$num" -ge 1000 ]; then
        awk "BEGIN {printf \"%.0fk\", $num / 1000}"
    else
        printf "%d" "$num"
    fi
}

color_for_pct() {
    local pct=$1
    if [ "$pct" -ge 90 ]; then printf "$red"
    elif [ "$pct" -ge 70 ]; then printf "$yellow"
    elif [ "$pct" -ge 50 ]; then printf "$orange"
    else printf "$green"
    fi
}

build_bar() {
    local pct=$1
    local width=$2
    [ "$pct" -lt 0 ] 2>/dev/null && pct=0
    [ "$pct" -gt 100 ] 2>/dev/null && pct=100

    local filled=$(( pct * width / 100 ))
    local empty=$(( width - filled ))
    local bar_color
    bar_color=$(color_for_pct "$pct")

    local filled_str="" empty_str=""
    for ((i=0; i<filled; i++)); do filled_str+="●"; done
    for ((i=0; i<empty; i++)); do empty_str+="○"; done

    printf "${bar_color}${filled_str}${dim}${empty_str}${reset}"
}

iso_to_epoch() {
    local iso_str="$1"

    local epoch
    epoch=$(date -d "${iso_str}" +%s 2>/dev/null)
    if [ -n "$epoch" ]; then
        echo "$epoch"
        return 0
    fi

    local stripped="${iso_str%%.*}"
    stripped="${stripped%%Z}"
    stripped="${stripped%%+*}"
    stripped="${stripped%%-[0-9][0-9]:[0-9][0-9]}"

    if [[ "$iso_str" == *"Z"* ]] || [[ "$iso_str" == *"+00:00"* ]] || [[ "$iso_str" == *"-00:00"* ]]; then
        epoch=$(env TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%S" "$stripped" +%s 2>/dev/null)
    else
        epoch=$(date -j -f "%Y-%m-%dT%H:%M:%S" "$stripped" +%s 2>/dev/null)
    fi

    if [ -n "$epoch" ]; then
        echo "$epoch"
        return 0
    fi

    return 1
}

format_epoch() {
    local epoch="$1"
    local style="$2"
    [ -z "$epoch" ] && return

    case "$style" in
        time)
            date -j -r "$epoch" +"%l:%M%p" 2>/dev/null | sed 's/^ //; s/\.//g' | tr '[:upper:]' '[:lower:]' || \
            date -d "@$epoch" +"%l:%M%P" 2>/dev/null | sed 's/^ //; s/\.//g'
            ;;
        datetime)
            date -j -r "$epoch" +"%b %-d, %l:%M%p" 2>/dev/null | sed 's/  / /g; s/^ //; s/\.//g' | tr '[:upper:]' '[:lower:]' || \
            date -d "@$epoch" +"%b %-d, %l:%M%P" 2>/dev/null | sed 's/  / /g; s/^ //; s/\.//g'
            ;;
        *)
            date -j -r "$epoch" +"%b %-d" 2>/dev/null | tr '[:upper:]' '[:lower:]' || \
            date -d "@$epoch" +"%b %-d" 2>/dev/null
            ;;
    esac
}

relative_from_now() {
    local epoch="$1"
    [ -z "$epoch" ] && return

    local now diff
    now=$(date +%s)
    diff=$(( epoch - now ))
    [ "$diff" -le 0 ] && { printf "now"; return; }

    local days=$(( diff / 86400 ))
    local hours=$(( (diff % 86400) / 3600 ))
    local mins=$(( (diff % 3600) / 60 ))

    if [ "$days" -gt 0 ]; then
        printf "in %dd%dh" "$days" "$hours"
    elif [ "$hours" -gt 0 ]; then
        printf "in %dh%dm" "$hours" "$mins"
    else
        printf "in %dm" "$mins"
    fi
}

format_reset_time() {
    local iso_str="$1"
    local style="$2"
    [ -z "$iso_str" ] || [ "$iso_str" = "null" ] && return

    local epoch
    epoch=$(iso_to_epoch "$iso_str")
    [ -z "$epoch" ] && return

    format_epoch "$epoch" "$style"
}

# ── Extract JSON data ───────────────────────────────────
model_name=$(echo "$input" | jq -r '.model.display_name // "Claude"')

size=$(echo "$input" | jq -r '.context_window.context_window_size // 200000')
[ "$size" -eq 0 ] 2>/dev/null && size=200000

input_tokens=$(echo "$input" | jq -r '.context_window.current_usage.input_tokens // 0')
cache_create=$(echo "$input" | jq -r '.context_window.current_usage.cache_creation_input_tokens // 0')
cache_read=$(echo "$input" | jq -r '.context_window.current_usage.cache_read_input_tokens // 0')
current=$(( input_tokens + cache_create + cache_read ))

used_tokens=$(format_tokens $current)
total_tokens=$(format_tokens $size)

if [ "$size" -gt 0 ]; then
    pct_used=$(( current * 100 / size ))
else
    pct_used=0
fi

thinking_on=false
thinking_val=$(echo "$input" | jq -r '.thinking.enabled // false')
[ "$thinking_val" = "true" ] && thinking_on=true

# ── Session cost, diff, effort, output style, context flag ──
cost_usd=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
lines_added=$(echo "$input" | jq -r '.cost.total_lines_added // 0')
lines_removed=$(echo "$input" | jq -r '.cost.total_lines_removed // 0')
effort_level=$(echo "$input" | jq -r '.effort.level // empty')
fast_mode=$(echo "$input" | jq -r '.fast_mode // false')
output_style=$(echo "$input" | jq -r '.output_style.name // empty')

# ── LINE 1: Model │ Context % │ Directory (branch) │ Session │ Thinking ──
pct_color=$(color_for_pct "$pct_used")
cwd=$(echo "$input" | jq -r '.cwd // ""')
[ -z "$cwd" ] || [ "$cwd" = "null" ] && cwd=$(pwd)
dirname=$(basename "$cwd")

git_branch=""
git_dirty=""
git_track=""
if git -C "$cwd" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    git_branch=$(git -C "$cwd" symbolic-ref --short HEAD 2>/dev/null)
    if [ -n "$(git -C "$cwd" status --porcelain 2>/dev/null)" ]; then
        git_dirty="*"
    fi
    # Ahead/behind vs upstream, only when an upstream is configured
    counts=$(git -C "$cwd" rev-list --left-right --count '@{upstream}...HEAD' 2>/dev/null)
    if [ -n "$counts" ]; then
        behind=$(echo "$counts" | awk '{print $1}')
        ahead=$(echo "$counts" | awk '{print $2}')
        [ "$ahead" -gt 0 ] 2>/dev/null && git_track+="↑${ahead}"
        [ "$behind" -gt 0 ] 2>/dev/null && git_track+="↓${behind}"
    fi
fi

session_duration=""
session_start=$(echo "$input" | jq -r '.session.start_time // empty')
if [ -n "$session_start" ] && [ "$session_start" != "null" ]; then
    start_epoch=$(iso_to_epoch "$session_start")
    if [ -n "$start_epoch" ]; then
        now_epoch=$(date +%s)
        elapsed=$(( now_epoch - start_epoch ))
        if [ "$elapsed" -ge 3600 ]; then
            session_duration="$(( elapsed / 3600 ))h$(( (elapsed % 3600) / 60 ))m"
        elif [ "$elapsed" -ge 60 ]; then
            session_duration="$(( elapsed / 60 ))m"
        else
            session_duration="${elapsed}s"
        fi
    fi
fi

# ── OAuth token resolution ──────────────────────────────
get_oauth_token() {
    local token=""

    if [ -n "$CLAUDE_CODE_OAUTH_TOKEN" ]; then
        echo "$CLAUDE_CODE_OAUTH_TOKEN"
        return 0
    fi

    if command -v security >/dev/null 2>&1; then
        local raw blob
        raw=$(security find-generic-password -s "Claude Code-credentials" -a "aashutosh" -w 2>/dev/null)
        if [ -n "$raw" ]; then
            if echo "$raw" | jq . >/dev/null 2>&1; then
                blob="$raw"
            else
                blob=$(echo "$raw" | xxd -r -p 2>/dev/null)
            fi
            token=$(echo "$blob" | jq -r '.claudeAiOauth.accessToken // empty' 2>/dev/null)
            if [ -n "$token" ] && [ "$token" != "null" ]; then
                echo "$token"
                return 0
            fi
        fi
    fi

    local creds_file="${HOME}/.claude/.credentials.json"
    if [ -f "$creds_file" ]; then
        token=$(jq -r '.claudeAiOauth.accessToken // empty' "$creds_file" 2>/dev/null)
        if [ -n "$token" ] && [ "$token" != "null" ]; then
            echo "$token"
            return 0
        fi
    fi

    if command -v secret-tool >/dev/null 2>&1; then
        local blob
        blob=$(timeout 2 secret-tool lookup service "Claude Code-credentials" 2>/dev/null)
        if [ -n "$blob" ]; then
            token=$(echo "$blob" | jq -r '.claudeAiOauth.accessToken // empty' 2>/dev/null)
            if [ -n "$token" ] && [ "$token" != "null" ]; then
                echo "$token"
                return 0
            fi
        fi
    fi

    echo ""
}

# ── Detect active account email ─────────────────────────
account_label=""
_accounts_dir="${CLAUDE_ACCOUNTS_DIR:-$HOME/.claude/accounts}"
_keychain_acct="${USER:-$(id -un)}"

if command -v security >/dev/null 2>&1; then
    _raw=$(security find-generic-password -s "Claude Code-credentials" -a "$_keychain_acct" -w 2>/dev/null)
    if [ -n "$_raw" ]; then
        if echo "$_raw" | jq . >/dev/null 2>&1; then
            _blob="$_raw"
        else
            _blob=$(echo "$_raw" | xxd -r -p 2>/dev/null)
        fi
        _active_token=$(echo "$_blob" | jq -r '.claudeAiOauth.accessToken // empty' 2>/dev/null)
        # Match active token against stored account files to find email
        set +f
        for _f in "$_accounts_dir"/*.json; do
            [ -f "$_f" ] || continue
            _stored_token=$(jq -r '.claudeAiOauth.accessToken // empty' "$_f" 2>/dev/null)
            if [ "$_stored_token" = "$_active_token" ]; then
                _name=$(basename "$_f" .json)
                _email_file="$_accounts_dir/${_name}.email"
                [ -f "$_email_file" ] && account_label=$(cat "$_email_file")
                break
            fi
        done
        set -f
    fi
fi

line1="${cyan}${dirname}${reset}"
if [ -n "$git_branch" ]; then
    line1+=" ${green}(${git_branch}${red}${git_dirty}${green})${reset}"
    [ -n "$git_track" ] && line1+="${yellow}${git_track}${reset}"
fi
# PR badge: number colored/iconed by review state, when the branch has an open PR
pr_number=$(echo "$input" | jq -r '.pr.number // empty')
if [ -n "$pr_number" ]; then
    pr_state=$(echo "$input" | jq -r '.pr.review_state // empty')
    case "$pr_state" in
        approved) pr_color="$green"; pr_icon="✓" ;;
        changes_requested) pr_color="$red"; pr_icon="✗" ;;
        draft) pr_color="$dim"; pr_icon="◌" ;;
        pending) pr_color="$yellow"; pr_icon="…" ;;
        *) pr_color="$white"; pr_icon="" ;;
    esac
    line1+=" ${pr_color}#${pr_number}${pr_icon}${reset}"
fi
line1+="${sep}"
line1+="${blue}${model_name}${reset}"
line1+="${sep}"
if [ -n "$account_label" ]; then
    line1+="${magenta}${account_label}${reset}"
    line1+="${sep}"
fi
# Context %: battery-drain metaphor, flips to low-battery past the auto-compact danger zone (~80%)
if [ "$pct_used" -ge 80 ]; then
    ctx_icon="🪫"
else
    ctx_icon="🔋"
fi
line1+="${ctx_icon} ${pct_color}${pct_used}%${reset}"
if [ -n "$session_duration" ]; then
    line1+="${sep}"
    line1+="${dim}⏱ ${reset}${white}${session_duration}${reset}"
fi
# Session cost + diff, only once there is spend to show
if awk "BEGIN {exit !($cost_usd > 0)}"; then
    cost_fmt=$(awk "BEGIN {printf \"%.2f\", $cost_usd}")
    line1+="${sep}"
    line1+="${dim}\$${reset}${white}${cost_fmt}${reset} ${green}+${lines_added}${reset}${dim}/${reset}${red}-${lines_removed}${reset}"
fi
line1+="${sep}"
if $thinking_on; then
    line1+="${magenta}◐ thinking${reset}"
else
    line1+="${dim}◑ thinking${reset}"
fi
# Reasoning effort / fast mode - only when notable (fast mode on, or effort != high)
if [ "$fast_mode" = "true" ]; then
    line1+="${sep}${orange}⚡ fast${reset}"
elif [ -n "$effort_level" ] && [ "$effort_level" != "high" ]; then
    line1+="${sep}${cyan}${effort_level}${reset}"
fi
# Output style - only when non-default (learning-mode via hook still reports default)
if [ -n "$output_style" ] && [ "$output_style" != "default" ]; then
    line1+="${sep}${magenta}${output_style}${reset}"
fi

# ── Rate limit lines (five_hour/seven_day come straight off stdin) ──
bar_width=10
rate_lines=""

five_hour_pct=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty')
if [ -n "$five_hour_pct" ]; then
    five_hour_pct=$(printf "%.0f" "$five_hour_pct")
    five_hour_reset_epoch=$(echo "$input" | jq -r '.rate_limits.five_hour.resets_at // empty')
    five_hour_reset=$(format_epoch "$five_hour_reset_epoch" "time")
    five_hour_rel=$(relative_from_now "$five_hour_reset_epoch")
    five_hour_bar=$(build_bar "$five_hour_pct" "$bar_width")
    five_hour_pct_color=$(color_for_pct "$five_hour_pct")
    five_hour_pct_fmt=$(printf "%3d" "$five_hour_pct")

    rate_lines+="${white}current${reset} ${five_hour_bar} ${five_hour_pct_color}${five_hour_pct_fmt}%${reset} ${dim}⟳${reset} ${white}${five_hour_reset}${reset} ${dim}(${five_hour_rel})${reset}"
fi

seven_day_pct=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty')
if [ -n "$seven_day_pct" ]; then
    seven_day_pct=$(printf "%.0f" "$seven_day_pct")
    seven_day_reset_epoch=$(echo "$input" | jq -r '.rate_limits.seven_day.resets_at // empty')
    seven_day_reset=$(format_epoch "$seven_day_reset_epoch" "datetime")
    seven_day_rel=$(relative_from_now "$seven_day_reset_epoch")
    seven_day_bar=$(build_bar "$seven_day_pct" "$bar_width")
    seven_day_pct_color=$(color_for_pct "$seven_day_pct")
    seven_day_pct_fmt=$(printf "%3d" "$seven_day_pct")

    [ -n "$rate_lines" ] && rate_lines+="\n"
    rate_lines+="${white}weekly${reset}  ${seven_day_bar} ${seven_day_pct_color}${seven_day_pct_fmt}%${reset} ${dim}⟳${reset} ${white}${seven_day_reset}${reset} ${dim}(${seven_day_rel})${reset}"
fi

# ── Extra usage credits: not in the built-in rate_limits field, still needs the API fetch (cached) ──
cache_file="/tmp/claude/statusline-usage-cache.json"
cache_max_age=60
mkdir -p /tmp/claude

needs_refresh=true
usage_data=""

if [ -f "$cache_file" ]; then
    cache_mtime=$(stat -c %Y "$cache_file" 2>/dev/null || stat -f %m "$cache_file" 2>/dev/null)
    now=$(date +%s)
    cache_age=$(( now - cache_mtime ))
    if [ "$cache_age" -lt "$cache_max_age" ]; then
        needs_refresh=false
        usage_data=$(cat "$cache_file" 2>/dev/null)
    fi
fi

if $needs_refresh; then
    token=$(get_oauth_token)
    if [ -n "$token" ] && [ "$token" != "null" ]; then
        response=$(curl -s --max-time 5 \
            -H "Accept: application/json" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $token" \
            -H "anthropic-beta: oauth-2025-04-20" \
            -H "User-Agent: claude-code/2.1.34" \
            "https://api.anthropic.com/api/oauth/usage" 2>/dev/null)
        if [ -n "$response" ] && echo "$response" | jq -e '.five_hour' >/dev/null 2>&1; then
            usage_data="$response"
            echo "$response" > "$cache_file"
        fi
    fi
    if [ -z "$usage_data" ] && [ -f "$cache_file" ]; then
        usage_data=$(cat "$cache_file" 2>/dev/null)
    fi
fi

if [ -n "$usage_data" ] && echo "$usage_data" | jq -e . >/dev/null 2>&1; then
    fable_limit=$(echo "$usage_data" | jq -c '[.limits[]? | select(.kind == "weekly_scoped" and (.scope.model.display_name // "" | ascii_downcase | startswith("fable")))] | first // empty')
    if [ -n "$fable_limit" ]; then
        fable_pct=$(echo "$fable_limit" | jq -r '.percent // 0' | awk '{printf "%.0f", $1}')
        fable_reset_epoch=$(iso_to_epoch "$(echo "$fable_limit" | jq -r '.resets_at // empty')")
        fable_reset=$(format_epoch "$fable_reset_epoch" "datetime")
        fable_rel=$(relative_from_now "$fable_reset_epoch")
        fable_bar=$(build_bar "$fable_pct" "$bar_width")
        fable_pct_color=$(color_for_pct "$fable_pct")
        fable_pct_fmt=$(printf "%3d" "$fable_pct")

        [ -n "$rate_lines" ] && rate_lines+="\n"
        rate_lines+="${white}fable${reset}   ${fable_bar} ${fable_pct_color}${fable_pct_fmt}%${reset} ${dim}⟳${reset} ${white}${fable_reset}${reset} ${dim}(${fable_rel})${reset}"
    fi

    extra_enabled=$(echo "$usage_data" | jq -r '.extra_usage.is_enabled // false')
    if [ "$extra_enabled" = "true" ]; then
        extra_pct=$(echo "$usage_data" | jq -r '.extra_usage.utilization // 0' | awk '{printf "%.0f", $1}')
        extra_used=$(echo "$usage_data" | jq -r '.extra_usage.used_credits // 0' | awk '{printf "%.2f", $1/100}')
        extra_limit=$(echo "$usage_data" | jq -r '.extra_usage.monthly_limit // 0' | awk '{printf "%.2f", $1/100}')
        extra_bar=$(build_bar "$extra_pct" "$bar_width")
        extra_pct_color=$(color_for_pct "$extra_pct")

        extra_reset_epoch=$(date -v+1m -v1d +%s 2>/dev/null)
        extra_reset=$(date -v+1m -v1d +"%b %-d" 2>/dev/null | tr '[:upper:]' '[:lower:]')
        if [ -z "$extra_reset" ]; then
            extra_reset_epoch=$(date -d "$(date +%Y-%m-01) +1 month" +%s 2>/dev/null)
            extra_reset=$(date -d "$(date +%Y-%m-01) +1 month" +"%b %-d" 2>/dev/null | tr '[:upper:]' '[:lower:]')
        fi
        extra_rel=$(relative_from_now "$extra_reset_epoch")

        extra_col="${white}extra${reset}   ${extra_bar} ${extra_pct_color}\$${extra_used}${dim}/${reset}${white}\$${extra_limit}${reset}"
        extra_reset_line="${dim}resets ${reset}${white}${extra_reset}${reset} ${dim}(${extra_rel})${reset}"
        rate_lines+="\n${extra_col}"
        rate_lines+="\n${extra_reset_line}"
    fi
fi

# ── Output ──────────────────────────────────────────────
printf "%b" "$line1"
[ -n "$rate_lines" ] && printf "\n\n%b" "$rate_lines"

exit 0
