#!/usr/bin/env bash
# br-gateway - BlackRoad API Gateway CLI (local)
set -eo pipefail

source "$HOME/.blackroad/config/nodes.sh" 2>/dev/null || {
  PINK='\033[38;5;205m'; AMBER='\033[38;5;214m'; GREEN='\033[38;5;82m'; RESET='\033[0m'
}
NC="$RESET"

case "$1" in
    start)
        echo -e "${PINK}Starting Gateway on cecilia...${NC}"
        ssh cecilia '~/br-gateway start'
        ;;

    stop)
        ssh cecilia '~/br-gateway stop'
        ;;

    status)
        ssh cecilia '~/br-gateway status'
        ;;

    health)
        ssh cecilia '~/br-gateway health'
        ;;

    metrics)
        echo -e "${PINK}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${GREEN}           FLEET METRICS${NC}"
        echo -e "${PINK}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
        for node in "${ALL_NODES[@]}"; do
            local ip="${NODE_IP[$node]:-}"; local user="${NODE_USER[$node]:-}"
            [[ -z "$ip" ]] && continue
            echo -e "${AMBER}$node:${NC}"
            local info
            info=$(ssh -o ConnectTimeout=3 -o BatchMode=yes "${user}@${ip}" \
              'printf "CPU:%s MEM:%s DISK:%s LOAD:%s" \
                "$(top -bn1 2>/dev/null | grep "Cpu" | awk "{print \$2}" || echo "?")" \
                "$(free 2>/dev/null | awk "/Mem:/{printf \"%.1f\", \$3/\$2*100}" || echo "?")" \
                "$(df / | awk "NR==2{print \$5}")" \
                "$(cat /proc/loadavg 2>/dev/null | awk "{print \$1}" || echo "?")"' 2>/dev/null) || info="offline"
            echo "  $info"
        done
        ;;

    logs)
        service="${2:-api}"
        echo -e "${PINK}Collecting $service logs...${NC}"
        for node in "${ALL_NODES[@]}"; do
            local ip="${NODE_IP[$node]:-}"; local user="${NODE_USER[$node]:-}"
            [[ -z "$ip" ]] && continue
            echo -e "\n${AMBER}=== $node ===${NC}"
            case "$service" in
                api) ssh -o ConnectTimeout=3 -o BatchMode=yes "${user}@${ip}" 'tail -5 ~/blackroad-api/api.log 2>/dev/null' ;;
                mesh) ssh -o ConnectTimeout=3 -o BatchMode=yes "${user}@${ip}" 'tail -5 ~/.blackroad/mesh/hub.log 2>/dev/null' ;;
                eventbus) ssh -o ConnectTimeout=3 -o BatchMode=yes "${user}@${ip}" 'tail -5 ~/.blackroad/eventbus/logs/bus.log 2>/dev/null' ;;
                gateway) ssh -o ConnectTimeout=3 -o BatchMode=yes "${user}@${ip}" 'tail -5 ~/.blackroad/gateway/logs/gateway.log 2>/dev/null' ;;
            esac
        done
        ;;

    *)
        echo -e "${PINK}br-gateway${NC} - BlackRoad API Gateway"
        echo ""
        echo "Commands:"
        echo "  start       - Start Gateway on cecilia"
        echo "  stop        - Stop Gateway"
        echo "  status      - Show gateway status"
        echo "  health      - Check backend health"
        echo "  metrics     - Show fleet metrics"
        echo "  logs [svc]  - Show logs (api/mesh/eventbus/gateway)"
        ;;
esac
