#!/bin/bash
set -e

# Momentry Runtime Start Script
# This script starts the momentry services

echo "========================================"
echo "Momentry Runtime Starting"
echo "========================================"

# Set environment
export HOME=/Users/accusys
export USER=accusys
export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin:$PATH"

# Database configuration
export DATABASE_URL="postgres://accusys@localhost:5432/momentry"
export REDIS_URL="redis://accusys:accusys@localhost:6379"
export OLLAMA_HOST="http://localhost:11434"

# Change to project directory
cd /Users/accusys/momentry_core_0.1

# Check dependencies
echo "Checking dependencies..."

# Check PostgreSQL
if ! pg_isready -h localhost -p 5432 -U accusys > /dev/null 2>&1; then
    echo "WARNING: PostgreSQL is not ready"
fi

# Check Redis
if ! redis-cli -a accusys ping > /dev/null 2>&1; then
    echo "WARNING: Redis is not ready"
fi

# Check Ollama
if ! curl -s http://localhost:11434/api/tags > /dev/null 2>&1; then
    echo "WARNING: Ollama is not ready"
fi

echo "Dependencies checked."

# Start API server in background
echo "Starting API server..."
./target/release/momentry server --host 127.0.0.1 --port 3000 >> momentry_runtime/logs/stdout.log 2>&1 &
API_PID=$!
echo "API server started (PID: $API_PID)"

# Save PID to file
echo $API_PID > momentry_runtime/logs/momentry.pid

echo "========================================"
echo "Momentry Runtime Started"
echo "========================================"
echo "API Server: http://127.0.0.1:3000"
echo "Log file: momentry_runtime/logs/stdout.log"
echo ""
echo "To stop: kill \$(cat momentry_runtime/logs/momentry.pid)"
