# shellcheck shell=dash

___x_cmd_ff_rec(){
    local output_file=""
    local device=":0"
    local sample_rate=16000
    local channels=1

    while [ "$#" -gt 0 ]; do
        case "$1" in
            -h|--help)
                x help -m ff rec
                return
                ;;
            -f|--file)
                output_file="$2"
                shift 2
                ;;
            -d|--device)
                device="$2"
                shift 2
                ;;
            -r|--rate)
                sample_rate="$2"
                shift 2
                ;;
            -c|--channels)
                channels="$2"
                shift 2
                ;;
            *)
                [ -z "$output_file" ] || N=ff M="Unknown option: $1" log:ret:1
                output_file="$1"
                shift
                ;;
        esac
    done

    [ -n "$output_file" ] || {
        local timestamp
        timestamp="$(date +%Y%m%d-%H%M%S)"
        output_file="recording-${timestamp}.wav"
    }

    ___x_cmd_ff_rec___info "Starting audio recording..."
    ___x_cmd_ff_rec___info "Output: $output_file"
    ___x_cmd_ff_rec___info "Device: $device, Sample rate: ${sample_rate}Hz, Channels: $channels"
    ___x_cmd_ff_rec___info "Press Ctrl+C to stop recording"

    ___x_cmd_ff_mpeg___cmd \
        -f avfoundation \
        -i "$device" \
        -ar "$sample_rate" \
        -ac "$channels" \
        -c:a pcm_s16le \
        "$output_file" || return $?

    ___x_cmd_ff_rec___info "Recording saved to: $output_file"
}

___x_cmd_ff_rec___posix(){
    local output_file=""
    
    while [ "$#" -gt 0 ]; do
        case "$1" in
            -h|--help)
                x help -m ff rec
                return
                ;;
            -f|--file)
                output_file="$2"
                shift 2
                ;;
            *)
                [ -z "$output_file" ] || N=ff M="Unknown option: $1" log:ret:1
                output_file="$1"
                shift
                ;;
        esac
    done

    [ -n "$output_file" ] || {
        local timestamp
        timestamp="$(date +%Y%m%d-%H%M%S)"
        output_file="recording-${timestamp}.wav"
    }

    ___x_cmd_ff_rec___info "Starting audio recording (POSIX mode, using sox)..."
    ___x_cmd_ff_rec___info "Output: $output_file"
    
    if ___x_cmd_hascmd sox; then
        rec "$output_file" || return $?
    elif ___x_cmd_hascmd arecord; then
        arecord -f cd "$output_file" || return $?
    else
        N=ff M="No audio recording tool found. Install sox or alsa-utils." log:ret:1
    fi

    ___x_cmd_ff_rec___info "Recording saved to: $output_file"
}

___x_cmd_ff_rec___info(){
    printf "[ff:rec] %s\n" "$1" >&2
}
