. (Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "env_fast_sim.ps1")

$buildDir = Join-Path $PSScriptRoot "sim_build\verilator_cpp_current2"
$rtl = Join-Path $PSScriptRoot "rtl\counter.sv"
$cpp = Join-Path $PSScriptRoot "sim_main.cpp"

& verilator --cc --exe --trace --top-module counter -Mdir $buildDir -o counter_cpp `
    -CFLAGS "-std=gnu++17" -LDFLAGS "-lstdc++" $cpp $rtl
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

& make -C $buildDir -f Vcounter.mk -j 1
if ($LASTEXITCODE -ne 0) {
    Write-Host "mingw32-make did not complete the archive/link step; using Windows fallback link flow."
    $requiredObjects = @(
        "sim_main.o",
        "verilated.o",
        "verilated_vcd_c.o",
        "verilated_threads.o",
        "Vcounter__ALL.o"
    )
    foreach ($object in $requiredObjects) {
        if (-not (Test-Path -LiteralPath (Join-Path $buildDir $object))) {
            exit $LASTEXITCODE
        }
    }

    Push-Location $buildDir
    try {
        & ar -cr Vcounter__ALL.a Vcounter__ALL.o
        if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

        & g++ sim_main.o verilated.o verilated_vcd_c.o verilated_threads.o Vcounter__ALL.a `
            -pthread -lpthread -latomic -lstdc++ -o counter_cpp.exe
        if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
        Write-Host "Fallback link completed."
    } finally {
        Pop-Location
    }
}

Push-Location $buildDir
try {
    & .\counter_cpp.exe
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Verilator C++ smoke test passed."
    }
    exit $LASTEXITCODE
} finally {
    Pop-Location
}
