#!/usr/bin/env bash
# Install the portable NexusOS wheel in Termux.
#
# NEXUS_PACKAGE may be a PyPI requirement, wheel URL, or local wheel path.
# NEXUS_ANDROID_WHEEL_INDEX may point at a trusted PEP 503 index containing
# Android pydantic-core wheels for the device's Python/CPU combination.
set -euo pipefail

if [[ "${PREFIX:-}" != *com.termux* ]]; then
    echo "This installer must be run inside Termux." >&2
    exit 2
fi

PACKAGE_SPEC="${1:-${NEXUS_PACKAGE:-nexusos-ai}}"

echo "==> Installing Termux prerequisites"
pkg update -y
pkg install -y python python-pip curl clang make

PYTHON_TAG="$(python -c 'import sys; print(f"cp{sys.version_info.major}{sys.version_info.minor}")')"
ARCH="$(uname -m)"
echo "==> Python ${PYTHON_TAG}; architecture ${ARCH}"

PIP_INDEX_ARGS=()
if [[ -n "${NEXUS_ANDROID_WHEEL_INDEX:-}" ]]; then
    PIP_INDEX_ARGS+=(--extra-index-url "${NEXUS_ANDROID_WHEEL_INDEX}")
fi

# Pydantic 2 is required on Python 3.14+, and its Rust extension is not built
# reliably on-device. Require a binary before asking pip to resolve NexusOS so
# failures are immediate and actionable. Older Termux environments also benefit
# from using a wheel instead of compiling the extension on a phone.
echo "==> Checking for an Android pydantic-core wheel"
if ! python -m pip install \
    --only-binary=pydantic-core \
    "${PIP_INDEX_ARGS[@]}" \
    "pydantic>=2.7,<3"; then
    cat >&2 <<EOF

No compatible pydantic-core wheel was found for ${PYTHON_TAG}/${ARCH}.
PyPI does not currently publish Android wheels for this native dependency.
Set NEXUS_ANDROID_WHEEL_INDEX to a trusted NexusOS Android wheel index and
run this installer again. Do not force a source build on a memory-limited phone.
EOF
    exit 1
fi

echo "==> Installing ${PACKAGE_SPEC}"
# Same extra index as the pydantic-core probe: a NexusOS wheel hosted there
# would otherwise be invisible to the resolver.
python -m pip install "${PIP_INDEX_ARGS[@]}" "${PACKAGE_SPEC}"

echo "==> Initializing NexusOS"
nexus init

if [[ -n "${NEXUS_PROVIDER_URL:-}" ]]; then
    nexus provider use remote --url "${NEXUS_PROVIDER_URL}"
fi

# Report health without aborting: `set -e` would otherwise skip the guidance
# below whenever doctor finds a failing required check - exactly when the
# reader most needs to see what to do next. The status is re-raised at exit.
DOCTOR_STATUS=0
nexus doctor || DOCTOR_STATUS=$?

cat <<'EOF'

NexusOS is installed. Configure an Ollama-compatible provider, then run:
  nexus provider use remote --url http://YOUR-OLLAMA-HOST:11434
  nexus serve

Open http://127.0.0.1:8000 in the Android browser.
EOF

exit "${DOCTOR_STATUS}"
