#include "interface.h"
#include "merger.h"

#include <search/panther/custom/v0_1/panther_v0_1.h>
#include <search/panther/indexing/counts_to_panther/operations.h>
#include <search/panther/indexing/counts_to_panther/processor_v0_1.h>

#include <kernel/walrus/advmerger.h>

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

#include <util/folder/path.h>

namespace {
    class TWebV0_1Panther : public NRTYServer::IPantherImplementation {
    public:
        void ConvertCountsToPanther(const TString& countsPrefix, const TString& pantherPrefix, const NPanther::TCountsToPantherOptions& options) const override {
            CHECK_WITH_LOG(options.Version == NPanther::PantherV0_1);
            NPanther::TPantherV0_1::TFormula formula;
            NPanther::CountsToPanther(options, countsPrefix, pantherPrefix, &formula);
        }
        bool MergeCountsAndPanther(
            TSimpleSharedPtr<TAdvancedMergeTask> task,
            const TRTYMergerContextBase& mergeCtx,
            const NPanther::TCountsToPantherOptions& options,
            const THashSet<TString>& frequentKeys = Default<THashSet<TString>>(),
            const std::atomic<bool>* stop = nullptr
        ) override {
            Y_UNUSED(mergeCtx);
            CHECK_WITH_LOG(options.Version == NPanther::PantherV0_1);
            if (task->Outputs.size() == 1 && options.UseYndexPanther) {
                const TFsPath root = TFsPath(task->Outputs[0].FilePrefix).Parent();

                using TFormula = NPanther::TPantherV0_1::TFormula;
                using TTermProcessor = NPanther::TCountsToPantherProcessorV0_1<TFormula>;
                TFormula formula;
                TTermProcessor termProcessor(options, frequentKeys, &formula);
                NRTYServer::TPantherHitsProcessor<TTermProcessor> processor(root / "indexpanther.", termProcessor, options);

                TAdvancedIndexMerger merger(task, stop);
                return merger.Run(processor);
            } else {
                return NRTYServer::IPantherImplementation::MergeCountsAndPanther(task, mergeCtx, options, frequentKeys, stop);
            }
        }
    };
}

NRTYServer::IPantherImplementation::TFactory::TRegistrator<TWebV0_1Panther> WebV0_1(NPanther::PantherV0_1);
