#!/bin/bash
# ==============================================================================
# PrivacyVPN for macOS - Native Application Launcher
# ==============================================================================

# Determine Resources directory inside the .app bundle
RESOURCES_DIR="$(cd "$(dirname "$0")/../Resources" && pwd)"
cd "$RESOURCES_DIR"

# 1. Locate Python 3 binary on macOS
PY_BIN=""
for p in "/opt/homebrew/bin/python3" "/usr/local/bin/python3" "$(which python3 2>/dev/null)" "/usr/bin/python3"; do
    if [ -n "$p" ] && [ -x "$p" ]; then
        PY_BIN="$p"
        break
    fi
done

if [ -z "$PY_BIN" ]; then
    osascript -e 'display alert "Python 3 Required" message "PrivacyVPN requires Python 3 to run on macOS.\n\nPlease install Python 3 from https://www.python.org or run:\nbrew install python" as critical' 2>/dev/null
    exit 1
fi

# 2. Setup isolated user-level environment in ~/Library/Application Support/PrivacyVPN
APP_SUPPORT="$HOME/Library/Application Support/PrivacyVPN"
VENV_DIR="$APP_SUPPORT/venv"

if [ ! -f "$VENV_DIR/bin/python" ]; then
    # First-run setup notification
    osascript -e 'display notification "Configuring PrivacyVPN environment for first launch..." with title "PrivacyVPN"' 2>/dev/null
    mkdir -p "$APP_SUPPORT"
    "$PY_BIN" -m venv "$VENV_DIR"
    if [ $? -ne 0 ]; then
        osascript -e 'display alert "Environment Setup Failed" message "Could not create Python environment in ~/Library/Application Support/PrivacyVPN." as critical' 2>/dev/null
        exit 1
    fi
    "$VENV_DIR/bin/pip" install --upgrade pip --quiet 2>/dev/null
    "$VENV_DIR/bin/pip" install -r "$RESOURCES_DIR/requirements.txt" --quiet
    if [ $? -ne 0 ]; then
        osascript -e 'display alert "Dependency Setup Failed" message "Could not install required libraries. Please check your internet connection and try again." as critical' 2>/dev/null
        exit 1
    fi
fi

# 3. Launch PrivacyVPN native window
exec "$VENV_DIR/bin/python" "$RESOURCES_DIR/vpn_app.py"
