[CmdletBinding()]
param(
    [string[]]$Packages = @("standard"),
    [switch]$ConfigureOnly
)

$ErrorActionPreference = "Stop"

. "$PSScriptRoot\android-sdk-env.ps1"

function Expand-ArgumentList {
    param([string[]]$Values)

    $expanded = @()
    foreach ($value in $Values) {
        foreach ($part in ($value -split ",")) {
            $trimmed = $part.Trim()
            if ($trimmed.Length -gt 0) {
                $expanded += $trimmed
            }
        }
    }
    return $expanded
}

$Packages = @(Expand-ArgumentList -Values $Packages)

$toolchain = Set-AndroidSdkToolchainEnvironment
$packageMap = @{
    standard = "android/android"
    quest = "android/quest"
    focus = "android/focus"
}

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

foreach ($package in $Packages) {
    if (!$packageMap.ContainsKey($package)) {
        throw "Unknown Android package '$package'. Expected one of: standard, quest, focus."
    }

    $sourceDir = $packageMap[$package]
    $buildDir = "out/build/android-legacy-$package-arm64"
    $toolchainFile = Join-Path $toolchain.ndkPath "build\cmake\android.toolchain.cmake"

    $configureArgs = @(
        "-S", $sourceDir,
        "-B", $buildDir,
        "-G", "Ninja",
        "-DCMAKE_TOOLCHAIN_FILE=$toolchainFile",
        "-DANDROID_ABI=arm64-v8a",
        "-DANDROID_PLATFORM=android-23"
    )

    & $toolchain.cmakeCommand @configureArgs
    $configureExitCode = $LASTEXITCODE
    if ($configureExitCode -ne 0) {
        if ($overallExitCode -eq 0) {
            $overallExitCode = $configureExitCode
        }
        $results += [ordered]@{
            package = $package
            stage = "configure"
            exitCode = $configureExitCode
        }
        continue
    }

    if ($ConfigureOnly) {
        $results += [ordered]@{
            package = $package
            stage = "configure"
            exitCode = 0
        }
        continue
    }

    & $toolchain.cmakeCommand --build $buildDir --target native-lib
    $buildExitCode = $LASTEXITCODE
    if ($buildExitCode -ne 0 -and $overallExitCode -eq 0) {
        $overallExitCode = $buildExitCode
    }

    $results += [ordered]@{
        package = $package
        stage = "build"
        target = "native-lib"
        exitCode = $buildExitCode
    }
}

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

exit $overallExitCode
