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 = $null -ne (Get-Process -Id $agentPid -ErrorAction SilentlyContinue)
    }
}

$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
