#!/usr/bin/env bash
# android_screen_record — Record screen video via adb screenrecord, pulls to local path.

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

# ---------------------------------------------------------------------------
# android_screen_record [--serial <S>] [--duration <s>] [--bit-rate <bps>] [--size <WxH>] <output_path>
#
# Args:
#   --serial <S>     Optional: target device serial (default: autodetect)
#   --duration <s>   Recording duration in seconds (default: 30, max: 180)
#   --bit-rate <bps> Video bit rate (default: 4000000)
#   --size <WxH>     Video dimensions e.g. 720x1280 (default: device native)
#   output_path      WSL destination path for the .mp4 file
#
# Exit codes:
#   0  success
#   1  general error
#   2  missing output_path argument
#   3  no device/emulator found
# ---------------------------------------------------------------------------
android_screen_record() {
    local dur=30
    local bit_rate=4000000
    local size=""

    # Parse flags first pass to extract serial; remaining args go to ADB_PICK_REST.
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    # Parse remaining flags
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --duration)  dur="$2";      shift 2 ;;
            --duration=*) dur="${1#--duration=}"; shift ;;
            --bit-rate)  bit_rate="$2"; shift 2 ;;
            --bit-rate=*) bit_rate="${1#--bit-rate=}"; shift ;;
            --size)      size="$2";     shift 2 ;;
            --size=*)    size="${1#--size=}"; shift ;;
            -*) echo "android_screen_record: unknown flag '$1'" >&2; return 1 ;;
            *)  break ;;
        esac
    done

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

    # Build adb screenrecord args
    local rec_args=("shell" "screenrecord" "--time-limit" "$dur")
    rec_args+=("--bit-rate" "$bit_rate")
    [[ -n "$size" ]] && rec_args+=("--size" "$size")
    rec_args+=("/sdcard/__rec.mp4")

    echo "android_screen_record: recording ${dur}s from $serial..." >&2
    adb_s "$serial" "${rec_args[@]}" || {
        echo "android_screen_record: screenrecord failed." >&2
        return 1
    }

    adb_s "$serial" pull /sdcard/__rec.mp4 "$output" || {
        echo "android_screen_record: pull failed." >&2
        return 1
    }

    adb_s "$serial" shell rm /sdcard/__rec.mp4

    echo "recorded: $output (${dur}s from $serial)"
}

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