#!/usr/bin/env bash
# cpu_check.sh — CPU usage % and thermal temperature.
set -euo pipefail

os=$(uname -s)

if [ "$os" = "Darwin" ]; then
  # `top -l 1 -n 0` prints "CPU usage: X% user, Y% sys, Z% idle".
  # Usage is 100 minus the idle figure that precedes the literal `idle`.
  USAGE=$(top -l 1 -n 0 -s 0 2>/dev/null | awk '
    /^CPU usage/ {
      for (i = 1; i <= NF; i++) {
        if ($i == "idle") { gsub(/%/, "", $(i - 1)); printf "%.1f", 100 - $(i - 1) }
      }
    }' || true)
else
  USAGE=$(top -bn1 2>/dev/null | awk '/^%Cpu/ {print 100 - $8}' || true)
  if [ -z "$USAGE" ]; then
    CORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1)
    USAGE=$(awk -v cores="$CORES" '{print ($1+$2+$3)*100/cores}' /proc/loadavg 2>/dev/null || echo "0")
  fi
fi

[ -z "$USAGE" ] && USAGE=0

TEMP=""
if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
  TEMP=$(awk '{printf "%.1f", $1/1000}' /sys/class/thermal/thermal_zone0/temp 2>/dev/null || true)
fi

if [ -n "$TEMP" ]; then
  echo "{\"health\":\"healthy\",\"metrics\":{\"cpu_pct\":$USAGE,\"cpu_temp\":$TEMP}}"
else
  echo "{\"health\":\"healthy\",\"metrics\":{\"cpu_pct\":$USAGE}}"
fi
