$runnerRoot = 'C:\xiaoxia-ci\act_runner'
$configPath = Join-Path $runnerRoot 'config.yaml'
$runnerExe = Join-Path $runnerRoot 'act_runner.exe'
$workDir = Join-Path $runnerRoot 'work'
$logDir = Join-Path $runnerRoot 'logs'

$results = [ordered]@{
  runnerRootExists = Test-Path $runnerRoot
  runnerExeExists = Test-Path $runnerExe
  configExists = Test-Path $configPath
  workDirExists = Test-Path $workDir
  logDirExists = Test-Path $logDir
}

$processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
  Where-Object {
    $_.Name -match 'act_runner' -or
    $_.ExecutablePath -eq $runnerExe -or
    $_.CommandLine -match 'act_runner'
  } |
  Select-Object ProcessId, Name, ExecutablePath, CommandLine

$results['runnerProcessCount'] = @($processes).Count

$logSummary = @()
if (Test-Path $logDir) {
  $logSummary = Get-ChildItem $logDir -File -ErrorAction SilentlyContinue |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 10 Name, LastWriteTime, Length
}

Write-Host '=== Runner Files ==='
$results.GetEnumerator() | ForEach-Object {
  Write-Host ("{0}: {1}" -f $_.Key, $_.Value)
}

Write-Host "`n=== Runner Processes ==="
if (@($processes).Count -eq 0) {
  Write-Host 'No runner process found.'
} else {
  $processes | Format-Table -AutoSize
}

Write-Host "`n=== Recent Logs ==="
if (@($logSummary).Count -eq 0) {
  Write-Host 'No runner logs found.'
} else {
  $logSummary | Format-Table -AutoSize
}

if (-not $results['runnerExeExists'] -or -not $results['configExists']) {
  exit 2
}

if (@($processes).Count -eq 0) {
  exit 3
}

exit 0
