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

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR"

missing=()
python3 -c "import serial" 2>/dev/null || missing+=(pyserial)
python3 -c "import psutil" 2>/dev/null || missing+=(psutil)

if ((${#missing[@]})); then
  echo "Installing: ${missing[*]}"
  python3 -m pip install --user "${missing[@]}"
fi

CFG="$HOME/.config/pc-monitor/cloud.json"
if [[ ! -f "$CFG" ]]; then
  echo "First run — cloud push setup"
  bash "$DIR/setup-cloud-push.sh"
fi

echo "Open PC Monitor on the handheld, then leave this window running."
echo "Live dashboard: http://127.0.0.1:8765/"
echo

ARGS=(--cloud)
if [[ -n "${PORT:-}" ]]; then
  ARGS+=(--port "$PORT")
fi

python3 "$DIR/pc_monitor.py" "${ARGS[@]}" "$@"
code=$?

echo
echo "PC Monitor stopped (exit $code)."
read -r -p "Press Enter to close…" _
