#!/bin/bash

# Install script for Hundred Dollar Enforcer auto-start

set -e

echo "🚀 Installing Hundred Dollar Enforcer auto-start..."

# Get the directory of the script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed. Please install Node.js first."
    exit 1
fi

# Get Node.js path
NODE_PATH=$(which node)
NPM_PATH=$(which npm)
NPX_PATH="${NPM_PATH%npm}npx"

# Build the project
echo "📦 Building project..."
cd "$PROJECT_DIR"
npm install
npm run build

# Create plist file with correct paths
PLIST_NAME="com.hundredollar.enforcer.plist"
PLIST_PATH="$HOME/Library/LaunchAgents/$PLIST_NAME"

echo "📝 Creating launch agent configuration..."
cat > "$PROJECT_DIR/$PLIST_NAME" <<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>com.hundredollar.enforcer</string>
    
    <key>ProgramArguments</key>
    <array>
        <string>$NODE_PATH</string>
        <string>$PROJECT_DIR/dist/index.js</string>
        <string>start</string>
    </array>
    
    <key>WorkingDirectory</key>
    <string>$PROJECT_DIR</string>
    
    <key>RunAtLoad</key>
    <true/>
    
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    
    <key>StandardOutPath</key>
    <string>$HOME/Library/Logs/hundred-dollar-enforcer.log</string>
    
    <key>StandardErrorPath</key>
    <string>$HOME/Library/Logs/hundred-dollar-enforcer.error.log</string>
    
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>$HOME/.asdf/plugins/nodejs/shims:$HOME/.nvm/current/bin:$HOME/.volta/bin:$HOME/.fnm/current/bin:${NPM_PATH%npm}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        <key>NODE_ENV</key>
        <string>production</string>
        <key>HOME</key>
        <string>$HOME</string>
    </dict>
</dict>
</plist>
EOF

# Create LaunchAgents directory if it doesn't exist
mkdir -p "$HOME/Library/LaunchAgents"

# Copy plist file to LaunchAgents
echo "📋 Installing launch agent..."
cp "$PROJECT_DIR/$PLIST_NAME" "$PLIST_PATH"

# Load the launch agent
echo "▶️ Starting service..."
launchctl load "$PLIST_PATH"

echo "✅ Installation complete!"
echo ""
echo "The Hundred Dollar Enforcer will now:"
echo "  • Start automatically when you log in"
echo "  • Monitor your Claude API usage"
echo "  • Notify you if you're not spending enough"
echo ""
echo "📊 Logs can be found at:"
echo "  • $HOME/Library/Logs/hundred-dollar-enforcer.log"
echo "  • $HOME/Library/Logs/hundred-dollar-enforcer.error.log"
echo ""
echo "To stop the service, run: ./scripts/uninstall-autostart.sh"