#!/bin/bash
# Flask App Startup Script
# This script starts the Jadwa AI Flask app with proper environment

APP_DIR="/home/ashraffarid2010/jadwaai.com"
APP_PORT=5006
LOG_FILE="$APP_DIR/logs/startup.log"

# Create logs directory if it doesn't exist
mkdir -p "$APP_DIR/logs"

# Function to log messages
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
    echo "$1"
}

log_message "=== Starting Jadwa AI Flask app ==="

# Stop any existing process
pkill -f "gunicorn.*$APP_PORT" 2>/dev/null
sleep 2

# Change to app directory
cd "$APP_DIR" || exit 1

# Set environment
export FLASK_ENV=export PYTHONUNBUFFERED=1

# Activate virtual environment
source venv/bin/activate

# Start gunicorn with proper configuration
log_message "Starting Gunicorn on port $APP_PORT..."
nohup venv/bin/gunicorn -w 4 -b 127.0.0.1:$APP_PORT \
    --timeout 120 \
    --keep-alive 5 \
    --max-requests 1000 \
    --max-requests-jitter 50 \
    --worker-class sync \
    --worker-connections 1000 \
    --access-logfile "$APP_DIR/logs/gunicorn_access.log" \
    --error-logfile "$APP_DIR/logs/gunicorn_error.log" \
    --log-level info \
    run:app >> "$APP_DIR/logs/gunicorn.log" 2>&1 &

# Save PID
GUNICORN_PID=$!
echo $GUNICORN_PID > "$APP_DIR/logs/gunicorn.pid"

log_message "Gunicorn started with PID: $GUNICORN_PID"

# Wait for app to start
sleep 5

# Verify it started
if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$APP_PORT/ --max-time 10 | grep -q "200"; then
    log_message "✓ Flask app is running and responding correctly"
    exit 0
else
    log_message "✗ Flask app failed to start or not responding"
    exit 1
fi
