#include "common.h"

#include <library/cpp/logger/global/global.h>

#include <util/generic/set.h>

NKiwi::TKiwiObject GetKiwiObject(const TString& data, const TKiwiObjectAcquireOptions& options) {
    NKiwi::TKiwiObject source(data);
    if (!options.MergeTimestamps) {
        return source;
    }

    NKiwi::TKiwiObject result;
    VERIFY_WITH_LOG(options.TimestampSuffix, "Timestamp suffix cannot be empty");

    TSet<TString> skipped;
    for (auto i = source.GetIterator(); i.IsValid(); i.Advance()) {
        auto tuple = i.Current();
        Y_VERIFY(tuple);

        NKiwi::NTuples::TTupleInfo info;
        if (!info.Parse(tuple->InfoPtr(), tuple->InfoSize())) {
            ythrow yexception() << "cannot parse tuple info for attrId" << tuple->GetId();
        }

        const TString& lable = info.GetLabel();
        const TString& timestampLable = lable + options.TimestampSuffix;

        if (skipped.contains(lable)) {
            continue;
        }

        ui32 timestamp = 0;
        if (HasTuple(source, timestampLable)) {
            timestamp = GetTuple<ui32>(source, timestampLable);
            skipped.insert(timestampLable);
        } else {
            timestamp = tuple->GetTag();
        }

        TStringBuf data(static_cast<const char*>(tuple->GetData()), tuple->GetSize());
        result.Add(tuple->GetId(), tuple->GetVer(), timestamp, data, info.GetProto());
    }

    return result;
}
