#!/usr/bin/env pwsh
# Sandbox Test Runner for PowerShell

Write-Host "========================================"
Write-Host "    MOSIS SANDBOX TEST RUNNER"
Write-Host "========================================"
Write-Host ""

$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Push-Location $scriptDir

try {
    # Check if build exists
    if (-not (Test-Path "build/Debug/sandbox-test.exe")) {
        Write-Host "Build not found. Building..."
        Write-Host ""

        # Check VCPKG_ROOT
        if (-not $env:VCPKG_ROOT) {
            Write-Error "VCPKG_ROOT environment variable not set"
            exit 1
        }

        # Configure
        Write-Host "Configuring CMake..."
        cmake -B build "-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
        if ($LASTEXITCODE -ne 0) {
            Write-Error "CMake configure failed"
            exit 1
        }

        # Build
        Write-Host "Building..."
        cmake --build build --config Debug
        if ($LASTEXITCODE -ne 0) {
            Write-Error "Build failed"
            exit 1
        }
        Write-Host ""
    }

    # Run tests
    Write-Host "Running tests..."
    Write-Host ""

    Push-Location "build/Debug"
    & ./sandbox-test.exe @args
    $testResult = $LASTEXITCODE
    Pop-Location

    Write-Host ""
    if ($testResult -eq 0) {
        Write-Host "========================================"
        Write-Host "    ALL TESTS PASSED"
        Write-Host "========================================"
    } else {
        Write-Host "========================================"
        Write-Host "    SOME TESTS FAILED"
        Write-Host "========================================"
    }

    exit $testResult
}
finally {
    Pop-Location
}
