#!/bin/bash
# Enhanced multi-line status line for Claude Code
# Line 1: Model, directory, git branch
# Line 2: Context bar, cost, duration, PwC budget

# Read JSON from stdin
input=$(cat)

# Extract fields
MODEL_RAW=$(echo "$input" | jq -r '.model.display_name // .model.id // "Claude"')
# Extract just the model name (Opus, Sonnet, Haiku) from full ID if needed
case "$MODEL_RAW" in
    *opus*|*Opus*) MODEL="Opus" ;;
    *sonnet*|*Sonnet*) MODEL="Sonnet" ;;
    *haiku*|*Haiku*) MODEL="Haiku" ;;
    *) MODEL="$MODEL_RAW" ;;
esac

DIR=$(echo "$input" | jq -r '.workspace.current_dir')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)
COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')
INPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_input_tokens // 0')
OUTPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_output_tokens // 0')

# Colors
CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

# Context bar color based on usage
if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"
elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"
else BAR_COLOR="$GREEN"; fi

# Build progress bar
FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))
BAR=$(printf "%${FILLED}s" | tr ' ' '█')$(printf "%${EMPTY}s" | tr ' ' '░')

# Format duration - cleaner format
TOTAL_SECS=$((DURATION_MS / 1000))
HOURS=$((TOTAL_SECS / 3600))
MINS=$(((TOTAL_SECS % 3600) / 60))
if [ "$HOURS" -gt 0 ]; then
    DURATION_FMT="${HOURS}h${MINS}m"
elif [ "$MINS" -gt 0 ]; then
    DURATION_FMT="${MINS}m"
else
    DURATION_FMT="${TOTAL_SECS}s"
fi

# Git status (cached 5s)
GIT_CACHE="/tmp/statusline-git-cache"
if [ ! -f "$GIT_CACHE" ] || [ $(($(date +%s) - $(stat -f %m "$GIT_CACHE" 2>/dev/null || echo 0))) -gt 5 ]; then
    if git rev-parse --git-dir > /dev/null 2>&1; then
        BRANCH=$(git branch --show-current 2>/dev/null)
        STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')
        MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')
        echo "$BRANCH|$STAGED|$MODIFIED" > "$GIT_CACHE"
    else
        echo "||" > "$GIT_CACHE"
    fi
fi
IFS='|' read -r BRANCH STAGED MODIFIED < "$GIT_CACHE"

# PwC Coding Agents Budget (cached 60s, API call to passthrough)
QUOTA_CACHE="$HOME/.claude/quota-cache.json"
BUDGET_LABEL="🏦 PwC Coding Agents Budget: unavailable"
SETTINGS="$HOME/.claude/settings.json"
if [ -f "$SETTINGS" ]; then
    if [ ! -f "$QUOTA_CACHE" ] || [ $(($(date +%s) - $(stat -f %m "$QUOTA_CACHE" 2>/dev/null || echo 0))) -gt 60 ]; then
        BASE_URL=$(jq -r '.env.ANTHROPIC_BASE_URL // empty' "$SETTINGS" 2>/dev/null)
        AUTH_TOKEN=$(jq -r '.env.ANTHROPIC_AUTH_TOKEN // empty' "$SETTINGS" 2>/dev/null)
        if [ -n "$BASE_URL" ] && [ -n "$AUTH_TOKEN" ]; then
            RESPONSE=$(curl -s --max-time 2 "$BASE_URL/quota/status" -H "Authorization: Bearer $AUTH_TOKEN" 2>/dev/null)
                if [ -n "$RESPONSE" ] && echo "$RESPONSE" | jq -e '.usage' >/dev/null 2>&1; then
                echo "$RESPONSE" > "$QUOTA_CACHE"
            fi
        fi
    fi
    if [ -f "$QUOTA_CACHE" ]; then
        USAGE=$(jq -r '.usage // 0' "$QUOTA_CACHE" 2>/dev/null)
        LIMIT=$(jq -r '.limit // 0' "$QUOTA_CACHE" 2>/dev/null)
        QUOTA_PCT=$(jq -r '.percent // 0' "$QUOTA_CACHE" 2>/dev/null)

        # Format usage/limit as integers
        USAGE_INT=$(printf '%.0f' "$USAGE")
        LIMIT_INT=$(printf '%.0f' "$LIMIT")

        # Color-coded emoji based on percentage
        if [ "$QUOTA_PCT" -ge 90 ]; then BUDGET_EMOJI="🔴"
        elif [ "$QUOTA_PCT" -ge 70 ]; then BUDGET_EMOJI="🟡"
        else BUDGET_EMOJI="🟢"; fi

        BUDGET_LABEL="🏦 PwC Coding Agents Budget: ${BUDGET_EMOJI} ${QUOTA_PCT}% (€${USAGE_INT}/€${LIMIT_INT})"
    fi
fi

# Line 1: Model, directory, git
GIT_INFO=""
if [ -n "$BRANCH" ]; then
    GIT_INFO=" | $BRANCH"
    [ "$STAGED" -gt 0 ] && GIT_INFO="$GIT_INFO ${GREEN}+${STAGED}${RESET}"
    [ "$MODIFIED" -gt 0 ] && GIT_INFO="$GIT_INFO ${YELLOW}~${MODIFIED}${RESET}"
fi
echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$GIT_INFO"

# Format tokens (K for thousands, M for millions)
format_tokens() {
    local tokens=$1
    if [ "$tokens" -ge 1000000 ]; then
        printf "%.1fM" "$(echo "scale=1; $tokens/1000000" | bc)"
    elif [ "$tokens" -ge 1000 ]; then
        printf "%.1fK" "$(echo "scale=1; $tokens/1000" | bc)"
    else
        echo "$tokens"
    fi
}
INPUT_FMT=$(format_tokens "$INPUT_TOKENS")
OUTPUT_FMT=$(format_tokens "$OUTPUT_TOKENS")

# Line 2: Context bar, cost, duration, budget (with verbose labels and emojis)
COST_FMT=$(printf '$%.2f' "$COST")
echo -e "${BAR_COLOR}${BAR}${RESET} 🧠 Context Window: ${PCT}% | 🔢 Session Tokens: ${INPUT_FMT}↓ ${OUTPUT_FMT}↑ | ${YELLOW}💰 Session Cost: ${COST_FMT}${RESET} | ⏱️  Session Time: ${DURATION_FMT} | $BUDGET_LABEL"
