#if os(Windows)
import Foundation
import WinSDK

/// Atomic file replacement on Windows (docs/WINDOWS_PORT.md §4.3).
///
/// The shared durable-write recipe is `write temp → fsync → rename(2)`, and both halves of the
/// tail are wrong here: Windows has no `fsync` reachable from Foundation, and the CRT's `rename`
/// is the C-standard one, which **fails** if the destination exists instead of replacing it
/// atomically the way POSIX does. `MoveFileExW` is the primitive that has POSIX rename's
/// semantics, and `MOVEFILE_WRITE_THROUGH` makes it return only once the move is on disk — the
/// durability `fsync` was buying.
///
/// Proven on Windows 11 amd64 (2026-07-29): `NucleicCarbonTests` drives `atomicWrite` through the
/// shard store, including the idempotent re-write of an already-present blob that a C `rename`
/// would have rejected.
enum WindowsAtomicMove {
    struct Failure: Error, CustomStringConvertible {
        let code: DWORD
        var description: String { "MoveFileExW failed (Win32 \(code))" }
    }

    private static let replaceExisting: DWORD = 0x0000_0001
    private static let writeThrough: DWORD = 0x0000_0008

    /// Replace `to` with `from`, atomically and durably. Both paths must be on the same volume,
    /// which the callers guarantee by staging the temp file in the destination's own directory.
    static func replace(from source: String, to destination: String) throws {
        let moved = source.withCString(encodedAs: UTF16.self) { sourceW in
            destination.withCString(encodedAs: UTF16.self) { destinationW in
                MoveFileExW(sourceW, destinationW, replaceExisting | writeThrough)
            }
        }
        guard moved.boolValue else { throw Failure(code: GetLastError()) }
    }
}
#endif
