#!/usr/bin/env bash
# android_app_info — Inspect installed app via dumpsys package.
# Usage: android_app_info [--serial <S>] <package> [--json]

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

android_app_info() {
    # Resolve serial (consumes --serial from args, leaves rest in ADB_PICK_REST)
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    # Parse remaining args: package + --json flag
    local pkg=""
    local want_json=0
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --json) want_json=1; shift ;;
            -*) echo "android_app_info: unknown flag '$1'" >&2; return 1 ;;
            *)
                if [[ -z "$pkg" ]]; then
                    pkg="$1"
                else
                    echo "android_app_info: unexpected argument '$1'" >&2
                    return 1
                fi
                shift ;;
        esac
    done

    if [[ -z "$pkg" ]]; then
        echo "android_app_info: package argument required" >&2
        return 1
    fi

    local dump
    dump=$(adb_s "$serial" shell dumpsys package "$pkg" 2>&1)
    local rc=$?
    if [[ $rc -ne 0 ]]; then
        echo "android_app_info: adb dumpsys failed (exit $rc)" >&2
        return 1
    fi

    # If dumpsys returns nothing meaningful for the package, treat as not installed
    if ! echo "$dump" | grep -q "Package \["; then
        if [[ $want_json -eq 1 ]]; then
            echo "null"
        else
            echo "android_app_info: package '$pkg' not found on device" >&2
            return 2
        fi
        return 0
    fi

    if [[ $want_json -eq 0 ]]; then
        echo "$dump"
        return 0
    fi

    # --- JSON extraction ---
    local versionName versionCode targetSdk launcherActivity

    versionName=$(echo "$dump" | grep -m1 'versionName=' \
        | sed 's/.*versionName=\([^ ]*\).*/\1/')
    versionCode=$(echo "$dump" | grep -m1 'versionCode=' \
        | sed 's/.*versionCode=\([0-9]*\).*/\1/')
    targetSdk=$(echo "$dump" | grep -m1 'targetSdk=' \
        | sed 's/.*targetSdk=\([0-9]*\).*/\1/')

    # Primary/launcher activity: look for MAIN/LAUNCHER category block
    launcherActivity=$(echo "$dump" | awk '
        /android.intent.action.MAIN/ { found=1 }
        found && /[a-zA-Z0-9_.]+\/[a-zA-Z0-9_.]+/ {
            match($0, /[a-zA-Z0-9_.]+\/[a-zA-Z0-9_.]+/)
            print substr($0, RSTART, RLENGTH)
            exit
        }
    ')

    # Emit JSON, quoting strings safely
    printf '{"package":"%s","versionName":"%s","versionCode":%s,"targetSdk":%s,"launcherActivity":"%s"}\n' \
        "$pkg" \
        "${versionName:-}" \
        "${versionCode:-0}" \
        "${targetSdk:-0}" \
        "${launcherActivity:-}"
}

# Run if invoked directly
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    android_app_info "$@"
fi
