#!/usr/bin/env bash
# deploy_capacitor_to_emulator — Pipeline end-to-end: build Capacitor APK + arranca AVD + instala + lanza app.
#
# USO:
#   deploy_capacitor_to_emulator.sh <app_dir> [avd_name] [package_name]
#
# ARGUMENTOS:
#   app_dir        Path al directorio de la app Capacitor (debe contener package.json). Obligatorio.
#   avd_name       Nombre del AVD a usar (default: Medium_Phone_API_35). Opcional.
#   package_name   Package id de la app Android (ej: com.fnregistry.voiceguide).
#                  Si se da, lanza la app tras instalar. Opcional.
#
# EJEMPLO:
#   bash deploy_capacitor_to_emulator.sh apps/voice_guide Medium_Phone_API_35 com.fnregistry.voiceguide
#
# REQUISITOS:
#   - Node.js + pnpm en PATH
#   - Java 17+ en PATH
#   - ANDROID_HOME seteado o ~/android-sdk/env.sh disponible
#   - Emulator Windows accesible desde WSL2 (adb_wsl)

set -euo pipefail

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

# ---------------------------------------------------------------------------
# Parseo de argumentos
# ---------------------------------------------------------------------------

APP_DIR="${1:-}"
AVD_NAME="${2:-Medium_Phone_API_35}"
PACKAGE_NAME="${3:-}"

if [[ -z "$APP_DIR" ]]; then
    echo "[deploy_capacitor_to_emulator] ERROR: app_dir es obligatorio." >&2
    echo "USO: $0 <app_dir> [avd_name] [package_name]" >&2
    exit 1
fi

# Resolver path absoluto de APP_DIR (puede venir relativo al cwd)
if [[ "$APP_DIR" != /* ]]; then
    APP_DIR="$(pwd)/$APP_DIR"
fi

if [[ ! -d "$APP_DIR" ]]; then
    echo "[deploy_capacitor_to_emulator] ERROR: directorio no existe: $APP_DIR" >&2
    exit 1
fi

if [[ ! -f "$APP_DIR/package.json" ]]; then
    echo "[deploy_capacitor_to_emulator] ERROR: no se encontró package.json en $APP_DIR" >&2
    exit 1
fi

echo ""
echo "======================================================================"
echo " deploy_capacitor_to_emulator"
echo "======================================================================"
echo " app_dir      : $APP_DIR"
echo " avd_name     : $AVD_NAME"
echo " package_name : ${PACKAGE_NAME:-(no lanzar)}"
echo "======================================================================"
echo ""

# ---------------------------------------------------------------------------
# Source adb_wsl para tener helpers ADB y resolver $ADB
# ---------------------------------------------------------------------------

# shellcheck source=../infra/adb_wsl.sh
source "$REGISTRY_ROOT/bash/functions/infra/adb_wsl.sh"

# ---------------------------------------------------------------------------
# Fase 1: Verificar que el AVD existe
# ---------------------------------------------------------------------------

echo "[deploy_capacitor_to_emulator] [1/4] Verificando AVD '$AVD_NAME'..."

if ! bash "$REGISTRY_ROOT/bash/functions/infra/android_emulator_list.sh" | grep -qx "$AVD_NAME"; then
    echo "[deploy_capacitor_to_emulator] ERROR: AVD '$AVD_NAME' no encontrado." >&2
    echo "  AVDs disponibles:" >&2
    bash "$REGISTRY_ROOT/bash/functions/infra/android_emulator_list.sh" | sed 's/^/    /' >&2
    exit 1
fi

echo "[deploy_capacitor_to_emulator] AVD '$AVD_NAME' existe."

# ---------------------------------------------------------------------------
# Fase 2: Build APK
# ---------------------------------------------------------------------------

echo ""
echo "[deploy_capacitor_to_emulator] [2/4] Construyendo APK desde $APP_DIR ..."

bash "$REGISTRY_ROOT/bash/functions/pipelines/capacitor_build_apk.sh" "$APP_DIR"

# Localizar APK generado: capacitor_build_apk copia el APK a $APP_DIR/<app_name>.apk
APK_PATH=""
while IFS= read -r -d '' candidate; do
    APK_PATH="$candidate"
    break
done < <(find "$APP_DIR" -maxdepth 1 -name "*.apk" -print0 2>/dev/null)

if [[ -z "$APK_PATH" ]]; then
    echo "[deploy_capacitor_to_emulator] ERROR: No se encontró ningún .apk en $APP_DIR tras el build." >&2
    exit 1
fi

echo "[deploy_capacitor_to_emulator] APK localizado: $APK_PATH"

# ---------------------------------------------------------------------------
# Fase 3: Arrancar emulador (idempotente)
# ---------------------------------------------------------------------------

echo ""
echo "[deploy_capacitor_to_emulator] [3/4] Arrancando emulador '$AVD_NAME' (idempotente)..."

bash "$REGISTRY_ROOT/bash/functions/infra/android_emulator_start.sh" "$AVD_NAME"

echo "[deploy_capacitor_to_emulator] Emulador listo."

# ---------------------------------------------------------------------------
# Fase 4: Instalar APK (y lanzar si se dio package_name)
# ---------------------------------------------------------------------------

echo ""
echo "[deploy_capacitor_to_emulator] [4/4] Instalando APK..."

# Source android_apk_install para usar su función
# shellcheck source=../infra/android_apk_install.sh
source "$REGISTRY_ROOT/bash/functions/infra/android_apk_install.sh"

android_apk_install "$APK_PATH" "$PACKAGE_NAME"

# ---------------------------------------------------------------------------
# Diagnóstico no-bloqueante: hint logcat
# ---------------------------------------------------------------------------

if [[ -n "$PACKAGE_NAME" ]]; then
    echo ""
    echo "[deploy_capacitor_to_emulator] Para seguir los logs de la app en tiempo real:"
    echo "  bash $REGISTRY_ROOT/bash/functions/infra/android_logcat.sh --package '$PACKAGE_NAME'"
    echo ""
    echo "  O los últimos 50 mensajes:"
    echo "  bash $REGISTRY_ROOT/bash/functions/infra/android_logcat.sh --package '$PACKAGE_NAME' --lines 50"
fi

# ---------------------------------------------------------------------------
# Resumen
# ---------------------------------------------------------------------------

echo ""
echo "======================================================================"
echo " DEPLOY COMPLETADO"
echo "======================================================================"
echo " APK instalado : $APK_PATH"
echo " Emulador      : $AVD_NAME"
if [[ -n "$PACKAGE_NAME" ]]; then
    echo " App lanzada   : $PACKAGE_NAME"
fi
echo "======================================================================"
echo ""
