[CmdletBinding()]
param(
    [string]$Preset = "windows-msvc-default",
    [switch]$NoApp
)

$ErrorActionPreference = "Stop"
$started = Get-Date
$argsList = @(
    "--preset", $Preset,
    "-DPP_ENABLE_MSVC_ANALYZE=ON",
    "-DPP_ENABLE_CLANG_TIDY=ON",
    "-DPP_ENABLE_CPPCHECK=ON"
)
if ($NoApp) {
    $argsList += "-DPP_BUILD_APP=OFF"
}

& cmake @argsList
$configureExitCode = $LASTEXITCODE
$shaderExitCode = 0
$rendererBoundaryExitCode = 0

if ($configureExitCode -eq 0) {
    & cmake --build --preset $Preset --target panopainter_validate_shaders
    $shaderExitCode = $LASTEXITCODE
}

if ($configureExitCode -eq 0) {
    & powershell -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot "check-renderer-boundary.ps1")
    $rendererBoundaryExitCode = $LASTEXITCODE
}

$exitCode = $configureExitCode
if ($exitCode -eq 0 -and $shaderExitCode -ne 0) {
    $exitCode = $shaderExitCode
}
if ($exitCode -eq 0 -and $rendererBoundaryExitCode -ne 0) {
    $exitCode = $rendererBoundaryExitCode
}

$elapsed = [int]((Get-Date) - $started).TotalMilliseconds

[ordered]@{
    command = "analyze"
    preset = $Preset
    exitCode = $exitCode
    checks = @(
        [ordered]@{
            name = "configure"
            exitCode = $configureExitCode
        },
        [ordered]@{
            name = "shader-validation"
            exitCode = $shaderExitCode
        },
        [ordered]@{
            name = "renderer-boundary"
            exitCode = $rendererBoundaryExitCode
        }
    )
    elapsedMs = $elapsed
} | ConvertTo-Json -Compress -Depth 4

exit $exitCode
