#!/bin/bash
# Grid Status Line - Shows mission status in terminal
# Part of The Grid - Multi-agent orchestration for Claude Code
# https://github.com/JamesWeatherhead/grid
#
# Usage: source this file, then call grid_statusline or grid_status_compact
#
# Can be used in two ways:
# 1. Shell prompt integration (source and call functions)
# 2. Claude Code status line (reads JSON from stdin)

# Colors
CYAN='\033[38;5;39m'
GREEN='\033[32m'
YELLOW='\033[33m'
RED='\033[31m'
DIM='\033[2m'
RESET='\033[0m'

# Grid icon (hexagon for TRON aesthetic)
GRID_ICON='\342\254\241'  # Unicode hexagon

# Full status line with all details
# Reads from .grid/STATE.md and .grid/budget.json
grid_statusline() {
    local state_file=".grid/STATE.md"
    local budget_file=".grid/budget.json"

    # Default values
    local mission="No active mission"
    local phase="--"
    local block="--"
    local cost="\$0.00"
    local agents="0"
    local status="idle"

    # Parse STATE.md if exists
    if [[ -f "$state_file" ]]; then
        # Extract mission/cluster name
        local extracted_mission
        extracted_mission=$(grep -m1 "^cluster:" "$state_file" 2>/dev/null | cut -d: -f2- | xargs)
        if [[ -z "$extracted_mission" ]]; then
            extracted_mission=$(grep -m1 "^mission:" "$state_file" 2>/dev/null | cut -d: -f2- | xargs)
        fi
        [[ -n "$extracted_mission" ]] && mission="$extracted_mission"

        # Extract phase
        local extracted_phase
        extracted_phase=$(grep -m1 "^Phase:" "$state_file" 2>/dev/null | sed 's/Phase: *\([0-9]*\).*/\1/')
        [[ -n "$extracted_phase" ]] && phase="$extracted_phase"

        # Extract block
        local extracted_block
        extracted_block=$(grep -m1 "^Block:" "$state_file" 2>/dev/null | sed 's/Block: *\([0-9]*\).*/\1/')
        [[ -n "$extracted_block" ]] && block="$extracted_block"

        # Extract status
        local extracted_status
        extracted_status=$(grep -m1 "^Status:" "$state_file" 2>/dev/null | cut -d: -f2- | xargs)
        [[ -n "$extracted_status" ]] && status="$extracted_status"

        # Count active agents (look for running status markers)
        agents=$(grep -c "status: running\|Status: In progress" "$state_file" 2>/dev/null || echo "0")
    fi

    # Parse budget.json if exists
    if [[ -f "$budget_file" ]]; then
        local spent
        spent=$(jq -r '.total_spent // .spent // 0' "$budget_file" 2>/dev/null)
        if [[ -n "$spent" && "$spent" != "null" ]]; then
            cost=$(printf "\$%.2f" "$spent")
        fi
    fi

    # Truncate mission name if too long
    if [[ ${#mission} -gt 30 ]]; then
        mission="${mission:0:27}..."
    fi

    # Color status based on value
    local status_color="$GREEN"
    case "$status" in
        *progress*|*running*|*active*)
            status_color="$YELLOW"
            ;;
        *complete*|*done*)
            status_color="$GREEN"
            ;;
        *fail*|*error*|*blocked*)
            status_color="$RED"
            ;;
    esac

    # Build status line
    local output=""
    output+="${CYAN}GRID${RESET}"
    output+=" ${DIM}|${RESET} ${GREEN}${mission}${RESET}"
    output+=" ${DIM}|${RESET} Phase: ${phase}"
    output+=" ${DIM}|${RESET} Block: ${block}"
    output+=" ${DIM}|${RESET} Agents: ${agents}"
    output+=" ${DIM}|${RESET} Cost: ${cost}"

    echo -e "$output"
}

# Compact one-line version for shell prompts
# Shows: hexagon icon + phase/block or "idle"
grid_status_compact() {
    local state_file=".grid/STATE.md"

    if [[ -f "$state_file" ]]; then
        local phase block status

        # Extract phase number
        phase=$(grep -m1 "^Phase:" "$state_file" 2>/dev/null | sed 's/Phase: *\([0-9]*\).*/\1/')
        [[ -z "$phase" ]] && phase="?"

        # Extract block number
        block=$(grep -m1 "^Block:" "$state_file" 2>/dev/null | sed 's/Block: *\([0-9]*\).*/\1/')
        [[ -z "$block" ]] && block="?"

        # Check if in progress
        status=$(grep -m1 "^Status:" "$state_file" 2>/dev/null | cut -d: -f2- | xargs)

        if [[ "$status" == *"progress"* || "$status" == *"active"* ]]; then
            echo -e "${CYAN}${GRID_ICON}${RESET} ${YELLOW}${phase}/${block}${RESET}"
        else
            echo -e "${CYAN}${GRID_ICON}${RESET} ${phase}/${block}"
        fi
    else
        echo -e "${CYAN}${GRID_ICON}${RESET} ${DIM}idle${RESET}"
    fi
}

# Claude Code status line mode - reads JSON from stdin
# This is designed to work with Claude Code's statusLine configuration
grid_statusline_claude() {
    local input
    input=$(cat)

    # Parse Claude Code context JSON
    local model cost_usd context_pct
    model=$(echo "$input" | jq -r '.model.display_name // "?"' 2>/dev/null)
    cost_usd=$(echo "$input" | jq -r '.cost.total_cost_usd // 0' 2>/dev/null)
    context_pct=$(echo "$input" | jq -r '.context_window.used_percentage // 0' 2>/dev/null)

    # Format values
    local cost_fmt context_fmt
    cost_fmt=$(printf "\$%.4f" "$cost_usd")
    context_fmt=$(printf "%.0f%%" "$context_pct")

    # Get Grid state if available
    local grid_state=""
    if [[ -f ".grid/STATE.md" ]]; then
        local status phase block
        status=$(grep -m1 "^Status:" .grid/STATE.md 2>/dev/null | cut -d: -f2- | xargs)
        phase=$(grep -m1 "^Phase:" .grid/STATE.md 2>/dev/null | sed 's/Phase: *\([0-9]*\).*/\1/')
        block=$(grep -m1 "^Block:" .grid/STATE.md 2>/dev/null | sed 's/Block: *\([0-9]*\).*/\1/')

        if [[ -n "$phase" && -n "$block" ]]; then
            grid_state=" ${DIM}|${RESET} ${CYAN}GRID${RESET} ${phase}/${block}"
        fi
    fi

    # Git branch if in repo
    local git_branch=""
    if git rev-parse --git-dir > /dev/null 2>&1; then
        local branch
        branch=$(git branch --show-current 2>/dev/null)
        if [[ -n "$branch" ]]; then
            git_branch=" ${DIM}|${RESET} ${branch}"
        fi
    fi

    # Output final status line
    echo -e "${CYAN}[${model}]${RESET} ${cost_fmt} ${DIM}|${RESET} ${context_fmt} ctx${grid_state}${git_branch}"
}

# Export functions for use in subshells
export -f grid_statusline grid_status_compact grid_statusline_claude

# If script is run directly with stdin (Claude Code mode), use that
if [[ ! -t 0 ]]; then
    grid_statusline_claude
fi
