#!/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() {
  gpu_mode_file="/tmp/gpu_mode"
  timestamp_file="/tmp/gpu_mode_timestamp"

  echo_na() {
    echo "N/A"
  }

  [[ ! -f "$gpu_mode_file" || ! -f "$timestamp_file" ]] && echo_na && return

  mode=$(< "$gpu_mode_file")
  last_change=$(< "$timestamp_file")
  now=$(date +%s)
  diff=$((now - last_change))

  # Solo permitir nvidia-smi si:
  # 1. El modo es nvidia
  # 2. Han pasado más de 5s
  # 3. La dGPU está realmente activa
  if [[ "$mode" == "nvidia" && "$diff" -gt 5 && $(dgpu_is_active) ]]; then
    nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits 2>/dev/null
  else
    echo_na
  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}}"

