#!/bin/bash

# Schedule Parser Bot - Background Process Manager
# Run every second continuously in the background

SCRIPT_PATH="/var/www/html/tgbot/scheduleparser/watch-continuous.php"
PID_FILE="/var/www/html/tgbot/scheduleparser/.watcher.pid"
LOG_FILE="/var/www/html/tgbot/scheduleparser/logs/continuous_watcher.log"

# Create log directory if it doesn't exist
mkdir -p "$(dirname "$LOG_FILE")"

function start_watcher() {
    if [ -f "$PID_FILE" ]; then
        PID=$(<"$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo "❌ Watcher already running (PID: $PID)"
            return 1
        fi
    fi
    
    echo "🚀 Starting continuous watcher..."
    nohup php "$SCRIPT_PATH" >> "$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    
    sleep 1
    
    if [ -f "$PID_FILE" ]; then
        PID=$(<"$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo "✅ Watcher started successfully (PID: $PID)"
            echo "📊 Checking every 1 second"
            echo "📝 Log file: $LOG_FILE"
            return 0
        fi
    fi
    
    echo "❌ Failed to start watcher"
    return 1
}

function stop_watcher() {
    if [ ! -f "$PID_FILE" ]; then
        echo "❌ Watcher is not running"
        return 1
    fi
    
    PID=$(<"$PID_FILE")
    
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "🛑 Stopping watcher (PID: $PID)..."
        kill "$PID"
        sleep 1
        
        if ! ps -p "$PID" > /dev/null 2>&1; then
            rm -f "$PID_FILE"
            echo "✅ Watcher stopped successfully"
            return 0
        else
            echo "⚠️  Process still running, forcing kill..."
            kill -9 "$PID"
            rm -f "$PID_FILE"
            return 0
        fi
    else
        echo "⚠️  Watcher process not found (PID: $PID), removing PID file"
        rm -f "$PID_FILE"
        return 1
    fi
}

function status_watcher() {
    if [ ! -f "$PID_FILE" ]; then
        echo "❌ Watcher is not running"
        return 1
    fi
    
    PID=$(<"$PID_FILE")
    
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "✅ Watcher is running (PID: $PID)"
        echo ""
        echo "📊 Process info:"
        ps -p "$PID" -o pid,vsz,rss,cmd
        echo ""
        echo "📝 Log file: $LOG_FILE"
        echo ""
        echo "Recent logs (last 10 lines):"
        tail -10 "$LOG_FILE" 2>/dev/null || echo "No logs yet"
        return 0
    else
        echo "❌ Watcher process not found (PID: $PID)"
        rm -f "$PID_FILE"
        return 1
    fi
}

function show_logs() {
    if [ ! -f "$LOG_FILE" ]; then
        echo "❌ Log file not found: $LOG_FILE"
        return 1
    fi
    
    echo "📺 Continuous Watcher Logs"
    echo "=========================="
    echo ""
    tail -f "$LOG_FILE"
}

# Main menu
case "${1:-help}" in
    start)
        start_watcher
        ;;
    stop)
        stop_watcher
        ;;
    restart)
        stop_watcher
        sleep 1
        start_watcher
        ;;
    status)
        status_watcher
        ;;
    logs)
        show_logs
        ;;
    *)
        echo "Schedule Parser Bot - Background Watcher Manager"
        echo "================================================="
        echo ""
        echo "Usage: $0 {start|stop|restart|status|logs}"
        echo ""
        echo "Commands:"
        echo "  start   - Start continuous watcher (checks every 1 second)"
        echo "  stop    - Stop the watcher"
        echo "  restart - Restart the watcher"
        echo "  status  - Show watcher status and last logs"
        echo "  logs    - Follow logs in real-time"
        echo ""
        echo "Examples:"
        echo "  $0 start      # Start watching"
        echo "  $0 status     # Check if running"
        echo "  $0 logs       # View live logs"
        echo "  $0 stop       # Stop watching"
        ;;
esac
