#if os(Windows)
import Foundation
import WinSDK

// POSIX `setenv`/`unsetenv` for Windows (docs/WINDOWS_PORT.md §4.3). `ucrt` has neither, and
// the shared code calls them by those names — the blank-API-key scrub in `NucleicHeadless`, the
// runner credential vault's env landings, both headless hosts' transport default, and
// `DirectUpgradeLoopbackTests` pointing the STUN client at a local responder. Same stand-in move
// as `WindowsSignals.swift`: the call sites stay platform-free.
//
// This lives in NucleicProtocol, the LOWEST module that needs it, rather than beside the other
// §4.3 shims in NucleicCore/Windows/. `NucleicProtocolTests` reaches for it, and that suite has
// to build under `NUCLEIC_WINDOWS_PROTOCOL_ONLY=1`, where the manifest is narrowed to
// NucleicProtocol + its tests and NucleicCore does not exist. NucleicCore re-exports
// NucleicProtocol (`ProtocolExports.swift`), so its own call sites see these unqualified.
//
// `SetEnvironmentVariableW` rather than the CRT's `_putenv_s` because the Win32 environment block
// is what corelibs-foundation's `ProcessInfo.environment` reads and what `CreateProcess` hands a
// child; the CRT's private copy is read by nothing Nucleic runs.

/// POSIX `setenv`. Returns 0 on success, -1 on failure.
@discardableResult
public func setenv(_ name: String, _ value: String, _ overwrite: Int32) -> Int32 {
    if overwrite == 0, ProcessInfo.processInfo.environment[name] != nil { return 0 }
    let ok = name.withCString(encodedAs: UTF16.self) { nameW in
        value.withCString(encodedAs: UTF16.self) { valueW in
            SetEnvironmentVariableW(nameW, valueW)
        }
    }
    // `.boolValue`: older toolchains import Win32 `BOOL` as `WindowsBool`, which can't stand
    // alone in a condition. Newer ones import it as plain `Bool`, where this is the identity
    // shim below.
    return ok.boolValue ? 0 : -1
}

/// POSIX `unsetenv`. A nil value deletes the variable on Windows.
@discardableResult
public func unsetenv(_ name: String) -> Int32 {
    let ok = name.withCString(encodedAs: UTF16.self) { SetEnvironmentVariableW($0, nil) }
    return ok.boolValue ? 0 : -1
}

extension Bool {
    /// Lets the `.boolValue` spelling above compile under either importer — see the note there.
    /// Mirrors the same shim in `NucleicCore/Windows/WindowsSupport.swift`; both are internal to
    /// their module, so neither is visible to the other.
    @inline(__always) var boolValue: Bool { self }
}
#endif
