#!/bin/bash
# Install the AI Pulse watcher as a launchd service on macOS.
# Runs once, every 5 minutes, in the background. Starts on login.
#
# Usage:
#   cd <this project>
#   bash watcher/install.sh
#
# To uninstall:
#   launchctl unload ~/Library/LaunchAgents/com.dewa.aipulse.watcher.plist
#   rm ~/Library/LaunchAgents/com.dewa.aipulse.watcher.plist

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PLIST_SRC="${PROJECT_ROOT}/watcher/com.dewa.aipulse.watcher.plist"
PLIST_DEST="${HOME}/Library/LaunchAgents/com.dewa.aipulse.watcher.plist"

echo "Project root: ${PROJECT_ROOT}"

# 1. Unload if already loaded
if launchctl list | grep -q com.dewa.aipulse.watcher; then
    echo "Unloading existing service..."
    launchctl unload "${PLIST_DEST}" 2>/dev/null || true
fi

# 2. Render plist with the real project path
mkdir -p "${HOME}/Library/LaunchAgents"
sed "s|PROJECT_ROOT|${PROJECT_ROOT}|g" "${PLIST_SRC}" > "${PLIST_DEST}"

# 3. Seed seen.json so the first poll doesn't back-fill every current item
echo "Seeding seen.json with current AI Pulse feed..."
/usr/bin/python3 "${PROJECT_ROOT}/watcher/ai_pulse_watcher.py" --seed || {
    echo "  (seed failed — feed may not be live yet; that's OK, the watcher will"
    echo "   start catching items as soon as the /ai-adoption-focus.json endpoint responds)"
}

# 4. Load the service
echo "Loading watcher as launchd service..."
launchctl load "${PLIST_DEST}"

echo ""
echo "Watcher installed and running."
echo "Logs: ${PROJECT_ROOT}/watcher/activity.log"
echo "      ${PROJECT_ROOT}/watcher/launchd.out.log"
echo "      ${PROJECT_ROOT}/watcher/launchd.err.log"
echo ""
echo "To check status: launchctl list | grep aipulse"
echo "To stop:        launchctl unload ${PLIST_DEST}"
