#!/bin/bash
# Template Version: 2 | ContextKit: 0.1.0 | Updated: 2025-09-15

# Custom Claude Code statusline:
# Format: 5h-Usage: 61% (2.3h left) | Chat: ████░░░░░░ 44% (87k/200k)
# With colored progress bar for chat context
#
# Usage: CustomStatusline.sh --plan Pro|Max5|Max20
# Plan parameter is required for accurate cost tracking

# ⚠️ FOR DEVELOPERS: Do not edit this file - changes will be overwritten during ContextKit updates.
# Report bugs: https://github.com/FlineDev/ContextKit/issues

# Color definitions
YELLOW='\033[33m'       # Normal yellow
RED='\033[31m'          # Bright red
LIGHT_GRAY='\033[37m'   # Light gray text
RESET='\033[0m'

# Parse command line arguments
PLAN=""  # No default - must be specified

while [[ $# -gt 0 ]]; do
    case $1 in
        --plan)
            PLAN="$2"
            shift 2
            ;;
        --help|-h)
            echo "Usage: $0 --plan Pro|Max5|Max20"
            echo "Plan is required for accurate cost tracking"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 --plan Pro|Max5|Max20"
            exit 1
            ;;
    esac
done

# Validate that plan was provided
if [[ -z "$PLAN" ]]; then
    echo "Error: --plan parameter is required"
    echo "Usage: $0 --plan Pro|Max5|Max20"
    exit 1
fi

# Set block budget based on plan
case "$PLAN" in
    "Pro")
        BLOCK_BUDGET="10.00"
        ;;
    "Max20")
        BLOCK_BUDGET="200.00"
        ;;
    "Max5")
        BLOCK_BUDGET="50.00"
        ;;
    *)
        echo "Invalid plan: $PLAN. Use Pro, Max5, or Max20"
        exit 1
        ;;
esac

# Allow environment variable override
BLOCK_BUDGET=${CLAUDE_BLOCK_BUDGET:-$BLOCK_BUDGET}

# Function to create colored progress bar and return color
create_progress_bar() {
    local percent=$1
    local width=10
    local filled=$((percent * width / 100))
    local empty=$((width - filled))
    
    # Choose color based on percentage
    local color
    if [[ $percent -lt 50 ]]; then
        color="$LIGHT_GRAY"
    elif [[ $percent -lt 80 ]]; then
        color="$YELLOW"
    else
        color="$RED"
    fi
    
    local bar=""
    
    # Add filled and empty portions
    for ((i=0; i<filled; i++)); do
        bar+="▓"
    done
    for ((i=0; i<empty; i++)); do
        bar+="░"
    done
    
    # Return both bar and color (separated by |)
    echo "${color}${bar}|${color}"
}

# Get ccusage data
ccusage_data=$(ccusage statusline 2>/dev/null)

if [[ $? -ne 0 ]] || [[ -z "$ccusage_data" ]]; then
    # Fallback if ccusage fails
    echo -e "${LIGHT_GRAY}5h-Usage: loading... | Chat: ░░░░░░░░░░ loading...${RESET}"
    exit 0
fi

# Extract block time remaining (format: "block (13m left)" or "block (1h 13m left)")
block_time=$(echo "$ccusage_data" | grep -o 'block ([^)]*left)' | sed 's/block (\|)//g')

# Extract context tokens and percentage  
context_tokens=$(echo "$ccusage_data" | grep -o '🧠[[:space:]]*[0-9,]\+' | grep -o '[0-9,]\+')
context_percent=$(echo "$ccusage_data" | grep -o '([0-9]\+%)' | grep -o '[0-9]\+')

# Parse block cost from ccusage output (e.g., "$0.45 block (2h 45m left)")
block_cost=$(echo "$ccusage_data" | grep -o '\$[0-9.]\+ block' | grep -o '[0-9.]\+')

# Parse time remaining for display
if [[ "$block_time" =~ ([0-9]+)h[[:space:]]+([0-9]+)m[[:space:]]+left ]]; then
    # Format: "1h 13m left"
    hours_left=${BASH_REMATCH[1]}
    minutes_left=${BASH_REMATCH[2]}
    total_minutes_left=$((hours_left * 60 + minutes_left))
elif [[ "$block_time" =~ ([0-9]+)m[[:space:]]+left ]]; then
    # Format: "13m left"
    hours_left=0
    minutes_left=${BASH_REMATCH[1]}
    total_minutes_left=$minutes_left
fi

# Calculate cost-based percentage and format display
if [[ -n "$block_cost" && -n "$BLOCK_BUDGET" ]]; then
    # Calculate real usage percentage based on API cost
    window_percent=$(echo "scale=0; ($block_cost * 100) / $BLOCK_BUDGET" | bc)
    if [[ $window_percent -gt 100 ]]; then window_percent=100; fi

    # Format time display: minutes if < 60, decimal hours if >= 60
    if [[ -n "$total_minutes_left" ]]; then
        if [[ $total_minutes_left -lt 60 ]]; then
            time_display="${total_minutes_left}m left"
        else
            # Convert to decimal hours with 1 decimal place
            hours_decimal=$(echo "scale=1; $total_minutes_left / 60" | bc)
            time_display="${hours_decimal}h left"
        fi
        window_info="5h-Usage: ${window_percent}% (${time_display})"
    else
        window_info="5h-Usage: ${window_percent}%"
    fi
else
    window_info="5h-Usage: parsing..."
fi

# Format chat context with progress bar
if [[ -n "$context_tokens" && -n "$context_percent" ]]; then
    # Convert to k format (round up)
    tokens_clean=$(echo "$context_tokens" | tr -d ',')
    tokens_k=$(((tokens_clean + 999) / 1000))
    
    # Create colored progress bar
    progress_result=$(create_progress_bar $context_percent)
    progress_bar=$(echo "$progress_result" | cut -d'|' -f1)
    text_color=$(echo "$progress_result" | cut -d'|' -f2)
    
    context_info="Chat: ${progress_bar} ${text_color}${context_percent}% (${tokens_k}k/200k)${LIGHT_GRAY}"
else
    context_info="Chat: ░░░░░░░░░░ parsing..."
fi

# Output statusline
echo -e "${LIGHT_GRAY}$window_info | $context_info${RESET}"