#!/usr/bin/env bash

escape_json() {
  jq -Rn --arg str "$1" '$str'
}

#######################################
# INTENTO 1: PIPEWIRE (via pactl + pw-dump)
#######################################
default_sink="$(pactl get-default-sink 2>/dev/null)"

if [ -n "$default_sink" ]; then
  tmpfile="/tmp/pwdump.json"
  pw-dump > "$tmpfile" 2>/dev/null

  sink_id="$(
    jq -r --arg name "$default_sink" '
      .[] 
      | select(.info.props["node.name"] == $name) 
      | .id
    ' "$tmpfile"
  )"

  if [ -n "$sink_id" ] && [ "$sink_id" != "null" ]; then
    rate="$(
      jq -r --argjson id "$sink_id" '
        .[] 
        | select(.id == $id) 
        | (.info.params.Format[].rate // 0)
      ' "$tmpfile"
    )"

    pw_cli_info="$(pw-cli info "$sink_id" 2>/dev/null)"
    codec="$(echo "$pw_cli_info" \
      | grep -F 'api.bluez5.codec' \
      | sed -E 's/.*= "(.*)".*/\1/' \
      | tr -d '\r\n')"

    [ -z "$codec" ] && codec="N/A"
    [ -z "$rate" ] && rate="0"

    if [ "$rate" != "0" ]; then
      if [[ "$codec" =~ ^(aptx|aptX|ldac|LDAC|sbc|SBC)$ ]]; then
        text="${rate} Hz (${codec^^})"
      else
        text="${rate} Hz"
      fi
      tooltip="${default_sink} - ${rate} - ${codec}"

      # Escape con jq
jq -cn --arg text "$text" --arg tooltip "$tooltip" '{text: $text, tooltip: $tooltip}'

      exit 0
    fi
  fi
fi

#######################################
# INTENTO 2: ALSA directo
#######################################
for card_path in /proc/asound/card*/pcm*p/sub*/hw_params; do
  if [ -f "$card_path" ] && ! grep -q "closed" "$card_path"; then
    rate=$(awk '/^rate:/ {print $2}' "$card_path")
    format=$(awk '/^format:/ {print $2}' "$card_path")
    channels=$(awk '/^channels:/ {print $2}' "$card_path")

    if [[ "$card_path" =~ card([0-9]+)/pcm([0-9]+)p ]]; then
      card_id="${BASH_REMATCH[1]}"
      pcm_id="${BASH_REMATCH[2]}"
    else
      card_id="?"
      pcm_id="?"
    fi

    text="${rate} Hz (${format})"
    tooltip="ALSA hw:${card_id},${pcm_id} - ${rate} Hz - ${format} - ${channels} ch"

jq -cn --arg text "$text" --arg tooltip "$tooltip" '{text: $text, tooltip: $tooltip}'

    exit 0
  fi
done

#######################################
# Si no se encuentra nada en PipeWire ni ALSA
#######################################
echo '{"text":"","tooltip":"No active audio stream"}'

