#include "assistant.h"

bool random_file(const std::string& file, size_t size)
{
    if (file.empty() || size == 0) {
        return false;
    }

    std::ofstream ofs(file, std::ios::binary | std::ios::trunc);
    if (!ofs) {
        return false;
    }

    std::random_device rd;
    std::mt19937_64 gen(rd());
    std::uniform_int_distribution<int> dis(0, 255);

    const size_t buffer_size = 4096;
    std::vector<unsigned char> buffer(buffer_size);

    for (size_t remaining = size; remaining > 0;) {
        size_t chunk = std::min(remaining, buffer_size);

        for (size_t i = 0; i < chunk; ++i) {
            buffer[i] = static_cast<unsigned char>(dis(gen));
        }
        if (!ofs.write(reinterpret_cast<const char*>(buffer.data()), chunk)) {
            return false;
        }
        remaining -= chunk;
    }
    return true;
}

/**
 * @brief 比较两个文件的内容是否完全相同
 *
 * @param filea 第一个文件路径
 * @param fileb 第二个文件路径
 * @return true 如果文件内容完全相同
 * @return false 如果文件内容不同或无法读取文件
 */
bool is_equal_filecontent(const std::string& filea, const std::string& fileb)
{
    std::ifstream stream_a(filea, std::ios::binary);
    std::ifstream stream_b(fileb, std::ios::binary);

    if (!stream_a.is_open() || !stream_b.is_open()) {
        return false;
    }

    auto size_a = fs::file_size(filea);
    auto size_b = fs::file_size(fileb);
    if (size_a != size_b) {
        return false;
    }

    const size_t buffer_size = 4096;   // 4KB 缓冲区
    char buffer_a[buffer_size];
    char buffer_b[buffer_size];

    while (stream_a.good() && stream_b.good()) {

        stream_a.read(buffer_a, buffer_size);
        stream_b.read(buffer_b, buffer_size);

        if (stream_a.gcount() != stream_b.gcount()) {
            return false;
        }

        if (!std::equal(buffer_a, buffer_a + stream_a.gcount(), buffer_b)) {
            return false;
        }
    }

    return !stream_a.bad() && !stream_b.bad();
}