# Monitor ACPI Thermal Zones (source of Event 86 "critical thermal event")
# Also optional ectool temps. Run as Admin for best WMI access. Ctrl+C quit.

param(
    [int]$IntervalSeconds = 5,
    [int]$WarnThresholdC  = 85,
    [switch]$NoEctool
)

$EctoolPath = "C:\Program Files\crosec\ectool.exe"
$HasEctool  = (Test-Path $EctoolPath) -and (-not $NoEctool)

Write-Host "Thermal Zone Monitor (every ${IntervalSeconds}s, Ctrl+C quit)" -ForegroundColor Green
Write-Host "Warn threshold: ${WarnThresholdC}C | ectool: $(if($HasEctool){'enabled'}else{'disabled'})"
Write-Host ""

function Get-ThermalZoneTemps {
    try {
        $zones = Get-CimInstance -Namespace "root/wmi" -ClassName MSAcpi_ThermalZoneTemperature -ErrorAction Stop
        if (-not $zones -or $zones.Count -eq 0) { return $null }
        $out = @()
        $idx = 0
        foreach ($z in $zones) {
            $idx++
            $kelvin10 = $z.CurrentTemperature
            if ($null -eq $kelvin10 -or $kelvin10 -eq 0) {
                $out += [PSCustomObject]@{ Index = $idx; TempC = $null; Raw = $kelvin10 }
                continue
            }
            $celsius = ($kelvin10 / 10.0) - 273.15
            $out += [PSCustomObject]@{ Index = $idx; TempC = [Math]::Round($celsius, 1); Raw = $kelvin10 }
        }
        return $out
    } catch {
        Write-Host "WMI thermal zone read failed: $($_.Exception.Message)" -ForegroundColor Red
        return $null
    }
}

function Show-Warning {
    param([double]$TempC)
    if ($null -eq $TempC) { return }
    if ($TempC -ge $WarnThresholdC) {
        Write-Host " *** WARNING: $TempC C >= ${WarnThresholdC}C - approaching critical thermal event ***" -ForegroundColor Red
    }
}

try {
    while ($true) {
        $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Write-Host "--- $ts ---" -ForegroundColor Cyan

        # ACPI thermal zones (these trigger Event 86 when critical)
        $zones = Get-ThermalZoneTemps
        if ($zones) {
            foreach ($z in $zones) {
                $msg = "Thermal Zone $($z.Index): "
                if ($null -ne $z.TempC) {
                    $msg += "$($z.TempC) C"
                    Show-Warning -TempC $z.TempC
                } else {
                    $msg += "N/A (raw $($z.Raw))"
                }
                Write-Host $msg
            }
        } else {
            Write-Host "ACPI Thermal Zones: Not available (BIOS/driver may not expose WMI)." -ForegroundColor DarkYellow
        }

        # Chrome EC sensor (if present)
        if ($HasEctool) {
            Write-Host "EC sensor (ectool temps 0):" -ForegroundColor DarkGray
            & $EctoolPath temps 0
        }

        Write-Host ""
        Start-Sleep -Seconds $IntervalSeconds
    }
} finally {
    Write-Host "Monitor stopped." -ForegroundColor Cyan
}
