#!/bin/bash

# Momentry Health Check Script

echo "========================================"
echo "Momentry Health Check"
echo "========================================"
echo ""

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

check() {
    local name="$1"
    local cmd="$2"
    
    if eval "$cmd" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} $name"
        return 0
    else
        echo -e "${RED}✗${NC} $name"
        return 1
    fi
}

total=0
passed=0

# PostgreSQL
total=$((total + 1))
check "PostgreSQL (localhost:5432)" "pg_isready -h localhost -p 5432 -U accusys" && passed=$((passed + 1))

# Redis
total=$((total + 1))
check "Redis (localhost:6379)" "redis-cli -a accusys ping" && passed=$((passed + 1))

# MongoDB - Port
total=$((total + 1))
check "MongoDB Port (27017)" "lsof -i :27017 > /dev/null 2>&1" && passed=$((passed + 1))

# MongoDB - Process
total=$((total + 1))
check "MongoDB Process" "pgrep -f mongod" && passed=$((passed + 1))

# MongoDB - Connection
total=$((total + 1))
check "MongoDB Connection" "mongosh --eval 'db.adminCommand(\"ping\")' > /dev/null 2>&1" && passed=$((passed + 1))

# Ollama
total=$((total + 1))
check "Ollama (localhost:11434)" "curl -s http://localhost:11434/api/tags > /dev/null" && passed=$((passed + 1))

# Momentry API
total=$((total + 1))
check "Momentry API (localhost:3000)" "curl -s http://localhost:3000/health > /dev/null" && passed=$((passed + 1))

# ffprobe
total=$((total + 1))
check "ffprobe" "which ffprobe" && passed=$((passed + 1))

# Check video_player binary
total=$((total + 1))
check "video_player binary" "test -f /Users/accusys/video_player/target/release/video_player" && passed=$((passed + 1))

# Check momentry binary
total=$((total + 1))
check "momentry binary" "test -f /Users/accusys/momentry_core_0.1/target/release/momentry" && passed=$((passed + 1))

echo ""
echo "========================================"
echo "Result: $passed/$total checks passed"
echo "========================================"

# Show status if failures
if [ $passed -lt $total ]; then
    echo ""
    echo "Failed services:"
    [ $(pg_isready -h localhost -p 5432 -U accusys > /dev/null 2>&1; echo $?) -ne 0 ] && echo "  - PostgreSQL: brew services start postgresql@18"
    [ $(redis-cli -a accusys ping > /dev/null 2>&1; echo $?) -ne 0 ] && echo "  - Redis: launchctl load ~/Library/LaunchAgents/com.momentry.redis.plist"
    [ $(curl -s http://localhost:11434/api/tags > /dev/null 2>&1; echo $?) -ne 0 ] && echo "  - Ollama: launchctl load ~/Library/LaunchAgents/com.momentry.ollama.plist"
fi

exit $([ $passed -eq $total ] && echo 0 || echo 1)
