BareGit
#pragma once

#include <cstdint>
#include <mutex>
#include <string>

#include <nlohmann/json.hpp>

namespace nethack_mcp
{

using Json = nlohmann::json;

/// The version of the private parent/worker protocol.
inline constexpr std::uint32_t IPC_VERSION = 1;

/// The maximum encoded payload accepted by the private protocol.
inline constexpr std::uint32_t MAX_IPC_FRAME_SIZE = 4U * 1024U * 1024U;

/// Exchange length-prefixed JSON messages over one file descriptor.
class FramedChannel
{
public:
    /// Take ownership of an already connected stream descriptor.
    explicit FramedChannel(int descriptor);

    FramedChannel(const FramedChannel&) = delete;
    FramedChannel& operator=(const FramedChannel&) = delete;

    /// Close the descriptor owned by this channel.
    ~FramedChannel();

    /// Send one JSON message, returning a diagnostic on failure.
    bool send(const Json& message, std::string& error);

    /// Read one JSON message, returning a diagnostic on failure or EOF.
    bool receive(Json& message, std::string& error);

    /// Interrupt a blocked read and release the descriptor.
    void close();

private:
    bool readExact(void* buffer, std::size_t size, std::string& error);
    bool writeExact(const void* buffer, std::size_t size,
                   std::string& error);

    int descriptor_;
    std::mutex write_mutex_;
};

} // namespace nethack_mcp