#!/usr/bin/env bash
# br-stats - BlackRoad Portfolio Statistics CLI (BR Visual Language Enhanced)
# Display professional achievements with live infrastructure data
set -euo pipefail

# Source centralized config
source "$HOME/.blackroad/config/nodes.sh" 2>/dev/null || true

# Legacy ANSI colors (fallback)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
BOLD='\033[1m'
DIM='\033[2m'
RESET='\033[0m'

# BR Semantic Colors (xterm-256)
BR_SUCCESS='\033[38;5;2m'       # OS_LAYER: SUCCESS (green)
BR_EXEC='\033[38;5;64m'         # EXECUTION: EXEC_HIGH
BR_MEMORY='\033[38;5;100m'      # MEMORY: MEM_PERSIST
BR_AGENT='\033[38;5;136m'       # AUTONOMY: AGENT_EXEC
BR_BRAND='\033[38;5;202m'       # PARADOX: EXEC_FORCE (brand hot)
BR_META='\033[38;5;244m'        # META: escape/commentary

# BR Shapes
SHAPE_SUCCESS="✓"
SHAPE_EXEC="▶"
SHAPE_MEMORY="●"
SHAPE_AGENT="◆"
SHAPE_METRIC="█"

# Function to print header with BR shapes
print_header() {
    echo -e "${BR_BRAND}${BOLD}"
    cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║                                                              ║
║   ██████╗ ██╗      █████╗  ██████╗██╗  ██╗██████╗  ██████╗  ║
║   ██╔══██╗██║     ██╔══██╗██╔════╝██║ ██╔╝██╔══██╗██╔═══██╗ ║
║   ██████╔╝██║     ███████║██║     █████╔╝ ██████╔╝██║   ██║ ║
║   ██╔══██╗██║     ██╔══██║██║     ██╔═██╗ ██╔══██╗██║   ██║ ║
║   ██████╔╝███████╗██║  ██║╚██████╗██║  ██╗██║  ██║╚██████╔╝ ║
║   ╚═════╝ ╚══════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝  ║
║                                                              ║
║        PORTFOLIO STATISTICS — Visual Language Mode           ║
║                  Alexa Amundson - 2026                       ║
╚══════════════════════════════════════════════════════════════╝
EOF
    echo -e "${RESET}"
}

# Function to print section header with BR shapes
print_section() {
    local title="$1"
    local shape="${2:-$SHAPE_METRIC}"
    echo ""
    echo -e "${BR_EXEC}${BOLD}═══════════════════════════════════════════════════════════════${RESET}"
    echo -e "${WHITE}${BOLD}  $shape $title${RESET}"
    echo -e "${BR_EXEC}${BOLD}═══════════════════════════════════════════════════════════════${RESET}"
    echo ""
}

# Function to print metric with BR semantic colors
print_metric() {
    local emoji="$1"
    local label="$2"
    local value="$3"
    local br_color="${4:-$WHITE}"
    local shape="${5:-$SHAPE_METRIC}"
    
    printf "  ${shape} ${emoji}  ${DIM}%-33s${RESET} ${br_color}${BOLD}%s${RESET}\n" "$label" "$value"
}

# Function to print progress bar with BR shapes
print_progress() {
    local label="$1"
    local current="$2"
    local total="$3"
    local width=30
    
    local percentage=$((current * 100 / total))
    local filled=$((width * current / total))
    local empty=$((width - filled))
    
    # Use BR shapes for progress
    printf "  ${SHAPE_AGENT} %-28s [" "$label"
    
    # Color progress by zone
    if [ "$percentage" -lt 50 ]; then
        color="$BR_MEMORY"
    elif [ "$percentage" -lt 75 ]; then
        color="$BR_EXEC"
    else
        color="$BR_SUCCESS"
    fi
    
    printf "${color}"
    printf "%${filled}s" | tr ' ' '█'
    printf "${RESET}"
    printf "%${empty}s" | tr ' ' '░'
    printf "] %3d%%\n" "$percentage"
}

# Collect live infrastructure data (fast, cached 5min)
CACHE_FILE="$HOME/.blackroad/stats-cache.json"
CACHE_TTL=300

collect_live() {
    # Use cache if fresh enough
    if [[ -f "$CACHE_FILE" ]]; then
        local age=$(( $(date +%s) - $(stat -f%m "$CACHE_FILE" 2>/dev/null || stat -c%Y "$CACHE_FILE" 2>/dev/null || echo 0) ))
        if [[ "$age" -lt "$CACHE_TTL" ]]; then
            return 0
        fi
    fi

    # Count local repos
    local repo_count
    repo_count=$(ls -d "$HOME"/*/.git 2>/dev/null | wc -l | tr -d ' ')

    # Count scripts
    local script_count
    script_count=$(find "$HOME/bin" -maxdepth 1 -type f 2>/dev/null | wc -l | tr -d ' ')
    local home_scripts
    home_scripts=$(find "$HOME" -maxdepth 1 -name '*.sh' -type f 2>/dev/null | wc -l | tr -d ' ')
    script_count=$((script_count + home_scripts))

    # Count fleet nodes online
    local nodes_online=0
    for node in "${PI_NODES[@]}"; do
        local ip="${NODE_IP[$node]:-}"
        [[ -z "$ip" ]] && continue
        ping -c 1 -W 1 "$ip" &>/dev/null && ((nodes_online++)) || true
    done

    # Docker containers locally
    local containers=0
    command -v docker &>/dev/null && containers=$(docker ps -q 2>/dev/null | wc -l | tr -d ' ')

    # SQLite databases
    local db_count
    db_count=$(find "$HOME/.blackroad" -name '*.db' -type f 2>/dev/null | wc -l | tr -d ' ')

    # Write cache
    mkdir -p "$(dirname "$CACHE_FILE")"
    cat > "$CACHE_FILE" <<JSON
{
  "repos": $repo_count,
  "scripts": $script_count,
  "nodes_online": $nodes_online,
  "nodes_total": ${#PI_NODES[@]},
  "containers": $containers,
  "databases": $db_count,
  "collected": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
JSON
}

# Read cached value
_cv() {
    jq -r ".$1 // \"?\"" "$CACHE_FILE" 2>/dev/null || echo "?"
}

# Main stats display with BR visual language
show_stats() {
    collect_live 2>/dev/null || true
    clear
    print_header

    # Infrastructure Scale (MEMORY zone - LIVE DATA)
    print_section "INFRASTRUCTURE SCALE (live)" "$SHAPE_MEMORY"
    print_metric "📦" "Local Repositories" "$(_cv repos)" "$BR_BRAND" "$SHAPE_MEMORY"
    print_metric "⚡" "CLI Tools + Scripts" "$(_cv scripts)" "$BR_BRAND" "$SHAPE_EXEC"
    print_metric "🖥️" "Fleet Nodes Online" "$(_cv nodes_online)/$(_cv nodes_total)" "$BR_SUCCESS" "$SHAPE_MEMORY"
    print_metric "📦" "Docker Containers" "$(_cv containers)" "$BR_EXEC" "$SHAPE_MEMORY"
    print_metric "💾" "SQLite Databases" "$(_cv databases)" "$BR_MEMORY" "$SHAPE_MEMORY"
    print_metric "🌐" "Production Domains" "48+" "$BR_AGENT" "$SHAPE_MEMORY"

    # Agent Platform (AUTONOMY zone)
    print_section "AI AGENT PLATFORM" "$SHAPE_AGENT"
    print_metric "🖥️" "Distributed Nodes" "7" "$BR_MEMORY" "$SHAPE_AGENT"
    print_metric "⚡" "Hailo-8 Accelerators" "2 (52 TOPS)" "$BR_BRAND" "$SHAPE_AGENT"
    print_metric "🧠" "Ollama Models (Cecilia)" "16" "$BR_SUCCESS" "$SHAPE_AGENT"
    print_metric "📦" "Cloudflare Pages" "95+" "$BR_EXEC" "$SHAPE_AGENT"
    print_metric "🌐" "KV Namespaces" "40" "$BR_MEMORY" "$SHAPE_AGENT"
    print_metric "💾" "D1 Databases" "8" "$BR_EXEC" "$SHAPE_AGENT"
    
    # Business Impact (EXECUTION zone - actions/results)
    print_section "BUSINESS IMPACT" "$SHAPE_EXEC"
    print_metric "💵" "Enterprise Sales Generated" "\$23M+" "$BR_SUCCESS" "$SHAPE_EXEC"
    print_metric "📈" "AUM Opportunities Identified" "\$18.4M" "$BR_EXEC" "$SHAPE_EXEC"
    print_metric "🎯" "Sales Goal Achievement" "92%" "$BR_SUCCESS" "$SHAPE_EXEC"
    print_metric "⭐" "Client Satisfaction Rating" "97%" "$BR_SUCCESS" "$SHAPE_EXEC"
    print_metric "📊" "Efficiency Improvement" "33%" "$BR_EXEC" "$SHAPE_EXEC"
    print_metric "🚀" "Workflow Speed Increase" "50%+" "$BR_BRAND" "$SHAPE_EXEC"
    
    # Credentials (OS_LAYER zone - core system)
    print_section "CREDENTIALS & LICENSES" "$SHAPE_SUCCESS"
    print_metric "✅" "FINRA Series 7" "Active" "$BR_SUCCESS" "$SHAPE_SUCCESS"
    print_metric "✅" "FINRA Series 63" "Active" "$BR_SUCCESS" "$SHAPE_SUCCESS"
    print_metric "✅" "FINRA Series 65" "Active" "$BR_SUCCESS" "$SHAPE_SUCCESS"
    print_metric "✅" "FINRA SIE" "Active" "$BR_SUCCESS" "$SHAPE_SUCCESS"
    print_metric "🏥" "Life & Health Insurance (MN)" "Active" "$BR_SUCCESS" "$SHAPE_SUCCESS"
    print_metric "🎓" "B.A. Strategic Communication" "UMN 2022" "$BR_EXEC" "$SHAPE_SUCCESS"
    
    # Agent Breakdown with BR visual progress
    print_section "AGENT DISTRIBUTION (30k capacity)" "$SHAPE_AGENT"
    echo ""
    print_progress "AI Research Agents" 12592 30000
    print_progress "Code Deployment Agents" 8407 30000
    print_progress "Infrastructure Agents" 5401 30000
    print_progress "Monitoring Agents" 3600 30000
    echo ""
    
    # Quick Links
    print_section "QUICK LINKS" "$SHAPE_MEMORY"
    echo -e "  ${SHAPE_MEMORY} ${BOLD}GitHub:${RESET}   https://github.com/blackboxprogramming"
    echo -e "  ${SHAPE_MEMORY} ${BOLD}LinkedIn:${RESET} https://linkedin.com/in/alexaamundson"
    echo -e "  ${SHAPE_MEMORY} ${BOLD}Website:${RESET}  https://blackroad.io"
    echo -e "  ${SHAPE_MEMORY} ${BOLD}Email:${RESET}    amundsonalexa@gmail.com"
    echo -e "  ${SHAPE_MEMORY} ${BOLD}Phone:${RESET}    (507) 828-0842"
    echo ""
    
    # Footer with BR meta commentary
    echo -e "${BR_META}═══════════════════════════════════════════════════════════════${RESET}"
    echo -e "${BR_META}  Built 1,094 repositories in under 2 years using AI as team${RESET}"
    echo -e "${BR_META}  AI isn't the future—it's the engineering team${RESET}"
    echo -e "${BR_META}  ${DIM}Colors: ✓ success ▶ execution ● memory ◆ agents █ metrics${RESET}"
    echo -e "${BR_META}═══════════════════════════════════════════════════════════════${RESET}"
    echo ""
}

# Function to show specific section
show_section() {
    case "$1" in
        infra|infrastructure)
            collect_live 2>/dev/null || true
            print_section "INFRASTRUCTURE SCALE (live)" "$SHAPE_MEMORY"
            print_metric "📦" "Local Repositories" "$(_cv repos)" "$BR_BRAND" "$SHAPE_MEMORY"
            print_metric "⚡" "CLI Tools + Scripts" "$(_cv scripts)" "$BR_BRAND" "$SHAPE_EXEC"
            print_metric "🖥️" "Fleet Nodes Online" "$(_cv nodes_online)/$(_cv nodes_total)" "$BR_SUCCESS" "$SHAPE_MEMORY"
            print_metric "📦" "Docker Containers" "$(_cv containers)" "$BR_EXEC" "$SHAPE_MEMORY"
            print_metric "💾" "SQLite Databases" "$(_cv databases)" "$BR_MEMORY" "$SHAPE_MEMORY"
            print_metric "🌐" "Production Domains" "48+" "$BR_AGENT" "$SHAPE_MEMORY"
            ;;
        agents)
            print_section "AI AGENT PLATFORM" "$SHAPE_AGENT"
            print_metric "🖥️" "Distributed Nodes" "7" "$BR_MEMORY" "$SHAPE_AGENT"
            print_metric "⚡" "Hailo-8 Accelerators" "2 (52 TOPS)" "$BR_BRAND" "$SHAPE_AGENT"
            print_metric "🧠" "Ollama Models (Cecilia)" "16" "$BR_SUCCESS" "$SHAPE_AGENT"
            print_metric "📦" "Cloudflare Pages" "95+" "$BR_EXEC" "$SHAPE_AGENT"
            print_metric "🌐" "KV Namespaces" "40" "$BR_MEMORY" "$SHAPE_AGENT"
            print_metric "💾" "D1 Databases" "8" "$BR_EXEC" "$SHAPE_AGENT"
            ;;
        business|sales)
            print_section "BUSINESS IMPACT" "$SHAPE_EXEC"
            print_metric "💵" "Enterprise Sales Generated" "\$23M+" "$BR_SUCCESS" "$SHAPE_EXEC"
            print_metric "📈" "AUM Opportunities Identified" "\$18.4M" "$BR_EXEC" "$SHAPE_EXEC"
            print_metric "🎯" "Sales Goal Achievement" "92%" "$BR_SUCCESS" "$SHAPE_EXEC"
            print_metric "⭐" "Client Satisfaction Rating" "97%" "$BR_SUCCESS" "$SHAPE_EXEC"
            print_metric "📊" "Efficiency Improvement" "33%" "$BR_EXEC" "$SHAPE_EXEC"
            print_metric "🚀" "Workflow Speed Increase" "50%+" "$BR_BRAND" "$SHAPE_EXEC"
            ;;
        *)
            echo "Usage: br-stats [infra|agents|business|json]"
            echo "Run without arguments for full dashboard"
            exit 1
            ;;
    esac
    echo ""
}

# Function to export stats as JSON (live + static)
export_json() {
    collect_live 2>/dev/null || true
    local repos; repos=$(_cv repos)
    local scripts; scripts=$(_cv scripts)
    local nodes; nodes=$(_cv nodes_online)
    local containers; containers=$(_cv containers)
    local dbs; dbs=$(_cv databases)
    local collected; collected=$(_cv collected)

    cat <<JSON
{
  "name": "Alexa Amundson",
  "collected": "$collected",
  "infrastructure": {
    "local_repos": $repos,
    "scripts": $scripts,
    "fleet_nodes_online": $nodes,
    "fleet_nodes_total": ${#PI_NODES[@]},
    "containers": $containers,
    "databases": $dbs,
    "cloudflare_pages": 95,
    "kv_namespaces": 40,
    "d1_databases": 8,
    "custom_domains": 48
  },
  "agent_platform": {
    "distributed_nodes": 7,
    "hailo_accelerators": 2,
    "hailo_tops": 52,
    "ollama_models": 16
  },
  "business": {
    "sales_millions": 23,
    "aum_millions": 18.4,
    "goal_pct": 92,
    "satisfaction_pct": 97
  }
}
JSON
}

# Main
if [ $# -eq 0 ]; then
    show_stats
elif [ "$1" = "json" ]; then
    export_json
else
    show_section "$1"
fi
