#!/usr/bin/env bash
# android_input_tap — Send tap gesture at screen coordinates via adb shell input tap.
set -euo pipefail

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

# ---------------------------------------------------------------------------
# android_input_tap [--serial <S>] <x> <y>
#
# --serial <S>  Optional target device serial (also auto-detected).
# x             X coordinate in pixels (non-negative integer).
# y             Y coordinate in pixels (non-negative integer).
#
# Exits:
#   0  tap sent successfully
#   1  missing or invalid coordinates
#   3  no device/emulator available
# ---------------------------------------------------------------------------
android_input_tap() {
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local x="${1:-}"
    local y="${2:-}"

    if [[ -z "$x" || -z "$y" ]]; then
        echo "android_input_tap: se requieren X e Y como argumentos posicionales." >&2
        return 1
    fi

    if [[ ! "$x" =~ ^[0-9]+$ ]]; then
        echo "android_input_tap: X debe ser un entero no negativo, recibido '$x'." >&2
        return 1
    fi

    if [[ ! "$y" =~ ^[0-9]+$ ]]; then
        echo "android_input_tap: Y debe ser un entero no negativo, recibido '$y'." >&2
        return 1
    fi

    adb_s "$serial" shell input tap "$x" "$y"
    echo "tap @ $x,$y on $serial"
}

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