#!/usr/bin/env bash
# gradle_run — Wrapper canonico para invocar gradlew Android en WSL2.
# Valida JDK 17 + ANDROID_HOME antes de delegar al wrapper del proyecto.
#
# Uso como libreria: source bash/functions/infra/gradle_run.sh
# Uso directo:       bash bash/functions/infra/gradle_run.sh <project_dir> <task...>

# ---------------------------------------------------------------------------
# gradle_run <project_dir> <task...>
#
# Resuelve JAVA_HOME y ANDROID_HOME si no estan fijados, luego invoca
# ./gradlew con las tareas indicadas en el directorio del proyecto.
#
# Exits:
#   0  — gradlew completado con exito
#   1  — JDK 17 no encontrado
#   2  — ./gradlew no existe en project_dir
#   *  — exit code propagado de gradlew
# ---------------------------------------------------------------------------
gradle_run() {
    local project_dir="$1"
    shift || true

    # ---- Resolver JAVA_HOME ------------------------------------------------
    local java_home="${JAVA_HOME:-}"
    if [[ -z "$java_home" ]]; then
        local _jdk_candidates=(
            "/usr/lib/jvm/java-17-openjdk-amd64"
            "/usr/lib/jvm/temurin-17-jdk-amd64"
            "/opt/android-studio-jbr/jbr"
        )
        for _candidate in "${_jdk_candidates[@]}"; do
            if [[ -d "$_candidate" ]]; then
                java_home="$_candidate"
                break
            fi
        done
        unset _jdk_candidates _candidate
    fi

    if [[ -z "$java_home" ]]; then
        echo "gradle_run: JDK 17 not found, install via install_android_sdk" >&2
        return 1
    fi

    # ---- Resolver ANDROID_HOME ---------------------------------------------
    local android_home="${ANDROID_HOME:-}"
    if [[ -z "$android_home" ]]; then
        local _default_linux="$HOME/Android/Sdk"
        if [[ -d "$_default_linux" ]]; then
            android_home="$_default_linux"
        elif [[ -n "${ANDROID_SDK_WIN:-}" && -d "${ANDROID_SDK_WIN}" ]]; then
            # SDK Windows montado en WSL via /mnt/c/...
            android_home="${ANDROID_SDK_WIN}"
        fi
        unset _default_linux
    fi

    # ANDROID_HOME puede quedar vacio si no hay SDK instalado; gradle mostrara
    # el error adecuado. No bloqueamos aqui para permitir builds puros JVM.

    # ---- Verificar gradlew -------------------------------------------------
    if [[ ! -f "${project_dir}/gradlew" ]]; then
        echo "gradle_run: no gradlew in ${project_dir}" >&2
        return 2
    fi

    # ---- Invocar gradlew ----------------------------------------------------
    (
        cd "$project_dir" || return 1
        JAVA_HOME="$java_home" ANDROID_HOME="${android_home:-}" ./gradlew "$@"
    )
}

# ---------------------------------------------------------------------------
# Ejecucion directa
# ---------------------------------------------------------------------------
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    gradle_run "$@"
fi
