"""
PlatformIO pre-script for the `native` env: points the build at the
PlatformIO-installed mingw toolchain so host tests run on Windows without
requiring a system-wide g++. Installed via:

    pio pkg install -g -t "platformio/toolchain-gccmingw32"
"""
import os
from pathlib import Path

Import("env")  # noqa: F821  (PlatformIO-provided)

TOOLCHAIN = Path.home() / ".platformio" / "packages" / "toolchain-gccmingw32" / "bin"

if TOOLCHAIN.is_dir():
    # Prepend to PATH so SCons picks up g++/gcc/ar from here
    os.environ["PATH"] = str(TOOLCHAIN) + os.pathsep + os.environ.get("PATH", "")
    env.Replace(
        CC=str(TOOLCHAIN / "gcc.exe"),
        CXX=str(TOOLCHAIN / "g++.exe"),
        AR=str(TOOLCHAIN / "ar.exe"),
        RANLIB=str(TOOLCHAIN / "ranlib.exe"),
    )
    # Force static linking so the test binary doesn't depend on
    # mingw runtime DLLs at exec time. Must be LINKFLAGS, not build_flags.
    env.Append(
        LINKFLAGS=[
            "-static",
            "-static-libgcc",
            "-static-libstdc++",
        ],
    )
    print(f"[native_toolchain] using mingw from {TOOLCHAIN} (static-linked)")
else:
    print(f"[native_toolchain] WARNING: {TOOLCHAIN} not found; tests may fail to build")
