#!/bin/bash

echo "=== Flask Application Launcher ==="

# Check for force refresh flag
FORCE_REFRESH=0
if [[ "$1" == "--refresh" || "$1" == "-r" ]]; then
    FORCE_REFRESH=1
fi

# ---- Python / Flask setup ----

# Check if venv exists
if [ ! -d "venv" ]; then
    echo "Creating new virtual environment..."
    python3 -m venv venv
    FORCE_REFRESH=1
else
    if [ $FORCE_REFRESH -eq 1 ]; then
        echo "Refreshing dependencies in existing virtual environment..."
    else
        echo "Using existing virtual environment..."
    fi
fi

# Activate the virtual environment
source venv/bin/activate || {
    echo "ERROR: Failed to activate virtual environment."
    exit 1
}

# Always install/update dependencies from requirements.txt
echo "Installing/updating dependencies from requirements.txt..."
pip install -r requirements.txt || {
    echo "ERROR: Failed to install Python requirements."
    exit 1
}
echo "Python dependencies successfully installed/updated!"

# ---- Node / Tailwind CSS setup ----

# Check Node.js is available
if ! command -v node &> /dev/null; then
    echo "ERROR: Node.js is not installed. Please install it from https://nodejs.org/"
    exit 1
fi

# Initialize package.json if not present
if [ ! -f "package.json" ]; then
    echo "Initializing npm project..."
    npm init -y || exit 1
fi

# Install npm dependencies if node_modules is missing or refresh requested
if [ ! -d "node_modules" ]; then
    echo "Installing npm dependencies..."
    npm install tailwindcss @tailwindcss/cli --save-dev || {
        echo "ERROR: Failed to install npm dependencies."
        exit 1
    }
else
    if [ $FORCE_REFRESH -eq 1 ]; then
        echo "Refreshing npm dependencies..."
        npm install tailwindcss @tailwindcss/cli --save-dev || {
            echo "ERROR: Failed to refresh npm dependencies."
            exit 1
        }
    else
        echo "Using existing node_modules..."
    fi
fi

# Start Tailwind CSS watcher in background
echo "Starting Tailwind CSS watcher in background..."
npx @tailwindcss/cli -i ./app/static/src/input.css -o ./app/static/dist/output.css --watch &
TAILWIND_PID=$!
echo "Tailwind watcher running (PID: $TAILWIND_PID)"

# Ensure Tailwind watcher is killed when Flask exits
trap "echo 'Stopping Tailwind watcher...'; kill $TAILWIND_PID 2>/dev/null" EXIT

# ---- Start Flask ----
echo "Starting Flask application..."
python run.py

echo ""
echo "Application stopped."
