#!/bin/bash
# Set up macOS Launch Agent so the Workout Planner starts automatically on login.
# Usage: ./scripts/setup-autostart.sh
#
# This creates a Launch Agent plist that runs scripts/start.sh on login.
# To remove: launchctl unload ~/Library/LaunchAgents/com.proof-of-work.plist

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
PLIST_NAME="com.proof-of-work"
PLIST_DIR="$HOME/Library/LaunchAgents"
PLIST_PATH="$PLIST_DIR/$PLIST_NAME.plist"
LOG_DIR="$PROJECT_DIR/logs"
NODE_PATH="$(which node)"

echo "=== Workout Planner — Auto-Start Setup ==="
echo ""
echo "Project:  $PROJECT_DIR"
echo "Node:     $NODE_PATH"
echo "Logs:     $LOG_DIR"
echo ""

# Check node exists
if [ -z "$NODE_PATH" ]; then
  echo "ERROR: node not found in PATH."
  echo "Make sure Node.js is installed (e.g. via nvm, homebrew, or nodejs.org)."
  exit 1
fi

# Build first if needed
if [ ! -d "$PROJECT_DIR/.next" ]; then
  echo "No production build found. Building now..."
  cd "$PROJECT_DIR"
  npm run build
  echo ""
fi

# Apply prisma migrations
echo "Applying database schema..."
cd "$PROJECT_DIR"
npx prisma db push --accept-data-loss 2>/dev/null || npx prisma db push
echo ""

mkdir -p "$PLIST_DIR"
mkdir -p "$LOG_DIR"

# Create the plist
cat > "$PLIST_PATH" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>$PLIST_NAME</string>

  <key>ProgramArguments</key>
  <array>
    <string>$NODE_PATH</string>
    <string>$PROJECT_DIR/node_modules/.bin/next</string>
    <string>start</string>
    <string>-p</string>
    <string>3000</string>
  </array>

  <key>WorkingDirectory</key>
  <string>$PROJECT_DIR</string>

  <key>EnvironmentVariables</key>
  <dict>
    <key>NODE_ENV</key>
    <string>production</string>
    <key>PATH</key>
    <string>$(dirname "$NODE_PATH"):/usr/local/bin:/usr/bin:/bin</string>
  </dict>

  <key>RunAtLoad</key>
  <true/>

  <key>KeepAlive</key>
  <true/>

  <key>StandardOutPath</key>
  <string>$LOG_DIR/server.log</string>

  <key>StandardErrorPath</key>
  <string>$LOG_DIR/server-error.log</string>
</dict>
</plist>
EOF

echo "Created: $PLIST_PATH"
echo ""

# Unload if already loaded, then load
launchctl unload "$PLIST_PATH" 2>/dev/null || true
launchctl load "$PLIST_PATH"

echo "=== Done! ==="
echo ""
echo "The server will now start automatically when you log in."
echo "It's also running right now at: http://localhost:3000"
echo ""
echo "Useful commands:"
echo "  Stop:     launchctl unload ~/Library/LaunchAgents/$PLIST_NAME.plist"
echo "  Start:    launchctl load ~/Library/LaunchAgents/$PLIST_NAME.plist"
echo "  Logs:     tail -f $LOG_DIR/server.log"
echo "  Rebuild:  ./scripts/rebuild.sh"
echo "  Remove:   launchctl unload ~/Library/LaunchAgents/$PLIST_NAME.plist && rm ~/Library/LaunchAgents/$PLIST_NAME.plist"
