#!/usr/bin/env bash
# Usage: ./proc_stats.sh simple

set -euo pipefail

if [ $# -ne 1 ]; then
  echo "Usage: $0 <process-name>" >&2
  exit 1
fi

NAME="$1"

# Find PID (first match)
PID=$(pgrep -x "$NAME" | head -n1 || true)
if [ -z "$PID" ]; then
  echo "Process '$NAME' not found" >&2
  exit 1
fi

# Thread count:
# macOS: each line under ps -M -p <pid> is a thread (minus header)
THREADS=$(($(ps -M -p "$PID" | wc -l | tr -d ' ') - 1))

# One powermetrics sample (1 second)
PM_LINE=$(sudo powermetrics --samplers tasks --show-process-energy -i 1000 -n 1 2>/dev/null |
  awk -v pid="$PID" '$2 == pid')

if [ -z "$PM_LINE" ]; then
  echo "Could not find process $PID in powermetrics output" >&2
  exit 1
fi

# powermetrics columns (simplified):
# Name  ID  CPU_ms/s  User%  D1  D2  Wake_intr  Wake_pkg_idle  Energy
# We want Wake_intr + Wake_pkg_idle as total wakeups/sec.
# We'll compute that in awk.

WAKEUPS=$(echo "$PM_LINE" | awk '{printf "%.2f", $7 + $8}')

echo "name=$NAME pid=$PID threads=$THREADS wakeups_per_sec=$WAKEUPS"
