param(
    [string]$InstallDirectory = (Split-Path -Path $PSScriptRoot -Parent),
    [switch]$RawAgentJson
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$agentExe = Join-Path $InstallDirectory "agent\IAUWP.Agent.exe"
$pidPath = Join-Path $InstallDirectory "run\agent.pid"
$agentPid = $null
$running = $false

if (Test-Path -Path $pidPath) {
    $pidText = Get-Content -Path $pidPath -Raw
    if ($pidText -match '^\s*\d+\s*$') {
        $agentPid = [int]$pidText
        # Running means "this pid is OUR agent", not "some process has this pid"
        # (post-reboot pid reuse made this report false positives, 2026-07-29).
        $candidate = Get-Process -Id $agentPid -ErrorAction SilentlyContinue
        if ($candidate) {
            $candidateExe = $null
            try { $candidateExe = $candidate.Path } catch { $candidateExe = $null }
            $running = $candidateExe -and [string]::Equals($candidateExe, $agentExe, [StringComparison]::OrdinalIgnoreCase)
        }
    }
}

$agentStatusJson = $null
if (Test-Path -Path $agentExe) {
    try {
        $agentStatusJson = & $agentExe --status-json
    }
    catch {
        $agentStatusJson = $null
    }
}

if ($RawAgentJson.IsPresent) {
    if ($agentStatusJson) {
        $agentStatusJson
    }
    return
}

$summary = [pscustomobject]@{
    Installed = (Test-Path -Path $agentExe)
    InstallDirectory = $InstallDirectory
    AgentExe = $agentExe
    Pid = $agentPid
    Running = $running
    StartupConfigured = $false
    AgentStatusJson = if ($agentStatusJson) { ($agentStatusJson | Out-String).Trim() } else { $null }
}

$summary | ConvertTo-Json -Depth 8
