#!/usr/bin/env bash
# android_apk_install — Instala APK en device/emulador via adb y opcionalmente lanza la app.
# Multi-emulator via --serial <S>.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Source helpers (adb_run, adb_pick_serial, adb_s, adb_wsl_to_win)
# shellcheck source=/dev/null
source "$SCRIPT_DIR/adb_wsl.sh"

# ---------------------------------------------------------------------------
# android_apk_install [--serial <S>] <apk_path> [package_name] [activity_name]
# ---------------------------------------------------------------------------
android_apk_install() {
    local serial
    adb_pick_serial "$@" || { echo "android_apk_install: no device/emulator." >&2; return 3; }
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local apk="${1:-}"
    local package="${2:-}"
    local activity="${3:-}"

    if [[ -z "$apk" ]]; then
        echo "android_apk_install: se requiere apk_path como primer argumento." >&2
        return 1
    fi
    if [[ ! -f "$apk" ]]; then
        echo "android_apk_install: APK no encontrado en '$apk'." >&2
        return 1
    fi

    local win_path
    win_path=$(adb_wsl_to_win "$apk")

    echo "android_apk_install: instalando '$win_path' on $serial ..."
    adb_s "$serial" install -r "$win_path"
    echo "android_apk_install: instalacion completada."

    if [[ -n "$package" ]]; then
        if [[ -n "$activity" ]]; then
            echo "android_apk_install: lanzando $package/$activity ..."
            adb_s "$serial" shell am start -n "$package/$activity"
        else
            echo "android_apk_install: lanzando $package via monkey LAUNCHER ..."
            adb_s "$serial" shell monkey -p "$package" -c android.intent.category.LAUNCHER 1
        fi
        echo "android_apk_install: app lanzada."
    fi
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_apk_install "$@"
fi
