#!/bin/bash

# Claude Code Status Line Script
# Clean, minimal implementation

# ANSI colors
BLUE=$'\033[38;2;118;159;240m'  # #769ff0
RED=$'\033[38;2;255;0;0m'
RESET=$'\033[0m'

# Read JSON input
input=$(cat)

# Extract basic info
folder=$(basename "$(echo "$input" | jq -r '.workspace.current_dir')")
model=$(echo "$input" | jq -r '.model.display_name')

# Venv indicator
venv_indicator="○"
[ -n "$VIRTUAL_ENV" ] && venv_indicator="◉"

# Language info (Python only for now)
lang_info=""
if [ -n "$VIRTUAL_ENV" ] || [ -f "requirements.txt" ] || [ -f "setup.py" ] || [ -f "pyproject.toml" ] || [ -f "Pipfile" ]; then
    pyver=$(python3 --version 2>/dev/null | cut -d' ' -f2 || echo 'N/A')
    lang_info=" $pyver"
fi

# Git branch
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'N/A')

# Git status indicators (in red)
git_status=""
if [ "$branch" != "N/A" ]; then
    # Uncommitted changes
    if ! git diff --quiet 2>/dev/null || ! git diff --cached --quiet 2>/dev/null; then
        git_status="${RED}*${BLUE}"
    fi

    # Untracked files
    if [ -n "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then
        git_status="${git_status}${RED}?${BLUE}"
    fi

    # Ahead/behind
    local_commit=$(git rev-parse @ 2>/dev/null)
    remote_commit=$(git rev-parse @{u} 2>/dev/null)
    base_commit=$(git merge-base @ @{u} 2>/dev/null)

    if [ -n "$remote_commit" ] && [ "$local_commit" != "$remote_commit" ]; then
        if [ "$local_commit" = "$base_commit" ]; then
            git_status="${git_status}${RED}⇣${BLUE}"
        elif [ "$remote_commit" = "$base_commit" ]; then
            git_status="${git_status}${RED}⇡${BLUE}"
        else
            git_status="${git_status}${RED}⇣⇡${BLUE}"
        fi
    fi

    [ -n "$git_status" ] && git_status=" $git_status"
fi

# Build main statusline (everything in blue except git indicators)
statusline="${BLUE}${venv_indicator} ${folder} | ${lang_info} |  $branch${git_status} | 󰚩 $model${RESET}"

# Cost info (optional)
cost_info=""
if command -v bun >/dev/null 2>&1; then
    ccusage_output=$(echo "$input" | bun x ccusage statusline 2>/dev/null)
    if [ -n "$ccusage_output" ]; then
        session_cost=$(echo "$ccusage_output" | grep -oE '\$[0-9]+\.[0-9]+ session' | sed 's/ session//')
        daily_cost=$(echo "$ccusage_output" | grep -oE '\$[0-9]+\.[0-9]+ today' | sed 's/ today//')
        time_left=$(echo "$ccusage_output" | grep -oE '[0-9]+h [0-9]+m left')

        [ -n "$session_cost" ] && cost_info="${cost_info} | 💸 $session_cost"
        [ -n "$daily_cost" ] && cost_info="${cost_info} | 💰 $daily_cost/day"
        [ -n "$time_left" ] && cost_info="${cost_info} | ⏱️ $time_left"
    fi
fi

# Output
echo -e "${statusline}${cost_info}"
