#!/usr/bin/env bash
# ============================================================================
# BLACKROAD OS, INC. - PROPRIETARY AND CONFIDENTIAL
# Copyright (c) 2025-2026 BlackRoad OS, Inc. All Rights Reserved.
# ============================================================================
# br-kpi - Live KPI dashboard and resume data updater

set -eo pipefail

PINK='\033[38;5;205m'
AMBER='\033[38;5;214m'
GREEN='\033[38;5;82m'
BLUE='\033[38;5;69m'
DIM='\033[38;5;240m'
RESET='\033[0m'

show_banner() {
  echo -e "${PINK}╔═══════════════════════════════════════════╗${RESET}"
  echo -e "${PINK}║${RESET}  ${PINK}BLACKROAD KPIs${RESET} — Live Metrics Dashboard"
  echo -e "${PINK}╚═══════════════════════════════════════════╝${RESET}"
}

cmd_live() {
  show_banner
  echo ""

  # GitHub
  echo -e "${BLUE}GitHub${RESET}"
  local repos orgs commits_pub commits_priv
  repos=$(gh repo list --limit 500 --json name --jq 'length' 2>/dev/null || echo "?")
  orgs=$(gh api user/orgs --jq 'length' 2>/dev/null || echo "?")
  commits_pub=$(gh api graphql -f query='query { viewer { contributionsCollection { totalCommitContributions } } }' --jq '.data.viewer.contributionsCollection.totalCommitContributions' 2>/dev/null || echo "?")
  commits_priv=$(gh api graphql -f query='query { viewer { contributionsCollection { restrictedContributionsCount } } }' --jq '.data.viewer.contributionsCollection.restrictedContributionsCount' 2>/dev/null || echo "?")

  printf "  %-28s %s\n" "Personal repos:" "$repos"
  printf "  %-28s %s\n" "Organizations:" "$orgs"
  printf "  %-28s %s\n" "Commits (public, YTD):" "$commits_pub"
  printf "  %-28s %s\n" "Commits (private, YTD):" "$commits_priv"

  # Local
  echo ""
  echo -e "${BLUE}Local${RESET}"
  local tools dbs
  tools=$(ls ~/bin 2>/dev/null | wc -l | tr -d ' ')
  dbs=$(find ~/.blackroad -name '*.db' 2>/dev/null | wc -l | tr -d ' ')
  printf "  %-28s %s\n" "CLI tools (~/bin):" "$tools"
  printf "  %-28s %s\n" "SQLite databases:" "$dbs"

  # Cloudflare
  echo ""
  echo -e "${BLUE}Cloudflare${RESET}"
  local workers websites
  workers=$(ls -d ~/blackroad-operator/workers/*/ 2>/dev/null | wc -l | tr -d ' ')
  websites=$(ls -d ~/blackroad-operator/websites/*/ 2>/dev/null | wc -l | tr -d ' ')
  printf "  %-28s %s\n" "Workers:" "$workers"
  printf "  %-28s %s\n" "Websites:" "$websites"
  printf "  %-28s %s\n" "Custom domains:" "54"

  # Fleet
  echo ""
  echo -e "${BLUE}Fleet${RESET}"
  for node in alice cecilia lucidia; do
    local ip
    case $node in
      alice) ip="192.168.4.49" ;;
      cecilia) ip="192.168.4.96" ;;
      lucidia) ip="192.168.4.38" ;;
    esac
    if ping -c1 -W1 "$ip" &>/dev/null; then
      printf "  %-28s ${GREEN}●${RESET} %s\n" "$node ($ip):" "online"
    else
      printf "  %-28s \033[38;5;196m●${RESET} %s\n" "$node ($ip):" "offline"
    fi
  done

  # Velocity
  echo ""
  echo -e "${BLUE}Velocity${RESET}"
  local contribs streak avg_cpd
  contribs=$(gh api graphql -f query='{ user(login:"blackboxprogramming") { contributionsCollection { contributionCalendar { totalContributions } } } }' --jq '.data.viewer.contributionsCollection.contributionCalendar.totalContributions' 2>/dev/null || echo "?")
  streak=$(python3 -c "
import json, subprocess
r = subprocess.run(['gh','api','graphql','-f','query={ user(login:\"blackboxprogramming\") { contributionsCollection { contributionCalendar { weeks { contributionDays { contributionCount } } } } } }'], capture_output=True, text=True, timeout=15)
d = json.loads(r.stdout)
days = [day for w in d['data']['user']['contributionsCollection']['contributionCalendar']['weeks'] for day in w['contributionDays']]
days.reverse()
s = 0
for day in days:
    if day['contributionCount'] > 0: s += 1
    else: break
print(s)
" 2>/dev/null || echo "?")
  printf "  %-28s %s\n" "Contributions (YTD):" "$contribs"
  printf "  %-28s %s days\n" "Commit streak:" "$streak"

  # GitHub Traffic
  echo ""
  echo -e "${BLUE}GitHub Traffic (14d)${RESET}"
  local clones views
  clones=$(gh api repos/blackboxprogramming/BlackRoad-Operating-System/traffic/clones --jq '.count' 2>/dev/null || echo "?")
  views=$(gh api repos/blackboxprogramming/BlackRoad-Operating-System/traffic/views --jq '.count' 2>/dev/null || echo "?")
  printf "  %-28s %s\n" "Clones (main repo):" "$clones"
  printf "  %-28s %s\n" "Views (main repo):" "$views"

  # Gateway
  echo ""
  echo -e "${BLUE}AI Gateway${RESET}"
  local gw
  gw=$(curl -sf --max-time 3 "https://api.blackroad.io/healthz" 2>/dev/null)
  if [[ -n "$gw" ]]; then
    printf "  %-28s ${GREEN}●${RESET} %s\n" "api.blackroad.io:" "online"
    local model_count
    model_count=$(curl -sf --max-time 3 "https://api.blackroad.io/v1/models" 2>/dev/null | python3 -c "import sys,json;print(len(json.load(sys.stdin)['data']))" 2>/dev/null || echo "?")
    printf "  %-28s %s\n" "Models available:" "$model_count"
  else
    printf "  %-28s \033[38;5;196m●${RESET} %s\n" "api.blackroad.io:" "offline"
  fi

  echo ""
  echo -e "${DIM}Updated: $(date '+%Y-%m-%d %H:%M:%S')${RESET}"
}

cmd_update() {
  echo -e "${AMBER}Updating resume-data.json with live KPIs...${RESET}"
  python3 ~/blackroad-operator/packages/blackroad-os-metrics/scripts/update_resume_data.py
  echo -e "${GREEN}Done.${RESET}"
}

cmd_help() {
  show_banner
  echo ""
  echo -e "${BLUE}Commands:${RESET}"
  echo "  live     Show live KPI dashboard"
  echo "  update   Update resume-data.json with live data"
  echo ""
}

case "${1:-live}" in
  live|l)    cmd_live ;;
  update|u)  cmd_update ;;
  help|--help|-h) cmd_help ;;
  *)         echo "Unknown: $1"; cmd_help ;;
esac
