#!/usr/bin/env bash

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

# ¿Está activa la dGPU?
dgpu_is_active() {
  # Comprueba el estado de energía de la NVIDIA
  local status
  status=$(cat /sys/bus/pci/devices/0000:01:00.0/power/runtime_status 2>/dev/null)
  [[ "$status" == "active" ]]
}

get_dgpu_temp() {
  if dgpu_is_active; then
    # Usa nvidia-smi si la dGPU está activada
    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; exit}' \
    | 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() {
  # Temperatura de placa/ambiente (acpitz temp1)
  sensors \
    | awk '/acpitz-acpi-0/ {flag=1} flag && /temp1:/ {print $2; exit}' \
    | sed 's/+//;s/°C//'
}

# --- Leer/rotar modo ---
current_mode="cpu"
[[ -f "$STATE_FILE" ]] && current_mode=$(<"$STATE_FILE")

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

# --- Obtener todas las temperaturas ---
cpu=$(get_cpu_temp)     && cpu=${cpu:-N/A}
igpu=$(get_igpu_temp)   && igpu=${igpu:-N/A}
dgpu=$(get_dgpu_temp)   && dgpu=${dgpu:-N/A}
nvme=$(get_nvme_temp)   && nvme=${nvme:-N/A}
board=$(get_board_temp) && board=${board:-N/A}

# --- Escoge qué mostrar según modo ---
case "$current_mode" in
  cpu) icon="CPU";  temp="$cpu"  ;;
  igpu) icon="iGPU"; temp="$igpu" ;;
  dgpu) icon="dGPU"; temp="$dgpu" ;;
esac

# --- Tooltip multilínea ---
tooltip=$(printf \
  "CPU: %sº\niGPU: %sº\ndGPU: %sº\nNVMe: %sº\nBoard: %sº" \
  "$cpu" "$igpu" "$dgpu" "$nvme" "$board")

tooltip_escaped=$(printf "%s" "$tooltip" | jq -Rs .)

# --- Salida JSON para Waybar ---
echo "{\"text\": \"$icon: ${temp}º\", \"tooltip\": ${tooltip_escaped}}"

