#!/bin/bash

# Application name for dialogs
APP_NAME="FaceID GTK"

# --- EXPLICITLY DEFINE THE SYSTEM PYTHON ---
# This avoids issues with conda, pyenv, or custom PATHs.
# It ensures we use the Python that pacman installed python-gobject for.
SYSTEM_PYTHON="/usr/bin/python3"

# Define paths
VENV_DIR="$HOME/.local/share/faceid-gtk/venv"
APP_PY_PATH="/usr/share/faceid-gtk/app.py"
REQUIREMENTS_PATH="/usr/share/faceid-gtk/requirements.txt"
VENV_PYTHON="$VENV_DIR/bin/python"

# --- First-Time Setup Logic ---
# Check if the virtual environment directory does not exist
if [ ! -d "$VENV_DIR" ]; then
    
    zenity --info --width=350 --title="$APP_NAME" \
           --text="<b>First-time setup for $APP_NAME</b>\n\nA dedicated environment will now be created. This will only happen once."

    (
        echo "# Creating virtual environment..."
        # --- THE CORE FIX ---
        # Create the venv using the EXPLICIT system python path.
        # This guarantees it inherits the correct system site packages, including 'gi'.
        "$SYSTEM_PYTHON" -m venv "$VENV_DIR" --system-site-packages > /dev/null 2>&1
        echo "50"
        
        echo "# Installing required Python packages..."
        "$VENV_PYTHON" -m pip install -r "$REQUIREMENTS_PATH" > /dev/null 2>&1
        echo "100" ; echo "# Setup complete!"
        sleep 1

    ) | zenity --progress --title="Installing..." --auto-close --no-cancel

    if [ $? -ne 0 ]; then
        zenity --error --text="Setup failed. Please check your internet connection and try again."
        exit 1
    fi
fi

# --- Launch the Application ---
# Execute the main Python script using the Python interpreter from our venv
exec "$VENV_PYTHON" "$APP_PY_PATH" "$@"
