// guid_diff implementation — pure set arithmetic for new-content detection. See
// guid_diff.h. No REAPER, no SWELL — std only.

#include "guid_diff.h"

#include <algorithm>

namespace reasampler {

std::vector<std::string> newGuids(const std::set<std::string>& previous,
                                  const std::set<std::string>& current) {
    std::vector<std::string> added;
    // current \ previous. std::set iterates ascending, so set_difference yields a
    // deterministic order without a separate sort.
    for (const std::string& g : current) {
        if (g.empty()) continue;             // never tag a GUID-read failure
        if (previous.count(g) == 0) added.push_back(g);
    }
    return added;
}

std::vector<std::string> GuidBaseline::observe(const std::set<std::string>& current) {
    if (!primed_) {
        // First poll after open/reset: establish the baseline, report nothing new so
        // pre-existing content is NOT auto-tagged (it defaults to Arrange).
        baseline_ = current;
        primed_ = true;
        return {};
    }
    std::vector<std::string> added = newGuids(baseline_, current);
    // Advance the baseline to the full current set. Using `current` (not baseline_ ∪
    // added) means a DELETED GUID drops out of the baseline too, so if REAPER later
    // reuses that GUID for genuinely new content it is detected again — the baseline
    // tracks the live set exactly, not a monotonic union.
    baseline_ = current;
    return added;
}

void GuidBaseline::reset() {
    baseline_.clear();
    primed_ = false;  // next observe() re-baselines (first-poll guard re-armed)
}

}  // namespace reasampler
