#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
NPU_INDEX=${NPU_INDEX:-$("${PYTHON:-python3}" "${SCRIPT_DIR}/detect_npu_index.py")}
NPU_CHIP_INDEX=${NPU_CHIP_INDEX:-0}

set +e
health_output=$(npu-smi info -t health -i "${NPU_INDEX}" -c "${NPU_CHIP_INDEX}" 2>&1)
status=$?
set -e
printf '%s\n' "${health_output}"

if [[ ${status} -ne 0 ]] || ! grep -Eq 'Health Status[[:space:]]*:[[:space:]]*OK' <<<"${health_output}"; then
    echo "NPU ${NPU_INDEX}/${NPU_CHIP_INDEX} is not healthy; aborting before vLLM startup." >&2
    exit 42
fi
