#!/bin/sh
set -eu

APP_ROOT=${LOCAL_OPTIMIZE_ROOT:-/usr/lib/local-optimize}
SYSTEM_PYTHON=${LOCAL_OPTIMIZE_SYSTEM_PYTHON:-/usr/bin/python3}
VERSION=1.0.1

usage() {
    cat <<'EOF'
Usage: local-optimize <command> [arguments]

Commands:
  sync           Provision the Python runtime and synchronize all models
  models         Inspect or synchronize models (status | sync)
  migrate        Apply PostgreSQL migrations
  server         Run the FastAPI server
  watchdog       Run filesystem indexing
  mcp            Run the full local-only MCP server
  lmstudio-mcp   Run the read-only LM Studio MCP wrapper
  index          Index the registered project
  version        Print the package version
  help           Print this help

The Python environment is read from LOCAL_OPTIMIZE_VENV, $APP_ROOT/venv,
or /var/lib/local-optimize/venv.
EOF
}

if [ "$#" -eq 0 ]; then
    usage >&2
    exit 2
fi

command=$1
shift
case "$command" in
    help|--help|-h)
        usage
        exit 0
        ;;
    version|--version)
        printf '%s\n' "$VERSION"
        exit 0
        ;;
    sync|models)
        if [ ! -x "$SYSTEM_PYTHON" ]; then
            SYSTEM_PYTHON=$(command -v python3 || true)
        fi
        if [ -z "$SYSTEM_PYTHON" ] || [ ! -x "$SYSTEM_PYTHON" ]; then
            printf '%s\n' 'System python3 interpreter not found.' >&2
            exit 1
        fi
        export PYTHONPATH="$APP_ROOT${PYTHONPATH:+:$PYTHONPATH}"
        export LOCAL_OPTIMIZE_CALLER_DIR="$PWD"
        exec "$SYSTEM_PYTHON" "$APP_ROOT/runtime_sync.py" --root "$APP_ROOT" "$command" "$@"
        ;;
esac

if [ -n "${LOCAL_OPTIMIZE_VENV:-}" ]; then
    VENV=$LOCAL_OPTIMIZE_VENV
elif [ -x "$APP_ROOT/venv/bin/python" ]; then
    VENV=$APP_ROOT/venv
elif [ -x "$APP_ROOT/.venv/bin/python" ]; then
    VENV=$APP_ROOT/.venv
else
    VENV=${LOCAL_OPTIMIZE_SYSTEM_DIR:-/var/lib/local-optimize}/venv
fi
PYTHON=$VENV/bin/python
if [ ! -x "$PYTHON" ]; then
    printf '%s\n' "Provisioned Python environment not found: $PYTHON" >&2
    printf '%s\n' 'Run "sudo local-optimize sync" or see /usr/share/doc/local-optimize/README.Debian.' >&2
    exit 1
fi

case "$command" in
    migrate) script=create_schema.py ;;
    server) script=gpu_rag_server.py ;;
    watchdog) script=watchdog_indexer.py ;;
    mcp) script=mcp_server.py ;;
    lmstudio-mcp) script=lmstudio_rag_mcp.py ;;
    index) script=index_project_codebase.py ;;
    *)
        printf 'Unknown command: %s\n' "$command" >&2
        usage >&2
        exit 2
        ;;
esac

export PYTHONPATH="$APP_ROOT${PYTHONPATH:+:$PYTHONPATH}"
export LOCAL_OPTIMIZE_CALLER_DIR="$PWD"
export PYTHONDONTWRITEBYTECODE=1
export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}"
export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}"
cd "$APP_ROOT"
exec "$PYTHON" "$APP_ROOT/$script" "$@"
