#!/bin/bash
set -e

# Defaults
COMPLETE_MODE=false
SINCE="48h"
HOPSWORKS_NS=""  # Empty = auto-detect, otherwise = specified namespace
HOPSWORKS_FLAG=false
MAX_PARALLEL=10
KUEUE_NS=""  # Empty = not set, "all" = all namespaces, otherwise = specific namespace
RONDB_NS=""
RONDB_FLAG=false
PVC_EXTRACT_IMAGE=""  # Empty = disabled, set via --pvc-extract

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --complete) COMPLETE_MODE=true; shift ;;
    --since) SINCE="$2"; shift 2 ;;
    --since=*) SINCE="${1#*=}"; shift ;;
    --parallel) MAX_PARALLEL="$2"; shift 2 ;;
    --parallel=*) MAX_PARALLEL="${1#*=}"; shift ;;
    --hopsworks)
      HOPSWORKS_FLAG=true
      # Check if next arg exists and is not a flag
      if [[ -n "${2:-}" && ! "$2" =~ ^- ]]; then
        HOPSWORKS_NS="$2"
        shift 2
      else
        HOPSWORKS_NS=""  # Will be auto-detected later
        shift
      fi
      ;;
    --hopsworks=*)
      HOPSWORKS_FLAG=true
      HOPSWORKS_NS="${1#*=}"
      # Empty value will be auto-detected later
      shift
      ;;
    --kueue)
      # Check if next arg exists and is not a flag
      if [[ -n "${2:-}" && ! "$2" =~ ^- ]]; then
        KUEUE_NS="$2"
        shift 2
      else
        KUEUE_NS="all"
        shift
      fi
      ;;
    --kueue=*)
      KUEUE_NS="${1#*=}"
      [ -z "$KUEUE_NS" ] && KUEUE_NS="all"
      shift
      ;;
    --rondb)
      RONDB_FLAG=true
      # Check if next arg exists and is not a flag
      if [[ -n "${2:-}" && ! "$2" =~ ^- ]]; then
        RONDB_NS="$2"
        shift 2
      else
        RONDB_NS=""  # Will be resolved later
        shift
      fi
      ;;
    --rondb=*)
      RONDB_FLAG=true
      RONDB_NS="${1#*=}"
      shift
      ;;
    --pvc-extract)
      # Check if next arg exists and is not a flag
      if [[ -n "${2:-}" && ! "$2" =~ ^- ]]; then
        PVC_EXTRACT_IMAGE="$2"
        shift 2
      else
        PVC_EXTRACT_IMAGE="docker.hops.works/hopsworks/hwutils:1.3"
        shift
      fi
      ;;
    --pvc-extract=*)
      PVC_EXTRACT_IMAGE="${1#*=}"
      [ -z "$PVC_EXTRACT_IMAGE" ] && PVC_EXTRACT_IMAGE="docker.hops.works/hopsworks/hwutils:1.3"
      shift
      ;;
    -h|--help)
      echo "Usage: $0 [--hopsworks [namespace]] [--rondb [namespace]] [--kueue [namespace]] [options]"
      echo ""
      echo "Modes (at least one required):"
      echo "  --hopsworks [ns]  Collect core debug info (default: auto-detect or 'hopsworks')"
      echo "  --rondb [ns]      Collect RonDB logs (default: same as --hopsworks or 'hopsworks')"
      echo "  --kueue [ns]      Collect Kueue info (default: all namespaces)"
      echo ""
      echo "Options:"
      echo "  --complete           Collect all logs including old completed jobs"
      echo "  --since <dur>        Time window for logs (default: 48h). Examples: 1h, 30m, 2d"
      echo "  --parallel <N>       Max parallel jobs (default: 10)"
      echo "  --pvc-extract [img]  Use helper pod to extract RonDB logs from PVCs (for crashlooping pods)"
      echo "                       Default image: docker.hops.works/hopsworks/hwutils:1.3"
      echo ""
      echo "Examples:"
      echo "  $0 --hopsworks                        # Auto-detect hopsworks namespace"
      echo "  $0 --hopsworks mynamespace            # Core debug from specific namespace"
      echo "  $0 --rondb                            # RonDB logs (auto-detect namespace)"
      echo "  $0 --hopsworks --rondb                # Core debug + RonDB logs"
      echo "  $0 --kueue                            # Kueue info only (all namespaces)"
      echo "  $0 --hopsworks --rondb --kueue        # All modes combined"
      echo "  $0 --rondb --pvc-extract              # Extract RonDB PVC logs via helper pod"
      exit 0 ;;
    -*) echo "Unknown option: $1"; exit 1 ;;
    *) echo "Unknown argument: $1. Use --hopsworks <ns> for core debug."; exit 1 ;;
  esac
done

# Validate: at least one mode must be specified
if [ "$HOPSWORKS_FLAG" = false ] && [ "$RONDB_FLAG" = false ] && [ -z "$KUEUE_NS" ]; then
  echo "Error: At least one of --hopsworks, --rondb, or --kueue must be specified"
  echo "Use -h for help"
  exit 1
fi

# Pre-flight check
if ! command -v kubectl &>/dev/null; then
  echo "ERROR: kubectl not found in PATH"
  exit 1
fi

# Auto-detect hopsworks namespace via helm, or return empty string
detect_hopsworks_namespace() {
  if command -v helm &>/dev/null; then
    helm list -A -o json 2>/dev/null | grep -o '"namespace":"[^"]*"' | grep -i hopsworks | head -1 | cut -d'"' -f4
  fi
}

# Auto-detect namespace if --hopsworks is active but no namespace specified
if [ "$HOPSWORKS_FLAG" = true ] && [ -z "$HOPSWORKS_NS" ]; then
  HOPSWORKS_NS=$(detect_hopsworks_namespace)
  if [ -n "$HOPSWORKS_NS" ]; then
    echo "Auto-detected hopsworks installation in namespace: $HOPSWORKS_NS"
  else
    HOPSWORKS_NS="hopsworks"
    echo "Using default namespace: $HOPSWORKS_NS"
  fi
fi

# Resolve RonDB namespace if --rondb is active but no namespace specified
if [ "$RONDB_FLAG" = true ] && [ -z "$RONDB_NS" ]; then
  if [ "$HOPSWORKS_FLAG" = true ]; then
    RONDB_NS="$HOPSWORKS_NS"
  else
    RONDB_NS=$(detect_hopsworks_namespace)
    if [ -n "$RONDB_NS" ]; then
      echo "Auto-detected hopsworks installation in namespace: $RONDB_NS"
    else
      RONDB_NS="hopsworks"
      echo "Using default namespace for RonDB: $RONDB_NS"
    fi
  fi
fi

# Warn if --pvc-extract is set without --rondb
if [ -n "$PVC_EXTRACT_IMAGE" ] && [ "$RONDB_FLAG" = false ]; then
  echo "Warning: --pvc-extract has no effect without --rondb"
fi

# Unique run ID for labeling helper pods (scoped cleanup, safe for concurrent runs)
RUN_ID="run-$$-$(date +%s)"

# Export variables for use in subshells
export COMPLETE_MODE SINCE HOPSWORKS_NS RONDB_NS PVC_EXTRACT_IMAGE RUN_ID

# Cleanup helper pods on exit (only those created by this run)
cleanup_helper_pods() {
  if [ -n "$PVC_EXTRACT_IMAGE" ] && [ -n "$RONDB_NS" ]; then
    kubectl delete pods -n "$RONDB_NS" -l "app=rondb-log-helper,run-id=$RUN_ID" --wait=false 2>/dev/null || true
  fi
}
trap cleanup_helper_pods EXIT

# Job throttling - wait if we have too many background jobs
throttle() {
  while [ "$(jobs -r | wc -l)" -ge "$MAX_PARALLEL" ]; do
    sleep 0.1
  done
}

# Convert duration to hours (for cutoff calculation)
duration_to_hours() {
  local dur=$1 num="${dur%[a-zA-Z]*}" unit="${dur##*[0-9]}"
  case "$unit" in
    m) echo $((num / 60)) ;;
    h) echo "$num" ;;
    d) echo $((num * 24)) ;;
    *) echo "24" ;;
  esac
}

# Get cutoff timestamp (ISO 8601) - works on Linux/macOS/Git Bash
get_cutoff_time() {
  local hours=$1
  # GNU date (Linux, Git Bash on Windows)
  date -u -d "$hours hours ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null && return
  # BSD date (macOS)
  date -u -v-${hours}H +%Y-%m-%dT%H:%M:%SZ 2>/dev/null && return
  # Fallback: include everything
  echo "1970-01-01T00:00:00Z"
}

# Get filtered pod list (skip old completed jobs unless --complete)
get_filtered_pods() {
  local ns=$1
  if [ "$COMPLETE_MODE" = true ]; then
    kubectl get pods -n "$ns" -o jsonpath='{.items[*].metadata.name}'
    return
  fi

  local cutoff_hours cutoff
  cutoff_hours=$(duration_to_hours "$SINCE")
  cutoff=$(get_cutoff_time "$cutoff_hours")

  # Extract: name|phase|finishedAt
  kubectl get pods -n "$ns" -o go-template='{{range .items}}{{.metadata.name}}|{{.status.phase}}|{{with (index .status.containerStatuses 0)}}{{if .state.terminated}}{{.state.terminated.finishedAt}}{{end}}{{end}}
{{end}}' | while IFS='|' read -r name phase finished; do
    [ -z "$name" ] && continue
    # Include non-Succeeded pods (Running, Pending, Failed, etc.)
    [ "$phase" != "Succeeded" ] && echo "$name" && continue
    # Include Succeeded pods within time window (ISO 8601 is lexicographically sortable)
    [ -z "$finished" ] && echo "$name" && continue
    [[ "$finished" > "$cutoff" ]] && echo "$name"
  done
}

function log_deployments() {
  local namespace=$1
  mkdir -p logs/deployments/$namespace
  for dep in $(kubectl get deployments -n $namespace -o jsonpath='{.items[*].metadata.name}'); do
    throttle
    (kubectl describe deployment -n $namespace $dep > logs/deployments/$namespace/$dep.txt || echo "Failed to log Deployment $dep" >&2) &
  done
}

function log_statefulsets() {
  local namespace=$1
  mkdir -p logs/statefulsets/$namespace
  for sts in $(kubectl get statefulsets -n $namespace -o jsonpath='{.items[*].metadata.name}'); do
    throttle
    (kubectl describe statefulset -n $namespace $sts > logs/statefulsets/$namespace/$sts.txt || echo "Failed to log StatefulSet $sts" >&2) &
  done
}

# Collect logs for a single pod (called in parallel)
function collect_pod_logs() {
  local namespace=$1 pod=$2
  mkdir -p logs/pods/logs/$namespace/$pod
  for container in $(kubectl get pods -n $namespace $pod -o jsonpath='{.spec.containers[*].name}' 2>/dev/null); do
    if [ "$COMPLETE_MODE" = true ]; then
      kubectl logs -n $namespace $pod $container > logs/pods/logs/$namespace/$pod/$container.log 2>/dev/null || true
    else
      kubectl logs -n $namespace $pod $container --since=$SINCE > logs/pods/logs/$namespace/$pod/$container.log 2>/dev/null || true
    fi
    kubectl logs -n $namespace $pod $container --previous > logs/pods/logs/$namespace/$pod/$container.previous.log 2>/dev/null || true
  done
  for container in $(kubectl get pods -n $namespace $pod -o jsonpath='{.spec.initContainers[*].name}' 2>/dev/null); do
    if [ "$COMPLETE_MODE" = true ]; then
      kubectl logs -n $namespace $pod $container > logs/pods/logs/$namespace/$pod/$container.log 2>/dev/null || true
    else
      kubectl logs -n $namespace $pod $container --since=$SINCE > logs/pods/logs/$namespace/$pod/$container.log 2>/dev/null || true
    fi
    kubectl logs -n $namespace $pod $container --previous > logs/pods/logs/$namespace/$pod/$container.previous.log 2>/dev/null || true
  done
}

function get_logs() {
  local namespace=$1
  mkdir -p logs/pods/logs/$namespace
  for pod in $(get_filtered_pods "$namespace"); do
    throttle
    collect_pod_logs "$namespace" "$pod" &
  done
}

function describe_pod() {
  local namespace=$1
  mkdir -p logs/pods/describe/$namespace
  for pod in $(get_filtered_pods "$namespace"); do
    throttle
    (kubectl describe pod -n $namespace $pod > logs/pods/describe/$namespace/$pod.txt || echo "Failed to describe Pod $pod" >&2) &
  done
}

function describe_pvc() {
  local namespace=$1
  mkdir -p logs/pvc/$namespace
  for p in $(kubectl get pvc -n $namespace -o jsonpath='{.items[*].metadata.name}'); do
    throttle
    (kubectl describe pvc -n $namespace $p > logs/pvc/$namespace/$p.txt || echo "Failed to describe PVC $p" >&2) &
  done
  mkdir -p logs/pv
  for p in $(kubectl get pv -o jsonpath='{.items[*].metadata.name}'); do
    throttle
    (kubectl describe pv $p > logs/pv/$p.txt || echo "Failed to describe PV $p" >&2) &
  done
}

# Discover RonDB pods by name prefix (all phases, not just Running)
discover_rondb_pods() {
  local ns=$1 prefix=$2
  kubectl get pods -n "$ns" -o name \
    | grep "^pod/${prefix}" | sed 's|pod/||' | sort || true
}

# Copy a directory from a pod (compressed transfer, requires tar+gzip in the container)
# Falls back to helper pod if --pvc-extract is enabled and direct exec fails
copy_pod_dir() {
  local ns=$1 pod=$2 remote_path=$3 local_path=$4
  local remote_dir remote_base
  remote_dir=$(dirname "$remote_path")
  remote_base=$(basename "$remote_path")
  mkdir -p "$local_path"

  # Try direct exec first (|| true prevents set -e from aborting before fallback)
  kubectl exec -n "$ns" "$pod" -- tar czf - -C "$remote_dir" "$remote_base" 2>/dev/null \
    | tar xzf - -C "$local_path" 2>/dev/null || true

  # Check if the expected subdirectory was actually extracted (not stale data)
  if [ -e "$local_path/$remote_base" ]; then
    return 0
  fi

  # Direct exec failed — try helper pod fallback if enabled
  if [ -n "$PVC_EXTRACT_IMAGE" ]; then
    echo "WARNING: Direct exec failed for $pod, trying PVC helper pod fallback..." >&2
    copy_via_helper_pod "$ns" "$pod" "$remote_path" "$local_path"
  else
    echo "WARNING: Failed to copy $remote_path from $pod (use --pvc-extract to extract logs from PVC)" >&2
  fi
}

# Fallback: mount the pod's PVC via a helper pod and extract logs from it
copy_via_helper_pod() {
  local ns=$1 pod=$2 remote_path=$3 local_path=$4
  local helper_name="log-helper-${pod}"

  # Get the node the pod is scheduled on
  local node
  node=$(kubectl get pod -n "$ns" "$pod" -o jsonpath='{.spec.nodeName}' 2>/dev/null || true)
  if [ -z "$node" ]; then
    echo "WARNING: Cannot determine node for $pod, skipping PVC fallback" >&2
    return 1
  fi

  # Find volume mounts from the first container: "name|mountPath\n..."
  local mounts
  mounts=$(kubectl get pod -n "$ns" "$pod" -o go-template='{{range (index .spec.containers 0).volumeMounts}}{{.name}}|{{.mountPath}}{{"\n"}}{{end}}' 2>/dev/null || true)

  # Find the longest-prefix-matching mount for remote_path
  local best_vol="" best_mount=""
  while IFS='|' read -r vol_name mount_path; do
    [ -z "$vol_name" ] && continue
    case "$remote_path" in
      "${mount_path}"*|"${mount_path}")
        if [ ${#mount_path} -gt ${#best_mount} ]; then
          best_vol="$vol_name"
          best_mount="$mount_path"
        fi
        ;;
    esac
  done <<< "$mounts"

  if [ -z "$best_vol" ]; then
    echo "WARNING: No volume mount found covering $remote_path in $pod" >&2
    return 1
  fi

  # Get the PVC claim name for this volume
  local pvc_name
  pvc_name=$(kubectl get pod -n "$ns" "$pod" -o go-template="{{range .spec.volumes}}{{if eq .name \"$best_vol\"}}{{if .persistentVolumeClaim}}{{.persistentVolumeClaim.claimName}}{{end}}{{end}}{{end}}" 2>/dev/null || true)

  if [ -z "$pvc_name" ]; then
    echo "WARNING: Volume '$best_vol' in $pod is not backed by a PVC, skipping" >&2
    return 1
  fi

  echo "  Helper pod '$helper_name' on node '$node' for PVC '$pvc_name'" >&2

  # Create helper pod (read-only mount, same node)
  if ! kubectl apply -n "$ns" -f - <<ENDYAML 2>/dev/null
apiVersion: v1
kind: Pod
metadata:
  name: "${helper_name}"
  labels:
    app: rondb-log-helper
    run-id: "${RUN_ID}"
spec:
  nodeName: "${node}"
  restartPolicy: Never
  terminationGracePeriodSeconds: 0
  containers:
  - name: helper
    image: "${PVC_EXTRACT_IMAGE}"
    command: ["sleep", "300"]
    volumeMounts:
    - name: data
      mountPath: "${best_mount}"
      readOnly: true
  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: "${pvc_name}"
      readOnly: true
ENDYAML
  then
    echo "WARNING: Failed to create helper pod '$helper_name' (RBAC, name collision, or invalid spec)" >&2
    return 1
  fi

  if ! kubectl wait --for=condition=Ready "pod/${helper_name}" -n "$ns" --timeout=120s 2>/dev/null; then
    echo "WARNING: Helper pod '$helper_name' did not become ready, cleaning up" >&2
    kubectl delete pod "$helper_name" -n "$ns" --wait=false 2>/dev/null || true
    return 1
  fi

  # Extract logs via helper
  local remote_dir remote_base
  remote_dir=$(dirname "$remote_path")
  remote_base=$(basename "$remote_path")
  kubectl exec -n "$ns" "$helper_name" -- tar czf - -C "$remote_dir" "$remote_base" 2>/dev/null \
    | tar xzf - -C "$local_path" 2>/dev/null || \
    echo "WARNING: Failed to extract $remote_path via helper pod '$helper_name'" >&2

  # Cleanup
  kubectl delete pod "$helper_name" -n "$ns" --wait=false 2>/dev/null || true
}

# Collect all data for a single RonDB pod (called as a background job)
collect_rondb_pod() {
  local ns=$1 pod=$2 remote_log_path=$3 local_subdir=$4

  # Copy RonDB log directory from the container (non-fatal so logs/describe still run)
  copy_pod_dir "$ns" "$pod" "$remote_log_path" "logs/rondb/${local_subdir}" || true

  # Collect kubectl logs for all containers (reuse existing function)
  collect_pod_logs "$ns" "$pod"

  # Describe the pod
  mkdir -p "logs/pods/describe/$ns"
  kubectl describe pod -n "$ns" "$pod" \
    > "logs/pods/describe/$ns/${pod}.txt" 2>/dev/null || true
}

echo "Parallel jobs: $MAX_PARALLEL"
[ "$HOPSWORKS_FLAG" = true ] && echo "Hopsworks namespace: $HOPSWORKS_NS"
[ "$RONDB_FLAG" = true ] && echo "RonDB namespace: $RONDB_NS"
[ -n "$PVC_EXTRACT_IMAGE" ] && echo "PVC extract image: $PVC_EXTRACT_IMAGE"
[ -n "$KUEUE_NS" ] && echo "Kueue namespace: $KUEUE_NS"
echo "Mode: $([ "$COMPLETE_MODE" = true ] && echo 'complete' || echo "default (skip completed jobs older than $SINCE)")"
mkdir -p logs

set -x

# Core hopsworks debug collection (only if --hopsworks is active)
if [ "$HOPSWORKS_FLAG" = true ]; then
  # Cluster info (parallel)
  (kubectl version > logs/cluster-version.txt 2>/dev/null || true) &
  (kubectl cluster-info > logs/cluster-info.txt 2>/dev/null || true) &

  # List all the pods (parallel)
  kubectl get pods -n $HOPSWORKS_NS -o wide > logs/pods.$HOPSWORKS_NS.txt &
  kubectl get pods -n kube-system -o wide > logs/pods.kube-system.txt &
  # List all (parallel)
  kubectl get all -n $HOPSWORKS_NS -o wide > logs/all.$HOPSWORKS_NS.txt &
  kubectl get all -n kube-system -o wide > logs/all.kube-system.txt &

  # Events - all recent events (parallel)
  (kubectl get events -n $HOPSWORKS_NS --sort-by='.lastTimestamp' > logs/events.$HOPSWORKS_NS.txt || true) &
  (kubectl get events -n kube-system --sort-by='.lastTimestamp' > logs/events.kube-system.txt || true) &

  # Services and Ingresses (parallel)
  (kubectl get services -n $HOPSWORKS_NS -o wide > logs/services.$HOPSWORKS_NS.txt || true) &
  (kubectl get services -n kube-system -o wide > logs/services.kube-system.txt || true) &
  (kubectl get ingress -n $HOPSWORKS_NS -o wide > logs/ingress.$HOPSWORKS_NS.txt 2>/dev/null || true) &
  (kubectl get ingress -n kube-system -o wide > logs/ingress.kube-system.txt 2>/dev/null || true) &

  # ConfigMaps list - names only (parallel)
  (kubectl get configmaps -n $HOPSWORKS_NS > logs/configmaps.$HOPSWORKS_NS.txt || true) &
  (kubectl get configmaps -n kube-system > logs/configmaps.kube-system.txt || true) &

  # HPA status (parallel)
  (kubectl get hpa -n $HOPSWORKS_NS -o wide > logs/hpa.$HOPSWORKS_NS.txt 2>/dev/null || true) &
  (kubectl get hpa -n kube-system -o wide > logs/hpa.kube-system.txt 2>/dev/null || true) &

  # Resource usage (parallel)
  (kubectl top pods -n $HOPSWORKS_NS > logs/top.$HOPSWORKS_NS.txt 2>/dev/null || true) &
  (kubectl top pods -n kube-system > logs/top.kube-system.txt 2>/dev/null || true) &

  # Get Nodes
  kubectl describe nodes > logs/nodes.txt &
  (kubectl top nodes > logs/nodes-top.txt 2>/dev/null || true) &
  wait

  # Describe Deployments (parallel)
  log_deployments $HOPSWORKS_NS
  log_deployments kube-system
  wait

  # Describe StatefulSets (parallel)
  log_statefulsets $HOPSWORKS_NS
  log_statefulsets kube-system
  wait

  # Get Logs (parallel - this is the slowest part)
  get_logs $HOPSWORKS_NS
  get_logs kube-system
  wait

  # Describe Pods (parallel)
  describe_pod $HOPSWORKS_NS
  describe_pod kube-system
  wait

  # Describe PVC (parallel)
  describe_pvc $HOPSWORKS_NS
  describe_pvc kube-system
  wait

  # CRD Definition
  kubectl get crd -A > logs/crds.txt
fi

# RonDB log collection (only if --rondb is active)
if [ "$RONDB_FLAG" = true ]; then
  MGMD_PODS=$(discover_rondb_pods "$RONDB_NS" "mgmds-")
  NODE_GROUP_PODS=$(discover_rondb_pods "$RONDB_NS" "node-group-")
  MYSQLD_PODS=$(discover_rondb_pods "$RONDB_NS" "mysqlds-")
  RDRS_PODS=$(discover_rondb_pods "$RONDB_NS" "rdrs-")

  if [[ -z "$MGMD_PODS" && -z "$NODE_GROUP_PODS" && -z "$MYSQLD_PODS" && -z "$RDRS_PODS" ]]; then
    echo "WARNING: No RonDB pods found in namespace '$RONDB_NS' (looked for mgmds-*, node-group-*, mysqlds-*, rdrs-*)"
  else
    mkdir -p logs/rondb

    for POD in $MGMD_PODS; do
      throttle
      collect_rondb_pod "$RONDB_NS" "$POD" "/srv/hops/mysql-cluster/log" "mgmd/$POD" &
    done
    for POD in $NODE_GROUP_PODS; do
      throttle
      collect_rondb_pod "$RONDB_NS" "$POD" "/srv/hops/mysql-cluster/default_storage/log" "node-group/$POD" &
    done
    for POD in $MYSQLD_PODS; do
      throttle
      collect_rondb_pod "$RONDB_NS" "$POD" "/srv/hops/mysql-cluster/log" "mysqld/$POD" &
    done
    for POD in $RDRS_PODS; do
      throttle
      collect_rondb_pod "$RONDB_NS" "$POD" "/srv/hops/mysql-cluster/log" "rdrs/$POD" &
    done
    wait
  fi
fi

# Kueue cluster-scoped resources (always collected)
mkdir -p logs/kueue
(kubectl get clusterqueues -o wide > logs/kueue/clusterqueues.txt 2>/dev/null || true) &
(kubectl describe clusterqueues > logs/kueue/clusterqueues-describe.txt 2>/dev/null || true) &
(kubectl get resourceflavors -o wide > logs/kueue/resourceflavors.txt 2>/dev/null || true) &
(kubectl describe resourceflavors > logs/kueue/resourceflavors-describe.txt 2>/dev/null || true) &
(kubectl get topologies -o wide > logs/kueue/topologies.txt 2>/dev/null || true) &
(kubectl describe topologies > logs/kueue/topologies-describe.txt 2>/dev/null || true) &
(kubectl get admissionchecks -o wide > logs/kueue/admissionchecks.txt 2>/dev/null || true) &
(kubectl describe admissionchecks > logs/kueue/admissionchecks-describe.txt 2>/dev/null || true) &
wait

# Kueue namespace-scoped resources (only if --kueue flag is set)
if [ -n "$KUEUE_NS" ]; then
  if [ "$KUEUE_NS" = "all" ]; then
    NS_FLAG="-A"
    mkdir -p logs/kueue/workloads logs/kueue/localqueues
  else
    NS_FLAG="-n $KUEUE_NS"
    mkdir -p logs/kueue/workloads/$KUEUE_NS logs/kueue/localqueues/$KUEUE_NS
  fi

  # Workloads
  (kubectl get workloads $NS_FLAG -o wide > logs/kueue/workloads.txt 2>/dev/null || true) &

  # LocalQueues
  (kubectl get localqueues $NS_FLAG -o wide > logs/kueue/localqueues.txt 2>/dev/null || true) &
  (kubectl describe localqueues $NS_FLAG > logs/kueue/localqueues-describe.txt 2>/dev/null || true) &

  wait

  # Describe individual workloads (parallel)
  if [ "$KUEUE_NS" = "all" ]; then
    for wl in $(kubectl get workloads -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {end}' 2>/dev/null); do
      ns="${wl%/*}"
      name="${wl#*/}"
      throttle
      mkdir -p logs/kueue/workloads/$ns
      (kubectl describe workload -n $ns $name > logs/kueue/workloads/$ns/$name.txt 2>/dev/null || true) &
    done
  else
    for name in $(kubectl get workloads -n $KUEUE_NS -o jsonpath='{.items[*].metadata.name}' 2>/dev/null); do
      throttle
      (kubectl describe workload -n $KUEUE_NS $name > logs/kueue/workloads/$KUEUE_NS/$name.txt 2>/dev/null || true) &
    done
  fi
  wait

  # Describe individual localqueues (parallel)
  if [ "$KUEUE_NS" = "all" ]; then
    for lq in $(kubectl get localqueues -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {end}' 2>/dev/null); do
      ns="${lq%/*}"
      name="${lq#*/}"
      throttle
      mkdir -p logs/kueue/localqueues/$ns
      (kubectl describe localqueue -n $ns $name > logs/kueue/localqueues/$ns/$name.txt 2>/dev/null || true) &
    done
  else
    for name in $(kubectl get localqueues -n $KUEUE_NS -o jsonpath='{.items[*].metadata.name}' 2>/dev/null); do
      throttle
      (kubectl describe localqueue -n $KUEUE_NS $name > logs/kueue/localqueues/$KUEUE_NS/$name.txt 2>/dev/null || true) &
    done
  fi
  wait
fi
