#!/bin/bash
SOURCE="alsa_input.pci-0000_c1_00.6.analog-stereo"
HEADSET_PORT="analog-input-headset-mic"
INTERNAL_PORT="analog-input-internal-mic"
WAYBAR_SIGNAL_FILE="/tmp/waybar-mic-update"

# Función para log con timestamp
log() {
	echo "[$(date '+%H:%M:%S')] $1"
}

# Función para notificar a waybar
notify_waybar() {
	local port="$1"
	local status_file="$HOME/.cache/mic-status"

	case "$port" in
	"$HEADSET_PORT")
		echo '{"text":"🎧","tooltip":"Headset microphone","class":"headset"}' >"$status_file"
		;;
	"$INTERNAL_PORT")
		echo '{"text":"💻","tooltip":"Internal microphone","class":"internal"}' >"$status_file"
		;;
	*)
		echo '{"text":"🎤","tooltip":"Unknown: '"$port"'","class":"unknown"}' >"$status_file"
		;;
	esac

	# Señal a waybar para actualizar (si está usando el método de archivo)
	touch "$WAYBAR_SIGNAL_FILE"
}

# Función para cambiar puerto con verificación
switch_port() {
	local port="$1"
	local name="$2"

	if pactl set-source-port "$SOURCE" "$port" 2>/dev/null; then
		log "✓ Switched to $name"
		notify_waybar "$port"
	else
		log "✗ Failed to switch to $name"
	fi
}

# Verificar que pactl existe
if ! command -v pactl &>/dev/null; then
	log "✗ pactl not found. Install pulseaudio-utils"
	exit 1
fi

log "Starting microphone auto-switcher..."
log "Monitoring: $SOURCE"

# Procesar estado inicial
source_info=$(pactl list sources | grep -A1000 "$SOURCE" 2>/dev/null)
if [ -z "$source_info" ]; then
	log "✗ Source not found: $SOURCE"
	exit 1
fi

# Estado inicial para waybar
active_port=$(echo "$source_info" | grep "Active Port" | awk '{print $3}')
notify_waybar "$active_port"

# Loop principal
pactl subscribe 2>/dev/null | while read -r line; do
	if echo "$line" | grep -q "Event 'change' on source"; then
		# Obtener info actual
		source_info=$(pactl list sources | grep -A1000 "$SOURCE" 2>/dev/null)
		[ -z "$source_info" ] && continue

		active_port=$(echo "$source_info" | grep "Active Port" | awk '{print $3}')
		headset_status=$(echo "$source_info" | grep "$HEADSET_PORT")

		log "Event detected - Active: $active_port"

		# Lógica de switching simplificada
		if echo "$headset_status" | grep -q "availability unknown"; then
			# Headset conectado
			if [[ "$active_port" != "$HEADSET_PORT" ]]; then
				switch_port "$HEADSET_PORT" "headset mic"
			fi
		elif echo "$headset_status" | grep -q "not available"; then
			# Headset desconectado
			if [[ "$active_port" != "$INTERNAL_PORT" ]]; then
				switch_port "$INTERNAL_PORT" "internal mic"
			fi
		fi
	fi
done

log "✗ pactl subscribe ended unexpectedly"
