#!/usr/bin/env bash
# android_input_text — Type text in focused field via adb shell input text.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"

# ---------------------------------------------------------------------------
# android_input_text [--serial <S>] <text>
#
# $1  text   Text to type in the currently focused field (obligatorio).
#            Spaces are replaced with %s as required by adb input text.
#            Special chars " $ ` are escaped with backslash.
#
# Envvar ADB_SERIAL overrides --serial.
# ---------------------------------------------------------------------------
android_input_text() {
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local text="${1:-}"
    if [[ -z "$text" ]]; then
        echo "android_input_text: se requiere el texto como primer argumento." >&2
        return 1
    fi

    # adb input text does not support raw spaces; replace with %s.
    # Also escape " $ ` which the shell would interpret inside the adb command.
    local escaped
    escaped="${text// /%s}"
    escaped="${escaped//\"/\\\"}"
    escaped="${escaped//\$/\\\$}"
    escaped="${escaped//\`/\\\`}"

    adb_s "$serial" shell input text "$escaped"
    echo "typed: $text"
}

# Ejecutar si se llama directamente (no sourceado)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_input_text "$@"
fi
