$ErrorActionPreference = "Stop"

function Find-OctaveCli {
    if ($env:OCTAVE_CLI -and (Test-Path $env:OCTAVE_CLI)) {
        return (Resolve-Path $env:OCTAVE_CLI).Path
    }

    $command = Get-Command octave-cli.exe -ErrorAction SilentlyContinue
    if ($command) {
        return $command.Source
    }

    $roots = @(
        "$env:ProgramFiles\GNU Octave",
        "${env:ProgramFiles(x86)}\GNU Octave"
    ) | Where-Object { $_ -and (Test-Path $_) }

    $candidates = foreach ($root in $roots) {
        Get-ChildItem $root -Filter octave-cli.exe -File -Recurse -ErrorAction SilentlyContinue
    }

    return $candidates |
        Sort-Object LastWriteTime -Descending |
        Select-Object -First 1 -ExpandProperty FullName
}

$octave = Find-OctaveCli
if (-not $octave) {
    throw "octave-cli.exe was not found. Install GNU Octave or set OCTAVE_CLI."
}

Write-Host "Octave executable:" -ForegroundColor Cyan
Write-Host "  $octave"
Write-Host ""

& $octave --version
if ($LASTEXITCODE -ne 0) {
    throw "octave-cli.exe returned exit code $LASTEXITCODE."
}

$script = Join-Path $env:TEMP ("OctaveExcel_" + [guid]::NewGuid().ToString("N") + ".m")

@'
printf ("OCTAVEEXCEL_AIRY=%.17g\n", airy (0, 0));
'@ | Set-Content $script -Encoding ASCII

try {
    $output = & $octave -qf --no-line-editing --no-window-system $script
    if ($LASTEXITCODE -ne 0) {
        throw "The Octave function test failed with exit code $LASTEXITCODE."
    }

    $line = $output | Where-Object { $_ -like "OCTAVEEXCEL_AIRY=*" } | Select-Object -First 1
    if (-not $line) {
        throw "The Octave function test did not return the expected output."
    }

    Write-Host ""
    Write-Host $line -ForegroundColor Green
    Write-Host "GNU Octave is ready for OctaveExcel." -ForegroundColor Green
}
finally {
    Remove-Item $script -Force -ErrorAction SilentlyContinue
}
