#!/bin/bash
# vixy-vision Collector Setup for macOS
# Run this on Mac mini

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="${HOME}/vixy-vision-collector"
PLIST_NAME="com.vixy.vision-collector"
PLIST_PATH="${HOME}/Library/LaunchAgents/${PLIST_NAME}.plist"

echo "=========================================="
echo "  vixy-vision Collector Setup (macOS)"
echo "  Event collection for the fox 🦊"
echo "=========================================="
echo ""

# Check if running on macOS
if [[ "$(uname)" != "Darwin" ]]; then
    echo "This script is designed for macOS"
    exit 1
fi

# Create install directory
echo "[INFO] Creating install directory: ${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}"
cp "${SCRIPT_DIR}/collector.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/requirements.txt" "${INSTALL_DIR}/"

# Create virtual environment
echo "[INFO] Creating Python virtual environment..."
cd "${INSTALL_DIR}"
python3 -m venv venv
source venv/bin/activate

# Install dependencies
echo "[INFO] Installing dependencies..."
pip install --upgrade pip
pip install -r requirements.txt

# Create data directory
DATA_DIR="${HOME}/Documents/Vixy/events"
mkdir -p "${DATA_DIR}/snapshots"
echo "[INFO] Data directory: ${DATA_DIR}"

# Create launchd plist
echo "[INFO] Creating launchd service..."
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>${INSTALL_DIR}/venv/bin/python</string>
        <string>${INSTALL_DIR}/collector.py</string>
    </array>
    <key>WorkingDirectory</key>
    <string>${INSTALL_DIR}</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>VIXY_DATA_DIR</key>
        <string>${DATA_DIR}</string>
        <key>COLLECTOR_PORT</key>
        <string>8780</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/vixy-collector.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/vixy-collector.log</string>
</dict>
</plist>
EOF

echo ""
echo "=========================================="
echo "  Setup Complete! 🦊"
echo "=========================================="
echo ""
echo "Commands:"
echo "  Load:    launchctl load ${PLIST_PATH}"
echo "  Unload:  launchctl unload ${PLIST_PATH}"
echo "  Logs:    tail -f /tmp/vixy-collector.log"
echo ""
echo "Service will be available at:"
echo "  http://$(ipconfig getifaddr en0):8780/"
echo ""
echo "Configure camera servers with:"
echo "  COLLECTOR_URL=http://$(ipconfig getifaddr en0):8780/events"
echo ""
echo "[INFO] Start the collector with:"
echo "  launchctl load ${PLIST_PATH}"
