#include "optimized_parallel_walker.h"
#include "tree.h"
#include <algorithm>
#include <cstring>

namespace cutysoup {

OptimizedParallelWalker::OptimizedParallelWalker(const Config& config) 
    : config_(config) {
}

OptimizedParallelWalker::~OptimizedParallelWalker() {
    // Simple destructor - no complex cleanup needed
}

std::shared_ptr<Node> OptimizedParallelWalker::create_node(GumboNode* gumbo_node, const Tree* tree) const {
    if (!gumbo_node || !tree) return nullptr;
    return tree->get_or_create_node(gumbo_node);
}

// Specialized searches with reduced overhead

std::vector<std::shared_ptr<Node>> OptimizedParallelWalker::find_by_tag_parallel(
    GumboNode* root,
    const Tree* tree,
    const std::string& tag_name,
    const Config& config
) {
    // Convert tag name to Gumbo tag enum for faster comparison
    GumboTag target_tag = gumbo_tag_enum(tag_name.c_str());
    
    // Optimized predicate with early enum comparison
    auto predicate = [target_tag, &tag_name](GumboNode* node) -> bool {
        if (!node || node->type != GUMBO_NODE_ELEMENT) {
            return false;
        }
        
        // Fast comparison using enum if possible
        if (target_tag != GUMBO_TAG_UNKNOWN) {
            return node->v.element.tag == target_tag;
        }
        
        // Fallback to string comparison for custom tags
        const char* node_name = gumbo_normalized_tagname(node->v.element.tag);
        return node_name && tag_name == node_name;
    };
    
    // Use the optimized parallel implementation
    return parallel_find_all(root, tree, predicate, config);
}

} // namespace cutysoup
