// Copyright (c) 2026 Lux Industries Inc.
// SPDX-License-Identifier: Apache-2.0
//
// test_wire.cpp -- unit tests for the Layer A wire codec: Reader,
// Writer, read_frame, write_frame_locked, oversize/malformed rejection,
// and the flag-bit accessors.

#include <gtest/gtest.h>

#include <lux/zap/wire.hpp>

#include <array>
#include <cstring>
#include <mutex>
#include <thread>
#include <vector>

#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>

using namespace lux::zap;

namespace
{

// Helper: socketpair for in-process framing tests. Returns {read_fd, write_fd}.
struct FdPair { int rd; int wr; };
FdPair make_socketpair()
{
    int sv[2];
    EXPECT_EQ(0, ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv));
    return {sv[0], sv[1]};
}

}  // namespace

// ---------------------------------------------------------------------------
// Reader / Writer round-trip
// ---------------------------------------------------------------------------

TEST(Wire, WriterReaderRoundTripPrimitives)
{
    Writer w;
    w.write_u8(0x41);
    w.write_bool(true);
    w.write_bool(false);
    w.write_u32(0xDEADBEEF);
    w.write_u64(0x0123456789ABCDEFull);
    w.write_i64(-42);

    Reader r(w.data(), w.size());

    uint8_t b8;
    bool b1, b0;
    uint32_t v32;
    uint64_t v64;
    int64_t i64;

    ASSERT_TRUE(r.read_u8(b8));   EXPECT_EQ(0x41, b8);
    ASSERT_TRUE(r.read_bool(b1)); EXPECT_TRUE(b1);
    ASSERT_TRUE(r.read_bool(b0)); EXPECT_FALSE(b0);
    ASSERT_TRUE(r.read_u32(v32)); EXPECT_EQ(0xDEADBEEFu, v32);
    ASSERT_TRUE(r.read_u64(v64)); EXPECT_EQ(0x0123456789ABCDEFull, v64);
    ASSERT_TRUE(r.read_i64(i64)); EXPECT_EQ(-42, i64);
    EXPECT_EQ(0u, r.remaining());
}

TEST(Wire, WriterReaderRoundTripBytes)
{
    Writer w;
    std::vector<uint8_t> body{0xCA, 0xFE, 0xBA, 0xBE};
    w.write_bytes(body);
    w.write_string("hello world");
    w.write_bytes(nullptr, 0);  // empty length-prefixed bytes

    Reader r(w.data(), w.size());

    std::vector<uint8_t> rb;
    std::string rs;
    std::vector<uint8_t> empty;

    ASSERT_TRUE(r.read_bytes(rb));  EXPECT_EQ(body, rb);
    ASSERT_TRUE(r.read_string(rs)); EXPECT_EQ("hello world", rs);
    ASSERT_TRUE(r.read_bytes(empty)); EXPECT_TRUE(empty.empty());
    EXPECT_EQ(0u, r.remaining());
}

TEST(Wire, ReaderShortReadReturnsFalse)
{
    std::array<uint8_t, 3> buf{0x00, 0x00, 0x00};
    Reader r(buf.data(), buf.size());

    uint32_t v;
    EXPECT_FALSE(r.read_u32(v));  // need 4 bytes, have 3

    uint64_t w;
    EXPECT_FALSE(r.read_u64(w));  // need 8 bytes
}

TEST(Wire, ReaderTruncatedBytesReturnsFalse)
{
    Writer w;
    w.write_u32(100);  // claims 100 bytes follow, but writes none
    Reader r(w.data(), w.size());

    std::vector<uint8_t> out;
    EXPECT_FALSE(r.read_bytes(out));
}

// ---------------------------------------------------------------------------
// Flag-bit helpers
// ---------------------------------------------------------------------------

TEST(Wire, FlagHelpers)
{
    EXPECT_FALSE(is_response(0x05));
    EXPECT_FALSE(is_error(0x05));
    EXPECT_EQ(0x05, strip_flags(0x05));

    EXPECT_TRUE(is_response(0x05 | MsgResponseFlag));
    EXPECT_FALSE(is_error(0x05 | MsgResponseFlag));
    EXPECT_EQ(0x05, strip_flags(0x05 | MsgResponseFlag));

    EXPECT_TRUE(is_response(0x05 | MsgResponseFlag | MsgErrorFlag));
    EXPECT_TRUE(is_error(0x05 | MsgResponseFlag | MsgErrorFlag));
    EXPECT_EQ(0x05, strip_flags(0x05 | MsgResponseFlag | MsgErrorFlag));

    // Edge: flag bits without a base type still strip cleanly to 0.
    EXPECT_EQ(0, strip_flags(MsgResponseFlag | MsgErrorFlag));
}

// ---------------------------------------------------------------------------
// Frame I/O round-trip
// ---------------------------------------------------------------------------

TEST(Wire, FrameRoundTripSmall)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;

    std::mutex wmu;
    std::vector<uint8_t> body{0x01, 0x02, 0x03, 0x04, 0x05};
    ASSERT_TRUE(write_frame_locked(wr, wmu, 0x42, body.data(), body.size()));

    uint8_t mt;
    std::vector<uint8_t> out;
    ASSERT_TRUE(read_frame(rd, mt, out));
    EXPECT_EQ(0x42, mt);
    EXPECT_EQ(body, out);

    ::close(rd);
    ::close(wr);
}

TEST(Wire, FrameRoundTripEmpty)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;

    std::mutex wmu;
    ASSERT_TRUE(write_frame_locked(wr, wmu, 0xFF, nullptr, 0));

    uint8_t mt;
    std::vector<uint8_t> out;
    ASSERT_TRUE(read_frame(rd, mt, out));
    EXPECT_EQ(0xFF, mt);
    EXPECT_TRUE(out.empty());

    ::close(rd);
    ::close(wr);
}

TEST(Wire, FrameRoundTripLarge)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;

    std::vector<uint8_t> body(64 * 1024);
    for (std::size_t i = 0; i < body.size(); ++i)
        body[i] = static_cast<uint8_t>(i & 0xFF);

    std::mutex wmu;
    std::thread writer([&]() {
        ASSERT_TRUE(write_frame_locked(wr, wmu, 0x10, body.data(), body.size()));
    });

    uint8_t mt;
    std::vector<uint8_t> out;
    ASSERT_TRUE(read_frame(rd, mt, out));
    EXPECT_EQ(0x10, mt);
    ASSERT_EQ(body.size(), out.size());
    EXPECT_EQ(0, std::memcmp(body.data(), out.data(), body.size()));

    writer.join();
    ::close(rd);
    ::close(wr);
}

// ---------------------------------------------------------------------------
// Malformed / oversize rejection
// ---------------------------------------------------------------------------

TEST(Wire, OversizeFrameRejected)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;

    // Hand-craft an oversize header: length = MaxMessageSize + 1.
    uint32_t bogus_len = MaxMessageSize + 1;
    uint8_t header[HeaderSize];
    header[0] = static_cast<uint8_t>(bogus_len >> 24);
    header[1] = static_cast<uint8_t>(bogus_len >> 16);
    header[2] = static_cast<uint8_t>(bogus_len >> 8);
    header[3] = static_cast<uint8_t>(bogus_len);
    header[4] = 0x05;
    ASSERT_EQ(static_cast<ssize_t>(HeaderSize),
              ::write(wr, header, HeaderSize));

    uint8_t mt;
    std::vector<uint8_t> out;
    EXPECT_FALSE(read_frame(rd, mt, out));

    ::close(rd);
    ::close(wr);
}

TEST(Wire, FrameReadEofReturnsFalse)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;
    ::close(wr);

    uint8_t mt;
    std::vector<uint8_t> out;
    EXPECT_FALSE(read_frame(rd, mt, out));

    ::close(rd);
}

// ---------------------------------------------------------------------------
// write_frame_locked is actually mutex-serialized
// ---------------------------------------------------------------------------

TEST(Wire, WriteFrameMutexSerializesConcurrentWriters)
{
    auto p = make_socketpair();
    int rd = p.rd, wr = p.wr;

    std::mutex wmu;
    constexpr int kFramesPerThread = 200;
    constexpr int kThreads = 8;

    auto writer_fn = [&](uint8_t tag) {
        std::vector<uint8_t> body(64, tag);
        for (int i = 0; i < kFramesPerThread; ++i)
        {
            ASSERT_TRUE(write_frame_locked(wr, wmu, tag, body.data(), body.size()));
        }
    };

    std::vector<std::thread> writers;
    writers.reserve(kThreads);
    for (int t = 0; t < kThreads; ++t)
    {
        writers.emplace_back(writer_fn, static_cast<uint8_t>(t + 1));
    }

    int total = 0;
    for (int t = 0; t < kThreads * kFramesPerThread; ++t)
    {
        uint8_t mt;
        std::vector<uint8_t> out;
        ASSERT_TRUE(read_frame(rd, mt, out));
        // Every byte in the body must equal the type byte -- proves no
        // interleaving occurred between concurrent writers.
        ASSERT_EQ(64u, out.size());
        for (uint8_t b : out) ASSERT_EQ(mt, b);
        ++total;
    }
    EXPECT_EQ(kThreads * kFramesPerThread, total);

    for (auto& w : writers) w.join();
    ::close(rd);
    ::close(wr);
}