#include "core/file_poll_diff.h"

#include <unordered_map>
#include <unordered_set>

namespace fn_ui {

FileDiff file_poll_diff(const std::vector<FileEntry>& before,
                        const std::vector<FileEntry>& after) {
    FileDiff out;

    // Index before by path para lookup O(1).
    std::unordered_map<std::string, const FileEntry*> idx_before;
    idx_before.reserve(before.size());
    for (const auto& e : before) {
        idx_before[e.path] = &e;
    }

    // Recorrer after: clasificar added/modified.
    std::unordered_set<std::string> seen_in_after;
    seen_in_after.reserve(after.size());
    for (const auto& e : after) {
        seen_in_after.insert(e.path);
        auto it = idx_before.find(e.path);
        if (it == idx_before.end()) {
            out.added.push_back(e.path);
        } else {
            const FileEntry* prev = it->second;
            if (prev->size != e.size || prev->mtime != e.mtime) {
                out.modified.push_back(e.path);
            }
        }
    }

    // Recorrer before: detectar removed (paths que no estan en after).
    for (const auto& e : before) {
        if (seen_in_after.find(e.path) == seen_in_after.end()) {
            out.removed.push_back(e.path);
        }
    }

    return out;
}

} // namespace fn_ui
