#include <maps/wikimap/mapspro/services/mrc/eye/lib/common/include/secure_config.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/common/include/tvm_client.h>

#include <maps/libs/log8/include/log8.h>

#include <util/system/fs.h>

namespace maps::mrc::eye {
namespace {

const char* TVM_CACHE_DIRECTORY = "/var/cache/yandex/maps/mrc/eye/tvm-cache";

std::optional<NTvmAuth::TTvmClient> makeTvmClient()
{
    // The following line will lead to exception on YT nodes.
    // REQUIRE(SecureConfig::isInitialized(), "Secure config was not initialized");

    const auto& eyeTvmConfig =
        SecureConfig::instance().mrcConfig().externals().eyeTvmConfig();

    if (!eyeTvmConfig.tvmSecret()) {
        // Do not use TVM if the secret is not defined.
        return std::nullopt;
    }

    class TvmLogger : public NTvmAuth::ILogger {
    public:
        void Log(int lvl, const TString& msg) override
        {
            MAPS_LOG(static_cast<log8::Level>(lvl))
                << "tvm ticket parser: " << msg;
        }
    };

    NTvmAuth::TLoggerPtr logger = MakeIntrusive<TvmLogger>();
    NTvmAuth::NTvmApi::TClientSettings settings;

    settings.SetSelfTvmId(eyeTvmConfig.selfTvmServiceId());
    settings.EnableServiceTicketChecking();
    settings.EnableServiceTicketsFetchOptions(
        TString(*eyeTvmConfig.tvmSecret()),
        {{PANORAMA_DESCRIPTION_SERVICE_ALIAS,
          eyeTvmConfig.panoramaDesciptionTvmServiceId()}});

    if (NFs::Exists(TVM_CACHE_DIRECTORY) ||
        NFs::MakeDirectoryRecursive(TVM_CACHE_DIRECTORY)) {
        settings.SetDiskCacheDir(TVM_CACHE_DIRECTORY);
    }

    return NTvmAuth::TTvmClient{settings, logger};
}

} // namespace

const std::optional<NTvmAuth::TTvmClient>& tvmClient()
{
    static std::optional<NTvmAuth::TTvmClient> client{makeTvmClient()};
    return client;
}

} // namespace maps::mrc::eye
