param(
  [Parameter(Mandatory=$true)][string]$StartUtc,
  [Parameter(Mandatory=$true)][string]$EndUtc,
  [Parameter(Mandatory=$true)][string]$OutputPath
)
$ErrorActionPreference = 'Stop'
$studyStart = [DateTimeOffset]::Parse($StartUtc)
$studyEnd = [DateTimeOffset]::Parse($EndUtc)
if ($studyEnd -le $studyStart) { throw 'The study interval must have positive duration.' }
$queryStatus = 'query_completed'
try {
  $studyEvents = @(Get-WinEvent -FilterHashtable @{
    LogName='System'; ProviderName='Microsoft-Windows-Kernel-Power'; Id=506,507
    StartTime=$studyStart.LocalDateTime; EndTime=$studyEnd.LocalDateTime
  } | Sort-Object TimeCreated | ForEach-Object {
    [ordered]@{
      timestamp_utc=$_.TimeCreated.ToUniversalTime().ToString('o')
      provider=$_.ProviderName
      event_id=$_.Id
      description_first_line=($_.Message -split "`r?`n")[0]
    }
  })
} catch {
  if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {
    $studyEvents=@(); $queryStatus='query_completed_no_matching_events'
  } else { throw }
}
[ordered]@{
  interval_start_utc=$studyStart.ToUniversalTime().ToString('o')
  interval_end_utc=$studyEnd.ToUniversalTime().ToString('o')
  selection='System / Microsoft-Windows-Kernel-Power / event IDs 506 and 507 only'
  retrieval_status=$queryStatus
  interpretation='Bounded recorded host transitions; temporal overlap does not establish the cause of every failure. Absence means no matching event was found in this interval, not proof of universal sleep prevention.'
  events=$studyEvents
} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $OutputPath -Encoding utf8
Write-Output "Saved $($studyEvents.Count) bounded host-power events."
