Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Pinned generator baseline. The committed Python bindings are stamped with
# GRPC_GENERATED_VERSION = 1.80.0 and "Protobuf Python Version: 6.31.1". A newer grpcio-tools
# stamps a higher GRPC_GENERATED_VERSION than the pinned grpcio runtime (pyproject.toml:
# grpcio>=1.80,<2), which makes _pb2_grpc import raise at runtime and breaks pytest. Regeneration
# MUST use this exact grpcio-tools version. See docs/ClientProtoGeneration.md and the repo memory
# project_python_client_regen_pin.
$PinnedGrpcioToolsVersion = '1.80.0'

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..')
$protoRoot = Join-Path $repoRoot 'src\ZB.MOM.WW.MxGateway.Contracts\Protos'
$outputRoot = Join-Path $PSScriptRoot 'src\zb_mom_ww_mxgateway\generated'

function Resolve-Python {
    # Prefer python on PATH (python on Windows, python3 on Linux/macOS), then the documented
    # Windows install location. Avoids the previous hard-coded per-machine path.
    foreach ($name in @('python', 'python3', 'python.exe')) {
        $cmd = Get-Command $name -ErrorAction SilentlyContinue
        if ($null -ne $cmd) {
            return $cmd.Source
        }
    }

    if ($env:LOCALAPPDATA) {
        $documentedPath = Join-Path $env:LOCALAPPDATA 'Programs\Python\Python312\python.exe'
        if (Test-Path $documentedPath) {
            return $documentedPath
        }
    }

    throw 'Could not find python on PATH. See docs/ToolchainLinks.md.'
}

function Assert-GrpcioToolsVersion {
    param([string]$Python)

    # Windows PowerShell 5.1 strips embedded double quotes when passing an argument to a native
    # exe (pwsh 7 does not), so a Python literal quoted with " " here would arrive at Python as
    # print(version(grpcio-tools)) -> NameError. Use single quotes for the Python string literal
    # inside this double-quoted PowerShell string so the quoting survives on both hosts.
    $version = (& $Python -c "import grpc_tools; from importlib.metadata import version; print(version('grpcio-tools'))").Trim()
    if ($version -ne $PinnedGrpcioToolsVersion) {
        throw "grpcio-tools $version is installed, but regeneration is pinned to $PinnedGrpcioToolsVersion. " +
            "Install the pin (python -m pip install 'grpcio-tools==$PinnedGrpcioToolsVersion') before regenerating, " +
            "or the generated bindings will stamp a GRPC_GENERATED_VERSION the pinned grpcio runtime rejects."
    }
}

$python = Resolve-Python
Assert-GrpcioToolsVersion -Python $python

New-Item -ItemType Directory -Path $outputRoot -Force | Out-Null
Get-ChildItem -Path (Join-Path $outputRoot '*_pb2.py') -File | Remove-Item
Get-ChildItem -Path (Join-Path $outputRoot '*_pb2_grpc.py') -File | Remove-Item

& $python -m grpc_tools.protoc `
    "-I$protoRoot" `
    "--python_out=$outputRoot" `
    "--grpc_python_out=$outputRoot" `
    mxaccess_gateway.proto `
    mxaccess_worker.proto `
    galaxy_repository.proto

if ($LASTEXITCODE -ne 0) {
    throw "grpc_tools.protoc failed with exit code $LASTEXITCODE."
}
