#!/usr/bin/env bash
# android_screenshot — Capture screen as PNG via adb exec-out screencap -p.

android_screenshot() {
    local SCRIPT_DIR
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    # shellcheck source=bash/functions/infra/adb_wsl.sh
    source "$SCRIPT_DIR/adb_wsl.sh" || return 1

    # Resolve serial, consume --serial from args
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local output="${1:-}"
    if [[ -z "$output" ]]; then
        echo "android_screenshot: output_path is required." >&2
        return 1
    fi

    # Ensure parent directory exists
    mkdir -p "$(dirname "$output")"

    # Capture screen
    adb_s "$serial" exec-out screencap -p > "$output"

    # Verify file created and non-empty
    if [[ ! -f "$output" ]] || [[ ! -s "$output" ]]; then
        rm -f "$output"
        echo "android_screenshot: screencap produced empty or missing file." >&2
        return 1
    fi

    local size
    size=$(stat -c%s "$output" 2>/dev/null || stat -f%z "$output" 2>/dev/null)
    echo "screenshot: $output ($size bytes) from $serial"
}

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