#!/bin/sh

set -e

if [ -z "${APPIMAGE}" ]; then
    self=$(readlink -f -- "$0")
    export APPDIR="${self%/*}"
fi

# uv creates opt/python as a symlink or directory — resolve to the real cpython dir
PYTHON_DIR=$(find "${APPDIR}/opt" -maxdepth 1 -type d -name "cpython-*" | head -1)
PYTHON_DIR="${PYTHON_DIR:-${APPDIR}/opt/python}"
PYTHON="${PYTHON_DIR}/bin/python3"

if [ ! -x "$PYTHON" ]; then
    echo "AppRun: bundled python not found or not executable: $PYTHON" >&2
    exit 1
fi

export SCIQLOP_BUNDLED="1"
SSL_CERT_FILE=$("$PYTHON" -c "import certifi; print(certifi.where())" 2>/dev/null || true)
if [ -n "$SSL_CERT_FILE" ]; then
    export SSL_CERT_FILE
fi
export PATH="${APPDIR}/opt/uv:${PYTHON_DIR}/bin:${APPDIR}/usr/local/bin:${PATH}"

############################################
# Handle AppImage built-in commands first
############################################

case "$1" in
    --appimage-extract|--appimage-mount|--appimage-version)
        if [ -n "$APPIMAGE" ]; then
            exec "$APPIMAGE" "$@"
        fi
        echo "AppRun: $1 requires running the AppImage itself, not an already-extracted AppDir" >&2
        exit 1
        ;;
esac

############################################
# Subcommands
############################################

case "$1" in
    python) shift; exec "$PYTHON" "$@" ;;
    uv)     shift; exec "${APPDIR}/opt/uv/uv" "$@" ;;
    shell)  exec /bin/sh ;;
esac

############################################
# Handle re-entry as Python interpreter
# (venv symlinks python → AppImage binary)
############################################

case "$1" in
    -c|-m|-V|--version|-W|-X|-h|--help|-I|-s|-u|-v|-E|-B|-O)
        exec "$PYTHON" "$@"
        ;;
esac

############################################
# Default: launch SciQLop
############################################

#export SCIQLOP_DEBUG="1"
# The native launcher shows a splash while the bundled python above (already
# on PATH) prepares the workspace and starts the app — see
# launcher/src/launcher.cpp. Falls back to the old direct exec if the
# binary isn't bundled (e.g. an AppImage built before it was wired in).
LAUNCHER="${APPDIR}/opt/launcher/sciqlop-launcher"
if [ -x "$LAUNCHER" ]; then
    exec "$LAUNCHER" "$@"
fi
exec "$PYTHON" -I -m SciQLop.app "$@"
