#!/bin/bash
# Launch OpenWhisper (macOS / Linux) using the project's virtualenv.
# Lives in the repo so `git pull` updates launcher logic without reinstalling.
set -euo pipefail

resolve_script_dir() {
    local source="${BASH_SOURCE[0]}"
    local dir

    while [ -L "$source" ]; do
        dir="$(cd -P "$(dirname "$source")" && pwd)"
        source="$(readlink "$source")"
        if [[ "$source" != /* ]]; then
            source="$dir/$source"
        fi
    done

    cd -P "$(dirname "$source")" && pwd
}

SCRIPT_DIR="$(resolve_script_dir)"
REPO="$(cd "$SCRIPT_DIR/.." && pwd)"
ENTRY="$REPO/main.py"
VIRTUAL_ENV="$REPO/.venv"
if [ ! -x "$VIRTUAL_ENV/bin/python" ] && [ -x "$REPO/venv/bin/python" ]; then
    VIRTUAL_ENV="$REPO/venv"
fi
PYTHON="$VIRTUAL_ENV/bin/python"

if [ ! -x "$PYTHON" ]; then
    echo "[error] Virtual environment not found." >&2
    echo "        Expected: $PYTHON" >&2
    echo "        From the repo root, run: uv sync --locked" >&2
    exit 1
fi

cd "$REPO"
export VIRTUAL_ENV
export PATH="$VIRTUAL_ENV/bin:$PATH"
unset PYTHONHOME

if [ "$(uname -s)" = "Linux" ]; then
    # main.py preloads these with RTLD_GLOBAL, which is enough on its own.
    # Exporting LD_LIBRARY_PATH as well costs nothing and covers the loader
    # paths a preload cannot reach: libraries dlopen'd by a child process, and
    # any NVIDIA wheel layout that does not set RPATH on its own libraries.
    # ld.so only reads this at process start, hence doing it here.
    NVIDIA_LIB_DIRS="$("$PYTHON" - <<'PY'
import os
import site
from pathlib import Path

roots = list(site.getsitepackages())
user_site = site.getusersitepackages()
if user_site:
    roots.append(user_site)

found = []
for root in dict.fromkeys(roots):
    nvidia_root = Path(root) / "nvidia"
    if not nvidia_root.is_dir():
        continue
    for lib_dir in sorted(nvidia_root.glob("*/lib")):
        if lib_dir.is_dir():
            found.append(str(lib_dir))
print(os.pathsep.join(dict.fromkeys(found)))
PY
    )"
    if [ -n "$NVIDIA_LIB_DIRS" ]; then
        export LD_LIBRARY_PATH="$NVIDIA_LIB_DIRS${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
    fi
fi

# Command-line modes answer in this terminal and exit: run them in the
# foreground, not in the background with their output in the launch log.
case "${1:-}" in
    -h|--help|--version|--diagnostics|--api|--channel|--self-test|--workflow-smoke)
        exec "$PYTHON" "$ENTRY" "$@"
        ;;
esac

if [ "$(uname -s)" = "Linux" ]; then
    if ! "$PYTHON" -c "from services.linux_deps import check_linux_dependencies; raise SystemExit(check_linux_dependencies())"; then
        echo "[error] Missing system libraries. Install them (command above), then retry." >&2
        exit 1
    fi
fi

run_openwhisper() {
    if [ "${OPENWHISPER_ATTACHED:-0}" = "1" ]; then
        exec "$@"
    fi

    nohup "$@" >> "$REPO/openwhisper.launch.log" 2>&1 &
    echo "OpenWhisper started in the background (pid $!)."
    echo "Logs: $REPO/openwhisper.log"
}

if [ "$(uname -s)" = "Darwin" ]; then
    PYTHON_APP="$("$PYTHON" - <<'PY'
import os
import sys

base_prefix = os.path.realpath(getattr(sys, "base_prefix", sys.prefix))
candidates = [
    os.path.join(base_prefix, "Resources", "Python.app", "Contents", "MacOS", "Python"),
]
for path in candidates:
    if os.path.isfile(path) and os.access(path, os.X_OK):
        print(path)
        break
PY
    )"
    if [ -n "$PYTHON_APP" ]; then
        export OPENWHISPER_MACOS_LAUNCH_APP="$PYTHON_APP"
        export __PYVENV_LAUNCHER__="$PYTHON"
        run_openwhisper "$PYTHON_APP" "$ENTRY" "$@"
        exit 0
    fi
fi

run_openwhisper "$PYTHON" "$ENTRY" "$@"
