#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <string>
#include <string_view>

#ifdef _WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <fcntl.h>
#include <unistd.h>
#endif

namespace {

enum class Result { not_replaced, durability_unknown, completed };

// The example owns filenames starting with ".savegame-" in this trusted directory.
Result write_durable_file(const std::filesystem::path& dir, std::string_view data) {
    const auto final_path = dir / "savegame.dat";
#ifdef _WIN32
    std::filesystem::path tmp_path;
    HANDLE h = INVALID_HANDLE_VALUE;
    for (unsigned attempt = 0; attempt < 128; ++attempt) {
        tmp_path = dir / (L".savegame-" + std::to_wstring(GetCurrentProcessId()) +
                          L"-" + std::to_wstring(attempt));
        h = CreateFileW(tmp_path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
                        FILE_ATTRIBUTE_NORMAL, nullptr);
        if (h != INVALID_HANDLE_VALUE) break;
        if (GetLastError() != ERROR_FILE_EXISTS) return Result::not_replaced;
    }
    if (h == INVALID_HANDLE_VALUE) return Result::not_replaced;

    const char* ptr = data.data();
    size_t remaining = data.size();
    while (remaining > 0) {
        DWORD chunk = static_cast<DWORD>(std::min<size_t>(remaining, 0x7FFFFFFFu));
        DWORD written = 0;
        if (!WriteFile(h, ptr, chunk, &written, nullptr) || written == 0) {
            CloseHandle(h);
            DeleteFileW(tmp_path.c_str());
            return Result::not_replaced;
        }
        ptr += written;
        remaining -= written;
    }

    const bool flushed = FlushFileBuffers(h) != 0;
    if (!CloseHandle(h) || !flushed) {
        DeleteFileW(tmp_path.c_str());
        return Result::not_replaced;
    }
    if (!MoveFileExW(tmp_path.c_str(), final_path.c_str(),
                     MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
        DeleteFileW(tmp_path.c_str());
        return Result::not_replaced;
    }
    return Result::completed; // Win32 call succeeded; not a POSIX directory-sync guarantee.
#else
    auto sync_fd = [](int fd) -> bool {
        int rc;
        do {
#ifdef __APPLE__
            rc = fcntl(fd, F_FULLFSYNC, 0);
#else
            rc = fsync(fd);
#endif
        } while (rc < 0 && errno == EINTR);
        return rc == 0;
    };

    std::string tmp_path = (dir / ".savegame-XXXXXX").string();
    int fd = mkstemp(tmp_path.data());
    if (fd < 0) return Result::not_replaced;

    const char* ptr = data.data();
    size_t remaining = data.size();
    while (remaining > 0) {
        ssize_t n = write(fd, ptr, remaining);
        if (n <= 0) {
            if (n < 0 && errno == EINTR) continue;
            close(fd);
            unlink(tmp_path.c_str());
            return Result::not_replaced;
        }
        ptr += n;
        remaining -= static_cast<size_t>(n);
    }

    const bool flushed = sync_fd(fd);
    if (close(fd) < 0 || !flushed || rename(tmp_path.c_str(), final_path.c_str()) < 0) {
        unlink(tmp_path.c_str());
        return Result::not_replaced;
    }

    // 3. Flush parent directory entry
    int dir_fd = open(dir.c_str(), O_RDONLY | O_DIRECTORY);
    if (dir_fd < 0) return Result::durability_unknown;
    bool ok = sync_fd(dir_fd);
    return close(dir_fd) == 0 && ok ? Result::completed : Result::durability_unknown;
#endif
}

}  // namespace

int main() {
    const Result result = write_durable_file(".", "high_score=9999\n");
    if (result == Result::completed) return 0;
    std::fputs(result == Result::not_replaced ? "File not replaced\n" :
               "Replacement visible; crash durability unknown\n", stderr);
    return 1;
}
