# Read CPU temperature via LibreHardwareMonitor WMI.
# Prereq: 1) Install LibreHardwareMonitor  2) Run it (as Admin)  3) Keep it running
# winget install LibreHardwareMonitor.LibreHardwareMonitor

param([switch]$ListAll)

$ns = "root\LibreHardwareMonitor"
$ok = $false
try {
    $sensors = Get-CimInstance -Namespace $ns -ClassName Sensor -ErrorAction Stop
    $ok = $true
} catch {
    Write-Host "LibreHardwareMonitor WMI not available. Ensure:" -ForegroundColor Yellow
    Write-Host "  1. LibreHardwareMonitor is installed"
    Write-Host "  2. LibreHardwareMonitor.exe is running (can be minimized)"
    Write-Host "  3. Run LibreHardwareMonitor as Administrator"
    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

if ($ListAll) {
    $sensors | Where-Object { $_.SensorType -eq 'Temperature' } | Select-Object Name, Parent, Value | Format-Table -AutoSize
    exit 0
}

# Intel CPU (adjust to /amdcpu/0 for AMD)
$cpu = $sensors | Where-Object { $_.SensorType -eq 'Temperature' -and $_.Parent -like '/intelcpu/*' }
if (-not $cpu) {
    $cpu = $sensors | Where-Object { $_.SensorType -eq 'Temperature' -and $_.Parent -like '/amdcpu/*' }
}
if (-not $cpu) {
    Write-Host "No CPU temperature sensor found. Try -ListAll to see available sensors." -ForegroundColor Yellow
    exit 1
}

$cpu | ForEach-Object {
    $c = if ($null -ne $_.Value) { [Math]::Round($_.Value, 1) } else { "N/A" }
    Write-Host "$($_.Name): $c C  (Parent: $($_.Parent))"
}
