$ErrorActionPreference = 'Stop'

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\..')
$expectedJar = Join-Path $repoRoot 'ruoyi-admin\target\ruoyi-admin.jar'
$originalJar = Join-Path $repoRoot 'ruoyi-admin\target\ruoyi-admin.jar.original'
$backupOriginalJar = "$originalJar.codex-test-backup"

Push-Location $repoRoot
try {
    $output = cmd /c "set RY_DRY_RUN=1&& call ry.bat start" 2>&1 | Out-String
    $exitCode = $LASTEXITCODE

    if ($exitCode -ne 0) {
        throw "ry.bat dry-run failed with exit code $exitCode.`n$output"
    }

    if ($output -notmatch 'START_CMD=java ') {
        throw "Expected START_CMD output was not found.`n$output"
    }

    if ($output -notmatch [regex]::Escape($expectedJar)) {
        throw "Expected jar path was not found in dry-run output.`n$output"
    }

    foreach ($unsupportedToken in @('PrintGCDateStamps', 'UseParallelOldGC', 'javaw')) {
        if ($output -match [regex]::Escape($unsupportedToken)) {
            throw "Unexpected token [$unsupportedToken] found in dry-run output.`n$output"
        }
    }

    if (Test-Path $originalJar) {
        Move-Item -Path $originalJar -Destination $backupOriginalJar -Force
        try {
            $packageOutput = cmd /c "set RY_DRY_RUN=1&& call ry.bat start" 2>&1 | Out-String
            $packageExitCode = $LASTEXITCODE

            if ($packageExitCode -ne 0) {
                throw "ry.bat package dry-run failed with exit code $packageExitCode.`n$packageOutput"
            }

            if ($packageOutput -notmatch 'BUILD_CMD=mvn -pl ruoyi-admin -am package -DskipTests') {
                throw "Expected BUILD_CMD output was not found.`n$packageOutput"
            }

            if ($packageOutput -notmatch [regex]::Escape($expectedJar)) {
                throw "Expected jar path was not found in package dry-run output.`n$packageOutput"
            }
        }
        finally {
            if (Test-Path $backupOriginalJar) {
                Move-Item -Path $backupOriginalJar -Destination $originalJar -Force
            }
        }
    }

    Write-Host 'ry.bat dry-run verification passed.'
}
finally {
    if (Test-Path $backupOriginalJar) {
        Move-Item -Path $backupOriginalJar -Destination $originalJar -Force
    }

    Pop-Location
}
