#pragma once

#include "bundle_model.h"
#include <robot/jupiter/library/rtdoc/rt/reader.h>
#include <saas/rtyserver_jupi/library/textwad/wad_keyinv_merge.h>
#include <util/folder/path.h>

namespace NFusion {
    class TKeyInvWad : public ICmdExtensions {
    public:
        TString OutputPrefix;
        bool LegacyWrangleMode = false;
    public:
        virtual void Init(TJupiterCmd& cmd, const TBundleVersion& bundleVer) override {
            OutputPrefix = cmd.OutputPrefix;
            LegacyWrangleMode = bundleVer.GetGlobalNo() < 20; //TODO(yrum): do REFRESH-319 and remove the magical constant
            Y_ENSURE(!OutputPrefix.empty());
        }

        virtual NRtDoc::IWadMerger::TPtr CreateWadCustomMerger() override {
            auto wadMerger = CreateTextWadMerger();
            wadMerger->MutableMeta()->DeltaMode = !LegacyWrangleMode;
            return wadMerger;
        }

        virtual void PreprocessInputs(const NRtDoc::IBuilderInputs& inputs) override {
            if (LegacyWrangleMode) {
                PreprocessLegacyInputs(inputs);
                return;
            }
        }

    private:
        void PreprocessLegacyInputs(const NRtDoc::IBuilderInputs& inputs) {
            // This is a legacy mode for switching from Oxygen
            for(size_t i = 0; i < inputs.InputsSize(); ++i) {
                auto input = inputs.GetInputs(i);
                TFsPath srcDir(input.GetSrcDir());

                bool shouldConvert = !input.GetIsFinalIndex() || !(srcDir / (OutputPrefix + ".wad")).Exists();
                const TString oldKeyInvPrefix = "indexold";
                if (shouldConvert && (srcDir / (oldKeyInvPrefix + "key")).Exists() && (srcDir / (oldKeyInvPrefix + "inv")).Exists()) {
                    Wrangle(srcDir / oldKeyInvPrefix, srcDir / OutputPrefix);
                }
            }
        }

        void Wrangle(const TString& oldPrefix, const TString& newPrefix);
    };
}
