#!/usr/bin/env bash
# android_emulator_list — Lista los AVDs disponibles invocando emulator.exe Windows desde WSL2.
set -euo pipefail

# Resolve emulator binary
EMULATOR="${EMULATOR:-${ANDROID_SDK_WIN:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk}/emulator/emulator.exe}"

if [[ ! -x "$EMULATOR" ]]; then
    echo "error: emulator binary not found or not executable: $EMULATOR" >&2
    exit 1
fi

# Parse flags
JSON=false
for arg in "$@"; do
    case "$arg" in
        --json) JSON=true ;;
        *) echo "error: unknown argument: $arg" >&2; exit 1 ;;
    esac
done

# Collect AVDs, stripping any warnings emulator.exe prints to stderr
mapfile -t AVDS < <("$EMULATOR" -list-avds 2>/dev/null || true)

if $JSON; then
    # Build JSON array
    printf '['
    first=true
    for avd in "${AVDS[@]}"; do
        [[ -z "$avd" ]] && continue
        if $first; then
            printf '"%s"' "$avd"
            first=false
        else
            printf ',"%s"' "$avd"
        fi
    done
    printf ']\n'
else
    for avd in "${AVDS[@]}"; do
        [[ -z "$avd" ]] && continue
        printf '%s\n' "$avd"
    done
fi
