#!/bin/bash
# manage_services.sh — LaunchAgent 일괄 관리
# 사용법: ./manage_services.sh status | start | stop | restart

SERVICES=(
  "com.syn-chat-bot.chat-bridge"
  "com.syn-chat-bot.heic-converter"
  "com.syn-chat-bot.caldav-bridge"
  "com.syn-chat-bot.devonthink-bridge"
  "com.syn-chat-bot.kb-writer"
  "com.syn-chat-bot.mail-bridge"
  "com.syn-chat-bot.inbox-processor"
  "com.syn-chat-bot.news-digest"
  "com.mlx-proxy"
)

PLIST_DIR="$HOME/Library/LaunchAgents"
SRC_DIR="$(cd "$(dirname "$0")" && pwd)"

case "$1" in
  status)
    for s in "${SERVICES[@]}"; do
      if launchctl list "$s" &>/dev/null; then
        pid=$(launchctl list "$s" 2>/dev/null | awk 'NR==2{print $1}')
        echo "✓ $s: LOADED (PID: ${pid:-?})"
      else
        echo "✗ $s: NOT LOADED"
      fi
    done
    ;;
  start)
    for s in "${SERVICES[@]}"; do
      plist="$PLIST_DIR/${s}.plist"
      src="$SRC_DIR/${s}.plist"
      if [ ! -f "$plist" ] && [ -f "$src" ]; then
        cp "$src" "$plist"
        echo "  Copied $s.plist to LaunchAgents"
      fi
      if [ -f "$plist" ]; then
        launchctl load "$plist" 2>/dev/null
        echo "✓ $s: started"
      else
        echo "✗ $s: plist not found"
      fi
    done
    ;;
  stop)
    for s in "${SERVICES[@]}"; do
      plist="$PLIST_DIR/${s}.plist"
      if [ -f "$plist" ]; then
        launchctl unload "$plist" 2>/dev/null
        echo "✓ $s: stopped"
      fi
    done
    ;;
  restart)
    "$0" stop
    sleep 1
    "$0" start
    ;;
  install)
    echo "Installing plist files to $PLIST_DIR..."
    for s in "${SERVICES[@]}"; do
      src="$SRC_DIR/${s}.plist"
      if [ -f "$src" ]; then
        cp "$src" "$PLIST_DIR/"
        echo "  ✓ $s"
      else
        echo "  ✗ $s: source plist not found"
      fi
    done
    echo "Done. Run '$0 start' to start services."
    ;;
  *)
    echo "Usage: $0 {status|start|stop|restart|install}"
    echo ""
    echo "  status   - Show service status"
    echo "  start    - Load and start all services"
    echo "  stop     - Unload all services"
    echo "  restart  - Stop then start"
    echo "  install  - Copy plist files to ~/Library/LaunchAgents"
    ;;
esac
