#!/usr/bin/env bash

set -e

echo "=============================="
echo "🔊 POWERCONF AUDIO CHECK"
echo "=============================="
echo

# ----------------------------------
# Detect PowerConf card + device
# ----------------------------------
POWERCONF_LINE=$(arecord -l | grep -i "PowerConf" | head -1)

if [ -z "$POWERCONF_LINE" ]; then
    echo "❌ PowerConf device not found"
    exit 1
fi

CARD_INDEX=$(echo "$POWERCONF_LINE" | sed -n 's/.*card \([0-9]\+\):.*/\1/p')
DEVICE_INDEX=$(echo "$POWERCONF_LINE" | sed -n 's/.*device \([0-9]\+\):.*/\1/p')

echo "✅ PowerConf detected:"
echo "   Card   = $CARD_INDEX"
echo "   Device = $DEVICE_INDEX"
echo "   ALSA   = hw:${CARD_INDEX},${DEVICE_INDEX}"
echo

# ----------------------------------
# Capture devices (PowerConf only)
# ----------------------------------
echo "🎤 CAPTURE DEVICE (PowerConf only)"
arecord -l | grep -i -A4 "PowerConf"
echo

# ----------------------------------
# Playback devices (PowerConf only)
# ----------------------------------
echo "🔈 PLAYBACK DEVICE (PowerConf only)"
aplay -l | grep -i -A4 "PowerConf"
echo

# ----------------------------------
# Capture HW params (forced safe)
# ----------------------------------
echo "🎤 MICROPHONE HARDWARE PARAMETERS (PowerConf)"

MIC_HW=$(arecord -D hw:${CARD_INDEX},${DEVICE_INDEX} \
    -f S16_LE -r 48000 -c 1 \
    -d 0.1 --dump-hw-params 2>/dev/null)

echo "$MIC_HW" | grep -E "FORMAT:|CHANNELS:|RATE:"
echo

# ----------------------------------
# Playback HW params (forced safe)
# ----------------------------------
echo "🔈 SPEAKER HARDWARE PARAMETERS (PowerConf)"

SPK_HW=$(aplay -D hw:${CARD_INDEX},${DEVICE_INDEX} \
    -f S16_LE -r 48000 -c 1 \
    -d 0.1 --dump-hw-params /dev/zero 2>/dev/null)

echo "$SPK_HW" | grep -E "FORMAT:|CHANNELS:|RATE:"
echo

# ----------------------------------
# Extract clean values
# ----------------------------------
FORMAT=$(echo "$MIC_HW" | grep -m1 "FORMAT"   | awk '{print $2}')
RATE=$(echo "$MIC_HW"   | grep -m1 "RATE"     | awk '{print $2}')
CHANNELS_IN=$(echo "$MIC_HW" | grep -m1 "CHANNELS" | awk '{print $2}')
CHANNELS_OUT=$(echo "$SPK_HW" | grep -m1 "CHANNELS" | awk '{print $2}')

FORMAT=${FORMAT:-S16_LE}
RATE=${RATE:-48000}
CHANNELS_IN=${CHANNELS_IN:-1}
CHANNELS_OUT=${CHANNELS_OUT:-1}
CHUNK=960

# ----------------------------------
# Final verified Python config
# ----------------------------------
echo "=============================="
echo "✅ VERIFIED POWERCONF PYTHON CONFIG"
echo "=============================="
echo "FORMAT        = pyaudio.paInt16  # ${FORMAT}"
echo "RATE          = ${RATE}"
echo "CHANNELS_IN   = ${CHANNELS_IN}"
echo "CHANNELS_OUT  = ${CHANNELS_OUT}"
echo "CHUNK         = ${CHUNK}"
echo "INPUT_DEVICE  = ${CARD_INDEX}"
echo "OUTPUT_DEVICE = ${CARD_INDEX}"
echo
echo "✔ PowerConf USB Audio"
echo "✔ Mono mic + Mono speaker"
echo "✔ hw:${CARD_INDEX},${DEVICE_INDEX}"
echo "=============================="
