// fuzz_index_storage.cpp - libFuzzer harness for index storage
// Tests parsing of arbitrary index.bin content

#include <cstdint>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

// Include the storage implementation
#include "../../queue_index/storage/index_storage.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
    // Create a temporary directory
    char tmpdir[] = "/tmp/fuzz_idx_XXXXXX";
    if (!mkdtemp(tmpdir)) {
        return 0;
    }
    
    // Write fuzz data as index.bin
    char path[256];
    snprintf(path, sizeof(path), "%s/index.bin", tmpdir);
    
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
    if (fd < 0) {
        rmdir(tmpdir);
        return 0;
    }
    
    // Write header if data is too small (minimum valid header)
    if (size < 48) {
        // Write a minimal valid header using proper struct
        FileHeader header{};
        memcpy(header.magic, "FQI1", 4);
        header.version = CURRENT_VERSION;
        header.entry_count = 0;
        memset(header.reserved, 0, sizeof(header.reserved));
        memset(header.padding, 0, sizeof(header.padding));
        write(fd, &header, sizeof(header));
        if (size > 0) {
            write(fd, data, size);
        }
    } else {
        write(fd, data, size);
    }
    close(fd);
    
    // Try to open and read the storage
    IndexStorage storage;
    if (storage_init(&storage, tmpdir)) {
        if (storage_open(&storage)) {
            // Try to read entries - this is where vulnerabilities could be triggered
            DiskEntry entries[16];
            size_t count = 0;
            storage_read_entries(&storage, entries, 16, &count);
            storage_close(&storage);
        }
        storage_cleanup(&storage);
    }
    
    // Cleanup
    unlink(path);
    rmdir(tmpdir);
    
    return 0;  // Non-crashing input
}
