[CmdletBinding()]
param(
    [string[]]$Presets = @("android-arm64"),
    [string[]]$Targets = @(
        "pp_foundation",
        "pp_assets",
        "pp_paint",
        "pp_document",
        "pp_renderer_api",
        "pp_renderer_gl",
        "pp_paint_renderer",
        "pp_ui_core",
        "pp_platform_api",
        "pp_app_core",
        "pano_cli",
        "pp_foundation_binary_stream_tests",
        "pp_foundation_event_tests",
        "pp_foundation_log_tests",
        "pp_foundation_parse_tests",
        "pp_foundation_task_queue_tests",
        "pp_foundation_trace_tests",
        "pp_assets_image_format_tests",
        "pp_assets_image_metadata_tests",
        "pp_assets_image_pixels_tests",
        "pp_assets_ppi_header_tests",
        "pp_assets_settings_document_tests",
        "pp_paint_brush_tests",
        "pp_paint_blend_tests",
        "pp_paint_stroke_tests",
        "pp_paint_stroke_script_tests",
        "pp_document_tests",
        "pp_document_ppi_import_tests",
        "pp_document_ppi_export_tests",
        "pp_renderer_api_tests",
        "pp_renderer_gl_capabilities_tests",
        "pp_renderer_gl_command_plan_tests",
        "pp_paint_renderer_compositor_tests",
        "pp_platform_api_tests",
        "pp_ui_core_color_tests",
        "pp_ui_core_layout_value_tests",
        "pp_ui_core_layout_xml_tests",
        "pp_app_core_document_route_tests",
        "pp_app_core_document_export_tests",
        "pp_app_core_document_cloud_tests",
        "pp_app_core_document_platform_io_tests",
        "pp_app_core_document_recording_tests",
        "pp_app_core_app_preferences_tests",
        "pp_app_core_app_status_tests",
        "pp_app_core_document_sharing_tests",
        "pp_app_core_document_session_tests"
    )
)

$ErrorActionPreference = "Stop"
$started = Get-Date
$results = @()
$overallExitCode = 0

foreach ($preset in $Presets) {
    & cmake --preset $preset
    $configureExitCode = $LASTEXITCODE
    if ($configureExitCode -ne 0) {
        $overallExitCode = $configureExitCode
        $results += [ordered]@{
            preset = $preset
            stage = "configure"
            exitCode = $configureExitCode
        }
        continue
    }

    $buildArgs = @("--build", "--preset", $preset)
    foreach ($target in $Targets) {
        $buildArgs += @("--target", $target)
    }

    & cmake @buildArgs
    $buildExitCode = $LASTEXITCODE
    if ($buildExitCode -ne 0 -and $overallExitCode -eq 0) {
        $overallExitCode = $buildExitCode
    }

    $results += [ordered]@{
        preset = $preset
        stage = "build"
        targets = $Targets
        exitCode = $buildExitCode
    }
}

$elapsed = [int]((Get-Date) - $started).TotalMilliseconds
[ordered]@{
    command = "platform-build"
    exitCode = $overallExitCode
    elapsedMs = $elapsed
    results = $results
} | ConvertTo-Json -Compress -Depth 6

exit $overallExitCode
