#!/usr/bin/env bash
#
# Run the HaloPSA MCP server and monitor logs simultaneously
# This script starts the MCP server and then monitors the logs for errors
#
# MIT License Copyright (c) 2025 sulemanji.com MCP Team

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Default values
DEBUG=false
LOG_FILE="${HOME}/Library/Logs/Claude/mcp-server-halopsa.log"
ERROR_ONLY=false

# Show usage
function show_usage {
  echo -e "${BLUE}Usage:${NC}"
  echo -e "  ./run-and-monitor.sh [options]"
  echo -e ""
  echo -e "${BLUE}Options:${NC}"
  echo -e "  -d, --debug        Enable debug mode for the MCP server"
  echo -e "  -e, --error-only   Only show error messages in the log monitor"
  echo -e "  -l, --log-file     Custom log file path"
  echo -e "  -h, --help         Show this help message"
  echo -e ""
  echo -e "${BLUE}Examples:${NC}"
  echo -e "  ./run-and-monitor.sh"
  echo -e "  ./run-and-monitor.sh --debug"
  echo -e "  ./run-and-monitor.sh --error-only"
  echo -e "  ./run-and-monitor.sh --log-file /path/to/custom/log/file.log"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    -d|--debug)
      DEBUG=true
      shift
      ;;
    -e|--error-only)
      ERROR_ONLY=true
      shift
      ;;
    -l|--log-file)
      LOG_FILE="$2"
      shift 2
      ;;
    -h|--help)
      show_usage
      exit 0
      ;;
    *)
      echo -e "${RED}Error: Unknown option $1${NC}"
      show_usage
      exit 1
      ;;
  esac
done

# Project root directory
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null 2>&1 && pwd)"

# Check if Claude Desktop is installed
if [ ! -d "${HOME}/Library/Application Support/Claude" ]; then
  echo -e "${RED}Error: Claude Desktop doesn't seem to be installed${NC}"
  echo -e "The expected configuration directory doesn't exist at:"
  echo -e "${HOME}/Library/Application Support/Claude"
  echo -e ""
  echo -e "Please make sure Claude Desktop is installed and run at least once."
  exit 1
fi

# Check if log directory exists
LOG_DIR=$(dirname "$LOG_FILE")
if [ ! -d "$LOG_DIR" ]; then
  echo -e "${YELLOW}Warning: Log directory doesn't exist, creating it: $LOG_DIR${NC}"
  mkdir -p "$LOG_DIR"
fi

# Clear the log file if it exists
if [ -f "$LOG_FILE" ]; then
  echo -e "${YELLOW}Clearing previous log file...${NC}"
  > "$LOG_FILE"
fi

# Start the MCP server in the background
echo -e "${GREEN}Starting HaloPSA MCP server...${NC}"

if [ "$DEBUG" = true ]; then
  echo -e "${BLUE}Debug mode enabled${NC}"
  "$ROOT_DIR/bin/desktop-mcp" --debug > /dev/null 2>&1 &
else
  "$ROOT_DIR/bin/desktop-mcp" > /dev/null 2>&1 &
fi
MCP_PID=$!

# Check if the server started correctly
sleep 1
if ! kill -0 $MCP_PID 2>/dev/null; then
  echo -e "${RED}Error: MCP server failed to start${NC}"
  exit 1
fi

echo -e "${GREEN}MCP server started with PID: $MCP_PID${NC}"

# Start the log monitor
echo -e "${GREEN}Starting log monitor...${NC}"
if [ "$ERROR_ONLY" = true ]; then
  "$ROOT_DIR/scripts/monitor-logs.js" --log-file "$LOG_FILE" --error-only &
else
  "$ROOT_DIR/scripts/monitor-logs.js" --log-file "$LOG_FILE" &
fi
MONITOR_PID=$!

# Handle termination
function cleanup {
  echo -e "${YELLOW}Shutting down...${NC}"
  kill $MCP_PID 2>/dev/null
  kill $MONITOR_PID 2>/dev/null
  wait $MCP_PID 2>/dev/null
  wait $MONITOR_PID 2>/dev/null
  echo -e "${GREEN}Cleanup complete${NC}"
}

trap cleanup EXIT INT TERM

# Wait for both processes
echo -e "${BLUE}MCP server and monitor running. Press Ctrl+C to exit.${NC}"
wait $MCP_PID
