// fuzz_file_hash.cpp - libFuzzer harness for file hashing
// Tests hash_file with arbitrary file content

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

// Include the file hash implementation
#include "../../dataset_hash/io/file_hash.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
    // Create a temporary file
    char tmpfile[] = "/tmp/fuzz_hash_XXXXXX";
    int fd = mkstemp(tmpfile);
    if (fd < 0) {
        return 0;
    }
    
    // Write fuzz data
    write(fd, data, size);
    close(fd);
    
    // Try to hash the file
    char hash[65];
    int result = hash_file(tmpfile, 64 * 1024, hash);
    
    // Verify: if success, hash must be 64 hex chars
    if (result == 0) {
        // Check all characters are valid hex
        for (int i = 0; i < 64; i++) {
            char c = hash[i];
            if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
                __builtin_trap();  // Invalid hash format
            }
        }
        // Must be null-terminated at position 64
        if (hash[64] != '\0') {
            __builtin_trap();
        }
    }
    
    // Cleanup
    unlink(tmpfile);
    
    return 0;  // Non-crashing input
}
