#!/usr/bin/env bash
# android_logcat — Lee logcat del device/emulador, opcionalmente filtrado por package y nivel.
# Multi-emulator via --serial <S>.
set -euo pipefail

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

# shellcheck source=/dev/null
source "$SCRIPT_DIR/adb_wsl.sh"

android_logcat() {
    local serial
    adb_pick_serial "$@" || { echo "android_logcat: no device/emulator." >&2; return 3; }
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local package=""
    local level="I"
    local lines=""
    local do_clear=0

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --package) package="$2"; shift 2 ;;
            --level)   level="$2";   shift 2 ;;
            --lines)   lines="$2";   shift 2 ;;
            --clear)   do_clear=1;   shift   ;;
            *) echo "android_logcat: unknown argument: $1" >&2; return 1 ;;
        esac
    done

    if [[ $do_clear -eq 1 ]]; then
        adb_s "$serial" logcat -c
    fi

    local pid_filter=""
    if [[ -n "$package" ]]; then
        local pid
        pid=$(adb_s "$serial" shell pidof -s "$package" 2>/dev/null || true)
        pid="${pid//$'\r'/}"
        if [[ -z "$pid" ]]; then
            echo "android_logcat: package '$package' is not running on $serial" >&2
            return 2
        fi
        pid_filter="--pid=$pid"
    fi

    local -a cmd=(logcat -v time)
    [[ -n "$lines" ]] && cmd+=(-d -t "$lines")
    [[ -n "$pid_filter" ]] && cmd+=("$pid_filter")
    cmd+=("*:${level}")

    trap 'exit 130' INT TERM

    adb_s "$serial" "${cmd[@]}"
}

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