#!/bin/bash

STATE_FILE="/tmp/waybar_temp_mode"
MODES=("cpu" "igpu" "dgpu")

# Detecta si la dGPU está realmente activa
dgpu_is_active() {
  runtime_status=$(cat /sys/bus/pci/devices/0000:01:00.0/power/runtime_status 2>/dev/null)
  [[ "$runtime_status" == "active" ]]
}

get_dgpu_temp() {
  if dgpu_is_active; then
    nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits 2>/dev/null || echo "N/A"
  else
    echo "N/A"
  fi
}

get_cpu_temp() {
  sensors | awk '/^Tctl:/ {print $2}' | sed 's/+//;s/°C//'
}

get_igpu_temp() {
  sensors | awk '/amdgpu/ {found=1} found && /edge:/ {print $2; exit}' | sed 's/+//;s/°C//'
}

get_nvme_temp() {
  sensors | awk '/nvme/ {found=1} found && /Composite:/ {print $2; exit}' | sed 's/+//;s/°C//'
}

get_board_temp() {
  sensors | awk '/temp1:/ && /°C/ {print $2; exit}' | sed 's/+//;s/°C//'
}

# Leer estado actual
current_mode="cpu"
[[ -f "$STATE_FILE" ]] && current_mode=$(<"$STATE_FILE")

# Cambiar modo si se hizo clic
if [[ "$1" == "click" ]]; then
  for i in "${!MODES[@]}"; do
    if [[ "${MODES[$i]}" == "$current_mode" ]]; then
      next_index=$(( (i + 1) % ${#MODES[@]} ))
      echo "${MODES[$next_index]}" > "$STATE_FILE"
      exit 0
    fi
  done
fi

# Obtener temperaturas
cpu=$(get_cpu_temp)
igpu=$(get_igpu_temp)
dgpu=$(get_dgpu_temp)
nvme=$(get_nvme_temp)
board=$(get_board_temp)

cpu=${cpu:-N/A}
igpu=${igpu:-N/A}
dgpu=${dgpu:-N/A}
nvme=${nvme:-N/A}
board=${board:-N/A}

# Definir ícono y valor visible
case "$current_mode" in
  cpu) icon="CPU"; temp="$cpu" ;;
  igpu) icon="iGPU"; temp="$igpu" ;;
  dgpu) icon="dGPU"; temp="$dgpu" ;;
esac

# Tooltip con \n y escapado correcto
tooltip=$(printf "CPU: %s°C\niGPU: %s°C\ndGPU: %s°C\nNVMe: %s°C\nBoard: %s°C" "$cpu" "$igpu" "$dgpu" "$nvme" "$board")
tooltip_escaped=$(echo "$tooltip" | jq -Rs .)

# Salida final
echo "{\"text\": \"$icon: ${temp}°C\", \"tooltip\": ${tooltip_escaped}}"
