#!/bin/bash

# FR3K Enhanced Status Bar for Claude Code
# Supports FR3K_HOME environment variable with HOME fallback
# Counts: Commands, MCPs, Agents, Hooks, ADW workflows
# Shows fr3k tier level, cost/tokens from ccusage
# Tokyo Night Storm color scheme

# Read JSON input from stdin
input=$(cat)

# Extract data from JSON input
current_dir=$(echo "$input" | jq -r '.workspace.current_dir')
model_name=$(echo "$input" | jq -r '.model.display_name')

# Get directory name
dir_name=$(basename "$current_dir")

# Determine fr3k directory (project .fr3k or global .fr3k)
if [ -d "$current_dir/.fr3k" ]; then
    fr3k_dir="$current_dir/.fr3k"
    is_project=true
else
    fr3k_dir="${FR3K_HOME:-$HOME}/.fr3k"
    is_project=false
fi

# Fallback to .claude if .fr3k doesn't exist
claude_dir="${FR3K_HOME:-$HOME}/.claude"

# Initialize counts
commands_count=0
mcps_count=0
agents_count=0
hooks_count=0
adw_count=0
tier="none"

# Count commands (only .md files in root of commands directory)
if [ -d "$fr3k_dir/commands" ]; then
    commands_count=$(find "$fr3k_dir/commands" -maxdepth 1 -name "*.md" 2>/dev/null | wc -l | tr -d ' ')
elif [ -d "$claude_dir/commands" ]; then
    commands_count=$(find "$claude_dir/commands" -maxdepth 1 -name "*.md" 2>/dev/null | wc -l | tr -d ' ')
fi

# Count MCPs from settings.json or .claude.json
if [ -f "$claude_dir/settings.json" ]; then
    mcps_count=$(jq -r '.mcpServers | keys | length' "$claude_dir/settings.json" 2>/dev/null || echo "0")
elif [ -f "$current_dir/.claude.json" ]; then
    mcps_count=$(jq -r '.mcpServers | keys | length' "$current_dir/.claude.json" 2>/dev/null || echo "0")
fi

# Count agents (both .md and .json files)
if [ -d "$fr3k_dir/agents" ]; then
    agents_count=$(find "$fr3k_dir/agents" -maxdepth 1 \( -name "*.md" -o -name "*.json" \) 2>/dev/null | wc -l | tr -d ' ')
elif [ -d "$claude_dir/agents" ]; then
    agents_count=$(find "$claude_dir/agents" -maxdepth 1 \( -name "*.md" -o -name "*.json" \) 2>/dev/null | wc -l | tr -d ' ')
fi

# Count hooks (both Python scripts and binaries)
if [ -d "$fr3k_dir/hooks" ]; then
    python_hooks=$(find "$fr3k_dir/hooks" -maxdepth 1 -name "*.py" 2>/dev/null | wc -l | tr -d ' ')
    binary_hooks=$(find "$fr3k_dir/hooks" -maxdepth 1 -type f -executable ! -name "*.py" ! -name "*.mp3" 2>/dev/null | wc -l | tr -d ' ')
    hooks_count=$((python_hooks + binary_hooks))
fi

# Count ADW workflows if directory exists
if [ -d "$current_dir/adws" ]; then
    adw_count=$(find "$current_dir/adws" -maxdepth 1 -name "adw_*.py" 2>/dev/null | wc -l | tr -d ' ')
fi

# Detect fr3k tier level based on installed components
if [ "$adw_count" -gt 0 ] && [ "$hooks_count" -gt 0 ] && [ "$commands_count" -gt 0 ]; then
    tier="complete"
elif [ "$commands_count" -gt 0 ] && [ "$hooks_count" -gt 0 ]; then
    tier="development"
elif [ "$hooks_count" -gt 0 ]; then
    tier="standard"
elif [ -f "$current_dir/.fr3k/fr3k.json" ] || [ -f "$current_dir/FR3K.md" ]; then
    tier="basic"
fi

# Get MCP names for line 2 with color coding
mcp_names_formatted=""
if [ -f "$claude_dir/settings.json" ]; then
    mcp_names_raw=$(jq -r '.mcpServers | keys[]' "$claude_dir/settings.json" 2>/dev/null | tr '\n' ' ')
elif [ -f "$current_dir/.claude.json" ]; then
    mcp_names_raw=$(jq -r '.mcpServers | keys[]' "$current_dir/.claude.json" 2>/dev/null | tr '\n' ' ')
fi

# Get daily usage data from ccusage (for line 3)
daily_tokens=""
daily_cost=""
if command -v bunx >/dev/null 2>&1; then
    # Run ccusage daily, strip ANSI codes, extract Total line data
    ccusage_output=$(bunx ccusage 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g' | grep "│ Total" | head -1)
    if [ -n "$ccusage_output" ]; then
        # Extract tokens and cost
        daily_input=$(echo "$ccusage_output" | awk -F'│' '{print $4}' | tr -d ' ,')
        daily_output=$(echo "$ccusage_output" | awk -F'│' '{print $5}' | tr -d ' ,')
        daily_cost=$(echo "$ccusage_output" | awk -F'│' '{print $9}' | tr -d ' ')

        # Calculate total tokens if both are valid numbers
        if [[ "$daily_input" =~ ^[0-9]+$ ]] && [[ "$daily_output" =~ ^[0-9]+$ ]]; then
            daily_total=$((daily_input + daily_output))
            # Format tokens with commas
            daily_tokens=$(printf "%'d" "$daily_total" 2>/dev/null || echo "$daily_total")
        fi
    fi
fi

# Tokyo Night Storm Color Scheme
BACKGROUND='\033[48;2;36;40;59m'           # #24283b - Dark blue-gray background
BRIGHT_PURPLE='\033[38;2;187;154;247m'     # #bb9af7 - Line 1 primary color
BRIGHT_BLUE='\033[38;2;122;162;247m'       # #7aa2f7 - Line 2 primary color
DARK_BLUE='\033[38;2;100;140;200m'         # Darker blue variant for Line 2
BRIGHT_GREEN='\033[38;2;158;206;106m'      # #9ece6a - Line 3 primary color
DARK_GREEN='\033[38;2;130;170;90m'         # Darker green variant for Line 3
BRIGHT_ORANGE='\033[38;2;255;158;100m'     # #ff9e64 - Cost color
CYAN='\033[38;2;125;207;255m'              # #7dcfff - Cyan for emphasis
YELLOW='\033[38;2;224;175;104m'            # #e0af68 - Yellow for tier
DIR_COLOR='\033[38;2;135;206;250m'         # Light sky blue for directory
MODEL_PURPLE='\033[38;2;138;99;210m'       # Deep violet for model name
FR3K_PURPLE='\033[38;2;147;112;219m'       # Medium violet for "fr3k"
SEPARATOR_COLOR='\033[38;2;140;152;180m'   # Subtle gray for separators
RESET='\033[0m'                            # Reset all formatting

# Line-specific color assignments
LINE1_PRIMARY="$BRIGHT_PURPLE"
LINE1_ACCENT='\033[38;2;160;130;210m'
LINE2_PRIMARY="$DARK_BLUE"
LINE2_ACCENT='\033[38;2;110;150;210m'
LINE3_PRIMARY="$DARK_GREEN"
LINE3_ACCENT='\033[38;2;140;180;100m'

# Individual MCP names - use line 2 blue scheme with accent colors
MCP_HEY_FR3K="$BRIGHT_BLUE"               # hey-fr3k - bright blue
MCP_FR3K_THINK="$BRIGHT_BLUE"             # fr3k-think - bright blue
MCP_DEFAULT="$LINE2_PRIMARY"              # All other MCPs - standard line 2 blue

# Format MCP names with color coding
for mcp in $mcp_names_raw; do
    case "$mcp" in
        "hey-fr3k") formatted="${MCP_HEY_FR3K}hey-fr3k${RESET}" ;;
        "fr3k-think") formatted="${MCP_FR3K_THINK}fr3k-think${RESET}" ;;
        "md-mcp") formatted="${MCP_DEFAULT}md-mcp${RESET}" ;;
        "mcp-omnisearch") formatted="${MCP_DEFAULT}mcp-omnisearch${RESET}" ;;
        "snap-happy") formatted="${MCP_DEFAULT}snap-happy${RESET}" ;;
        "daemon") formatted="${BRIGHT_BLUE}daemon${RESET}" ;;
        "stripe") formatted="${LINE2_ACCENT}stripe${RESET}" ;;
        "httpx") formatted="${MCP_DEFAULT}HTTPx${RESET}" ;;
        "brightdata") formatted="${MCP_DEFAULT}BrightData${RESET}" ;;
        "naabu") formatted="${MCP_DEFAULT}Naabu${RESET}" ;;
        "apify") formatted="${MCP_DEFAULT}Apify${RESET}" ;;
        "content") formatted="${MCP_DEFAULT}Content${RESET}" ;;
        "Ref") formatted="${MCP_DEFAULT}Ref${RESET}" ;;
        "pai") formatted="${MCP_DEFAULT}Foundry${RESET}" ;;
        "playwright") formatted="${MCP_DEFAULT}Playwright${RESET}" ;;
        *) formatted="${MCP_DEFAULT}${mcp^}${RESET}" ;;
    esac

    if [ -z "$mcp_names_formatted" ]; then
        mcp_names_formatted="$formatted"
    else
        mcp_names_formatted="$mcp_names_formatted${SEPARATOR_COLOR}, ${formatted}"
    fi
done

# Output the enhanced fr3k status bar
# LINE 1 - System info with fr3k metrics
printf "${FR3K_PURPLE}fr3k${RESET}${LINE1_PRIMARY} here, running on ${MODEL_PURPLE}🧠 ${model_name}${RESET}${LINE1_PRIMARY} in ${DIR_COLOR}📁 ${dir_name}${RESET}${LINE1_PRIMARY}, wielding: ${YELLOW}🎯 ${tier}${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}⚙️ ${commands_count} Commands${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}🔌 ${mcps_count} MCPs${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}🤖 ${agents_count} Agents${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}🪝 ${hooks_count} Hooks${RESET}"

# Add ADW info if available
if [ "$adw_count" -gt 0 ]; then
    printf "${LINE1_PRIMARY}, ${RESET}${CYAN}⚡ ${adw_count} ADWs${RESET}"
fi
printf "\n"

# LINE 2 - MCP names list
printf "${LINE2_PRIMARY}🔌 MCPs${RESET}${LINE2_PRIMARY}${SEPARATOR_COLOR}: ${RESET}${mcp_names_formatted}${RESET}\n"

# LINE 3 - Daily cost only
printf "${LINE3_PRIMARY}💎 Total Cost${RESET}${LINE3_PRIMARY}${SEPARATOR_COLOR}: ${RESET}${BRIGHT_ORANGE}${daily_cost:-N/A}${RESET}\n"