#!/bin/bash
#
# Start GooseFactory Learning Pipeline Service
#
# Usage:
#   ./start-service.sh           # Start in foreground
#   ./start-service.sh --bg      # Start in background
#   ./start-service.sh --stop    # Stop background service
#

set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="/tmp/learning-service.pid"
LOG_FILE="/tmp/learning-service.log"

case "${1:-}" in
  --bg|--background)
    echo "🚀 Starting Learning Pipeline service in background..."
    cd "$DIR"
    npx tsx src/service.ts > "$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    sleep 2
    if kill -0 $(cat "$PID_FILE" 2>/dev/null) 2>/dev/null; then
      echo "✅ Service started (PID: $(cat "$PID_FILE"))"
      echo "📋 Logs: $LOG_FILE"
      echo "🔍 Health check: curl http://localhost:4001/health"
    else
      echo "❌ Failed to start service. Check logs at $LOG_FILE"
      exit 1
    fi
    ;;
  
  --stop)
    if [ -f "$PID_FILE" ]; then
      PID=$(cat "$PID_FILE")
      echo "🛑 Stopping service (PID: $PID)..."
      kill "$PID" 2>/dev/null || true
      rm -f "$PID_FILE"
      echo "✅ Service stopped"
    else
      echo "ℹ️  No running service found"
    fi
    ;;
  
  --status)
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE" 2>/dev/null) 2>/dev/null; then
      echo "✅ Service is running (PID: $(cat "$PID_FILE"))"
      curl -s http://localhost:4001/health | jq .
    else
      echo "❌ Service is not running"
      exit 1
    fi
    ;;
  
  --logs)
    if [ -f "$LOG_FILE" ]; then
      tail -f "$LOG_FILE"
    else
      echo "❌ No log file found at $LOG_FILE"
      exit 1
    fi
    ;;
  
  *)
    echo "🚀 Starting Learning Pipeline service..."
    cd "$DIR"
    npx tsx src/service.ts
    ;;
esac
