# psopenai-eventlog.ps1
# Requires: Install-Module -Name PSOpenAI

$envPath = Join-Path $PSScriptRoot '.env'
Get-Content $envPath |
    Where-Object { $_ -match '^([^#=]+)=(.+)$' } |
    ForEach-Object {
        $k, $v = $_ -split '=', 2
        $v = $v.Trim().Trim('"')
        [Environment]::SetEnvironmentVariable(
            $k.Trim(), $v)
    }

$sysPrompt = @"
You are a Windows sysadmin assistant. You help with log analysis.

* Give a short summary (2-3 sentences).
* Group most critical issues by source.
* Specify concrete remediation steps for each issue.

Keep the response under 300 words.
"@

function Get-RecentErrors ([int]$Max = 60) {
    $events = foreach ($log in 'Application', 'System') {
        try {
            Get-WinEvent -LogName $log -MaxEvents $Max |
                Where-Object { $_.Level -in 1, 2 }
        } catch {}
    }
    $events | Sort-Object TimeCreated -Descending |
        Select-Object -First 30
}

$events = Get-RecentErrors
if (-not $events) { Write-Host 'No errors found.'; exit 0 }

# compact log entries
$lines = $events | ForEach-Object {
    $msg = ($_.Message -replace '\s+', ' ')
    if ($msg.Length -gt 200) {
        $msg = $msg.Substring(0, 200)
    }
    $lvl = if ($_.Level -eq 1) { 'CRIT' } else { 'ERR' }
    '[{0}] {1} {2}: {3}' -f
        $_.TimeCreated.ToString('MM-dd HH:mm'),
        $lvl, $_.ProviderName, $msg
}

$prompt = "Windows Event Log entries:`n" +
    ($lines -join "`n")

Write-Host 'Analyzing Event Log entries...'
$r = Request-ChatCompletion `
    -Model 'gpt-5.4-mini' `
    -SystemMessage $sysPrompt `
    -Message $prompt `
    -Temperature 0.2

Write-Host "`nEvent Log Analysis"
Write-Host ('=' * 60)
Write-Host $r.Answer
