#!/usr/bin/env bash
# Gilfoyle Pyroscope Discovery
# Usage: ./scripts/discover-pyroscope [env ...]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_SCRIPT="$SCRIPT_DIR/config"

# Colors for output
BOLD='\033[1m'
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

if [[ ! -f "$CONFIG_SCRIPT" ]]; then
    exit 1
fi

if [[ $# -gt 0 ]]; then
    deployments="$*"
else
    deployments=$("$CONFIG_SCRIPT" --list pyroscope)
    if [[ "$deployments" == "(none configured)" ]]; then
        exit 0
    fi
fi

echo -e "${BLUE}=== Pyroscope Deployments ===${NC}"

TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT

current_time_ms() {
    local t=${EPOCHREALTIME:-$(date +%s).000}
    local s=${t%.*}
    local us=${t#*.}
    us=$(printf "%-06s" "$us" | cut -c1-6)
    echo $(( s * 1000 + 10#${us%???} ))
}

discover_dep() {
    local dep="$1"
    local out="$TMP_DIR/$dep"
    
    {
        START_TIME=$(current_time_ms)
        echo -e "deployment: ${BOLD}$dep${NC}"
        response=$("$SCRIPT_DIR/pyroscope-services" "$dep" "1h" 2>/dev/null || echo "")
        
        END_TIME=$(current_time_ms)
        DURATION=$(( END_TIME - START_TIME ))
        
        count=$(echo "$response" | grep -c . || true)
        
        if [[ "$count" -gt 0 ]]; then
            echo -e "  ${GREEN}$count services found (last 1h)${NC} (${DURATION}ms)"
            echo "$response" | sed 's/^/  - /' | head -n 10
            if [[ "$count" -gt 10 ]]; then
                echo "  - ... (and $((count - 10)) more)"
            fi
        else
            echo -e "  ${RED}No services found (last 1h)${NC} (${DURATION}ms)"
        fi
    } > "$out" 2>&1
}

for dep in $deployments; do
    discover_dep "$dep" &
done
wait

for dep in $deployments; do
    [[ -f "$TMP_DIR/$dep" ]] && cat "$TMP_DIR/$dep"
done