#!/bin/zsh
# virtual-hid-doctor — diagnose Karabiner-DriverKit-VirtualHIDDevice install.
# Detects every step of the install flow and tells you exactly what's missing.
# See components/macos/virtual-hid/INSTALL.md for the install procedure.
set -euo pipefail
BIN_DIR=${0:A:h}
ROOT_DIR=${BIN_DIR:h}

usage() {
  awk 'NR == 1 { next } /^set -/ { exit } { sub(/^# ?/, ""); print }' "${(%):-%x}"
}

case "${1:-}" in
  -h|--help|help)
    usage
    exit 0
    ;;
esac

c_grn() { printf '\033[32m  ✓ %s\033[0m\n' "$*"; }
c_red() { printf '\033[31m  ✗ %s\033[0m\n' "$*"; }
c_ylw() { printf '\033[33m  · %s\033[0m\n' "$*"; }

ok=1
miss=()

echo '── Karabiner-DriverKit-VirtualHIDDevice install diagnostics ──'

# 1) Manager .app
MGR='/Applications/.Karabiner-VirtualHIDDevice-Manager.app'
if [[ -d "$MGR" ]]; then
  c_grn "Manager .app present: $MGR"
else
  c_red "Manager .app missing"
  miss+=("Install .pkg from pqrs-org GitHub release")
  ok=0
fi

# 2) System extension activated
EXT_LIST=$(systemextensionsctl list 2>/dev/null || true)
if grep -qE 'org\.pqrs\..*VirtualHID' <<<"$EXT_LIST"; then
  state=$(grep -E 'org\.pqrs\..*VirtualHID' <<<"$EXT_LIST" | head -1)
  if grep -q '\[activated enabled\]' <<<"$state"; then
    c_grn "system extension: activated + enabled"
  else
    c_ylw "system extension present but not fully active: $state"
    miss+=("Run: sudo Karabiner-VirtualHIDDevice-Manager activate ; reboot ; allow in System Settings")
    ok=0
  fi
else
  c_red "system extension not registered"
  miss+=("Run: sudo Karabiner-VirtualHIDDevice-Manager activate")
  ok=0
fi

# 3) Daemon
if launchctl list 2>/dev/null | grep -q 'org.pqrs.service.daemon.Karabiner-DriverKit-VirtualHIDDeviceClient'; then
  c_grn "daemon launchd entry running"
else
  if pgrep -f 'Karabiner-VirtualHIDDevice' >/dev/null 2>&1; then
    c_ylw "daemon process running but no launchd entry"
  else
    c_red "daemon not running (likely needs reboot post-install)"
    miss+=("Reboot the machine; daemon auto-starts via launchd")
    ok=0
  fi
fi

# 4) IOKit HID nodes (only present after reboot + driver loaded)
if /usr/sbin/ioreg -p IOService -l 2>/dev/null | grep -q 'org_pqrs_Karabiner_DriverKit_VirtualHID'; then
  c_grn "IOKit HID nodes visible (driver loaded into kernel)"
else
  c_red "IOKit HID nodes missing"
  miss+=("Reboot — kernel does not load .dext without restart after activation")
  ok=0
fi

# 5) IPC socket
if find /private/var/folders -name 'Karabiner-DriverKit-VirtualHIDDevice*' -type s 2>/dev/null | head -1 | read; then
  c_grn "IPC socket present"
else
  c_ylw "IPC socket not found (will appear after daemon binds)"
fi

echo ''
if [[ $ok -eq 1 ]]; then
  printf '\033[32mREADY=1   bin/clicker --via-vhid is usable.\033[0m\n'
  exit 0
else
  printf '\033[33mREADY=0   action needed:\033[0m\n'
  for m in "${miss[@]}"; do printf '   • %s\n' "$m"; done
  echo ''
  echo "  详见: $ROOT_DIR/components/macos/virtual-hid/INSTALL.md"
  exit 2
fi
