/*
 * Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <algorithm>
#include <bit>
#include <cinttypes>
#include <cstring>
#include <limits>
#include <span>
#include <stdexcept>
#include <string>

namespace ibmw::common::util {

inline constexpr size_t BUFFER_BITS_PER_BYTE = 8;

// Store the uin64_t type as little-endian in buf
inline void SetBufFromUint64(char* p, uint64_t n)
{
    for (size_t i = 0; i < sizeof(n); ++i) {
        p[i] = (char)((n >> (i * BUFFER_BITS_PER_BYTE)) & 0xFF);
    }
}

// Retrieve the uin64_t type from buf in little-endian form
inline uint64_t GetUint64FromBuf(const char* p)
{
    uint64_t n = 0;
    for (size_t i = 0; i < sizeof(n); ++i) {
        n += (uint64_t)((uint8_t)(p[i])) << (i * BUFFER_BITS_PER_BYTE);
    }
    return n;
}

// Store the uint32_t type as little-endian in buf
inline void SetBufFromUint32(char* p, uint32_t n)
{
    if constexpr (std::endian::native == std::endian::little) {
        std::copy_n(reinterpret_cast<const char*>(&n), sizeof(n), p);
    } else {
        for (size_t i = 0; i < sizeof(n); ++i) {
            p[i] = (char)((n >> (i * BUFFER_BITS_PER_BYTE)) & 0xFF);
        }
    }
}

// Retrieve the uint32_t type from buf in little-endian form
inline uint32_t GetUint32FromBuf(const char* p)
{
    if constexpr (std::endian::native == std::endian::little) {
        uint32_t n;
        std::copy_n(p, sizeof(n), reinterpret_cast<char*>(&n));
        return n;
    } else {
        uint32_t n = 0;
        for (size_t i = 0; i < sizeof(n); ++i) {
            n += (uint32_t)((uint8_t)(p[i])) << (i * BUFFER_BITS_PER_BYTE);
        }
        return n;
    }
}

// Store the uint16_t type as little-endian in buf
inline void SetBufFromUint16(char* p, uint16_t n)
{
    if constexpr (std::endian::native == std::endian::little) {
        std::copy_n(reinterpret_cast<const char*>(&n), sizeof(n), p);
    } else {
        p[0] = (char)(n & 0xFF);
        p[1] = (char)((n >> BUFFER_BITS_PER_BYTE) & 0xFF);
    }
}

// Retrieve the uint16_t type from buf in little-endian form
inline uint16_t GetUint16FromBuf(const char* p)
{
    if constexpr (std::endian::native == std::endian::little) {
        uint16_t n;
        std::copy_n(p, sizeof(n), reinterpret_cast<char*>(&n));
        return n;
    } else {
        return (uint16_t)((uint8_t)(p[0])) + ((uint16_t)((uint8_t)(p[1])) << BUFFER_BITS_PER_BYTE);
    }
}

enum class BufferLenType : size_t { kUInt8 = 1, kUInt16 = 2, kUInt32 = 4, kUInt64 = 8 };

class BufferOutOfBoundsException : public std::runtime_error {
public:
    BufferOutOfBoundsException() : std::runtime_error("Out of bounds") {}
};

class BufferOperator {
public:
    BufferOperator(char* ptr, size_t len) : start_(ptr), end_(start_ + len), cur_(start_) {}
    ~BufferOperator() = default;

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

    size_t Skip(size_t len)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (len) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        cur_ += len;
        return cur_ - start_;
    }

    void JumpTo(size_t pos)
    {
        if (pos > static_cast<size_t>(end_ - start_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        cur_ = start_ + pos;
    }

    void SetUint8(uint8_t n)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(n)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        *cur_ = n;
        cur_ += sizeof(n);
    }

    void SetUint16(uint16_t n)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(n)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        SetBufFromUint16(cur_, n);
        cur_ += sizeof(n);
    }

    void SetUint32(uint32_t n)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(n)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        SetBufFromUint32(cur_, n);
        cur_ += sizeof(n);
    }

    void SetUint64(uint64_t n)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(n)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        SetBufFromUint64(cur_, n);
        cur_ += sizeof(n);
    }

    void SetBuffer(const char* data, size_t len)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (len) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }

        std::copy_n(data, len, cur_);
        cur_ += len;
    }

    void SetBuffer(std::span<const char> buffer) { SetBuffer(buffer.data(), buffer.size()); }

    void SetString(std::string_view s, BufferLenType lenType = BufferLenType::kUInt64)
    {
        size_t strLen = s.size();
        if (reinterpret_cast<uintptr_t>(cur_) + (static_cast<size_t>(lenType) + strLen) >
            reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }

        switch (lenType) {
            case BufferLenType::kUInt8:
                if (strLen > std::numeric_limits<uint8_t>::max()) [[unlikely]] {
                    throw std::runtime_error("String length out of range.");
                }
                SetUint8(static_cast<uint8_t>(strLen));
                break;
            case BufferLenType::kUInt16:
                if (strLen > std::numeric_limits<uint16_t>::max()) [[unlikely]] {
                    throw std::runtime_error("String length out of range.");
                }
                SetUint16(static_cast<uint16_t>(strLen));
                break;
            case BufferLenType::kUInt32:
                if (strLen > std::numeric_limits<uint32_t>::max()) [[unlikely]] {
                    throw std::runtime_error("String length out of range.");
                }
                SetUint32(static_cast<uint32_t>(strLen));
                break;
            case BufferLenType::kUInt64:
                if (strLen > std::numeric_limits<uint64_t>::max()) [[unlikely]] {
                    throw std::runtime_error("String length out of range.");
                }
                SetUint64(static_cast<uint64_t>(strLen));
                break;
            default:
                throw std::runtime_error("Invalid buffer len type.");
        }

        std::copy_n(s.data(), strLen, cur_);
        cur_ += strLen;
    }

    size_t GetRemainingSize() const { return end_ - cur_; }

private:
    char* start_;
    char* end_;
    char* cur_;
};

class ConstBufferOperator {
public:
    ConstBufferOperator(const char* ptr, size_t len) : start_(ptr), end_(start_ + len), cur_(start_) {}

    ~ConstBufferOperator() = default;

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

    size_t Skip(size_t len)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (len) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        cur_ += len;
        return cur_ - start_;
    }

    void JumpTo(size_t pos)
    {
        if (pos > static_cast<size_t>(end_ - start_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        cur_ = start_ + pos;
    }

    uint8_t GetUint8()
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(uint8_t)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        uint8_t n = *cur_;
        cur_ += sizeof(uint8_t);
        return n;
    }

    uint16_t GetUint16()
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(uint16_t)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        uint16_t n = GetUint16FromBuf(cur_);
        cur_ += sizeof(uint16_t);
        return n;
    }

    uint32_t GetUint32()
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(uint32_t)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        uint32_t n = GetUint32FromBuf(cur_);
        cur_ += sizeof(uint32_t);
        return n;
    }

    uint64_t GetUint64()
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (sizeof(uint64_t)) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        uint64_t n = GetUint64FromBuf(cur_);
        cur_ += sizeof(uint64_t);
        return n;
    }

    std::span<const char> GetBuffer(size_t len)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (len) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        std::span<const char> buffer(cur_, cur_ + len);
        cur_ += len;
        return buffer;
    }

    void GetBuffer(char* dst, size_t len)
    {
        if (reinterpret_cast<uintptr_t>(cur_) + (len) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }
        std::copy_n(cur_, len, dst);
        cur_ += len;
    }

    std::string_view GetString(BufferLenType lenType = BufferLenType::kUInt64)
    {
        size_t strLen = 0;
        switch (lenType) {
            case BufferLenType::kUInt8:
                strLen = GetUint8();
                break;
            case BufferLenType::kUInt16:
                strLen = GetUint16();
                break;
            case BufferLenType::kUInt32:
                strLen = GetUint32();
                // On 32-bit targets a wire u32 can wrap the uintptr bound check below.
                if constexpr (sizeof(uintptr_t) < 8) {
                    if (strLen > GetRemainingSize()) [[unlikely]] {
                        throw BufferOutOfBoundsException();
                    }
                }
                break;
            case BufferLenType::kUInt64:
                strLen = GetUint64();
                // Wire-controlled 64-bit length: reject before `cur_ + str_len` can wrap.
                if (strLen > GetRemainingSize()) [[unlikely]] {
                    throw BufferOutOfBoundsException();
                }
                break;
            default:
                throw std::runtime_error("Invalid buffer len type.");
        }

        if (reinterpret_cast<uintptr_t>(cur_) + (strLen) > reinterpret_cast<uintptr_t>(end_)) [[unlikely]] {
            throw BufferOutOfBoundsException();
        }

        std::string_view s(cur_, strLen);
        cur_ += strLen;
        return s;
    }

    size_t GetRemainingSize() const { return end_ - cur_; }

    std::span<const char> GetRemainingBuffer() { return GetBuffer(GetRemainingSize()); }

private:
    const char* const start_;
    const char* const end_;
    const char* cur_;
};

/// Parse the `[uint32 len][len bytes]` framing written by
/// `BufferOperator::SetUint32(len)` followed by the payload. Returns the
/// payload view, or throws BufferOutOfBoundsException when the buffer is
/// shorter than the prefix or the declared length exceeds the received bytes
/// (the length field comes from the wire and must never be trusted).
inline std::span<const char> GetLengthPrefixedPayload(const char* ptr, size_t len)
{
    ConstBufferOperator prefix(ptr, len);
    const uint32_t payloadLen = prefix.GetUint32();
    // Explicit check (once per message): on 32-bit targets a wire u32 could wrap
    // GetBuffer's uintptr bound check.
    if (payloadLen > prefix.GetRemainingSize()) [[unlikely]] {
        throw BufferOutOfBoundsException();
    }
    return prefix.GetBuffer(payloadLen);
}

} // namespace ibmw::common::util