param(
    [switch] $IncludeRemoteArgoCD
)

$ErrorActionPreference = "Stop"
$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")

function Test-KustomizeDir {
    param(
        [Parameter(Mandatory = $true)][string] $RelativePath,
        [Parameter(Mandatory = $true)][string] $Label
    )

    $path = Join-Path $RepoRoot $RelativePath
    if (-not (Test-Path $path)) {
        throw "Missing kustomize path: $path"
    }

    Write-Host "== $Label ($RelativePath) ==" -ForegroundColor Cyan
    $out = & kubectl kustomize $path 2>&1
    if ($LASTEXITCODE -ne 0) {
        Write-Host $out
        throw "kubectl kustomize failed for $RelativePath (exit $LASTEXITCODE)"
    }

    if (-not $out) {
        throw "kubectl kustomize produced empty output for $RelativePath"
    }

    $docCount = ($out | Select-String -Pattern "^---$" -AllMatches).Matches.Count + 1
    Write-Host ("OK ({0} YAML documents emitted)" -f $docCount) -ForegroundColor Green
}

$targets = @(
    @{ Rel = "platform\bootstrap"; Label = "platform-bootstrap" },
    @{ Rel = "platform\bootstrap\apps"; Label = "argocd-app-of-apps" },
    @{ Rel = "platform\networking"; Label = "platform-networking" },
    @{ Rel = "platform\security"; Label = "platform-security" },
    @{ Rel = "platform\data"; Label = "platform-data" },
    @{ Rel = "observability"; Label = "observability" },
    @{ Rel = "ai-core"; Label = "ai-core" },
    @{ Rel = "tools-mcp"; Label = "tools-mcp" },
    @{ Rel = "agents\k8s"; Label = "agents-k8s" },
    @{ Rel = "interface\k8s"; Label = "interface-k8s" }
)

foreach ($t in $targets) {
    Test-KustomizeDir -RelativePath $t.Rel -Label $t.Label
}

if ($IncludeRemoteArgoCD) {
    Test-KustomizeDir -RelativePath "platform\bootstrap\initial-argocd" -Label "initial-argocd (remote)"
}

Write-Host "All requested kustomize builds succeeded." -ForegroundColor Green
