#include "extbuilder_app.h"

#include "dbg_helper.h"
#include "extbuilder_config.h"

#include <saas/rtyserver_jupi/library/extbuilder/module.h>

#include <kernel/index_mapping/index_mapping.h>

#include <library/cpp/mediator/global_notifications/system_status.h>

#include <util/datetime/base.h>
#include <util/system/file.h>

namespace NFusion {
    class TExtBuilderApp::TImpl {
    public:
        TImpl(const TString& staticFilesDir)
            : StaticFilesDir(staticFilesDir)
        {
            if (StaticFilesDir.IsDefined()) {
                StaticFilesDir.Fix();
                Y_ENSURE(StaticFilesDir.IsDirectory() || StaticFilesDir.IsSymlink());
            }
        }

        ~TImpl() = default;

    private:
        TFsPath StaticFilesDir;

    public:
        void Prefetch() {
            if (!StaticFilesDir.IsDefined()) {
                return;
            }
            TIndexPrefetchOptions ipo;
            ipo.TryLock = true;
            ipo.Deadline = TDuration::Minutes(1).ToDeadLine();

            const TFsPath nnModelsPanther = StaticFilesDir / "panther_dwelltime_dssm_model.nn_applier";
            if (nnModelsPanther.Exists()) {
                PrefetchMappedIndex(nnModelsPanther, ipo);
            }
        }

        void ReleaseMappings() {
            if (StaticFilesDir.IsDefined()) {
                ReleaseMappedIndexFilesInDir(StaticFilesDir);
            }
        }

    };

    TExtBuilderApp::TExtBuilderApp(const TExtBuilderConfig& serverConfig, IExtBuilderTrace::TPtr helper)
        : Impl(MakeHolder<TImpl>(serverConfig.GetModelsPath()))
        , ExtConfig(serverConfig)
        , DiagHelper(helper)
    {
        Y_VERIFY(DiagHelper);
    }

    TExtBuilderApp::~TExtBuilderApp() {
    }

    void TExtBuilderApp::Start() {
        Impl->Prefetch();
        DiagHelper->OnAppStart(ExtConfig.GetStatePath(), ExtConfig.CreateAssertPolicy());
    }

    void TExtBuilderApp::Stop() {
        Impl->ReleaseMappings();
    }
}
