#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/yt_worker.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/yt_spec.h>

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

#include <maps/wikimap/mapspro/services/mrc/libs/yt/include/schema.h>

#include <maps/wikimap/mapspro/services/mrc/libs/db/include/eye/recognition_gateway.h>

namespace maps::mrc::eye {

namespace {

// Возвращает количество строк в таблице
size_t getRowsCount(
    const NYT::ITransactionPtr ytTxn,
    const TString& input)
{
    return ytTxn->Get(input + "/@row_count").AsInt64();
}

} // namespace

void runRoadMarkingDetection(
    NYT::ITransactionPtr ytTxn,
    const YtWorkerConfig& ytConfig,
    const TString& input,
    const TString& output)
{
    const size_t framesCount = getRowsCount(ytTxn, input);

    REQUIRE(SecureConfig::isInitialized(), "Secure config was not initialized");

    ytTxn->Map(
        NYT::TMapOperationSpec()
            .AddInput<NYT::TNode>(input)
            .AddOutput<NYT::TNode>(
                NYT::TRichYPath(output)
                    .Schema(yt::getSchemaOf<db::eye::Recognition>())
            )
            .JobCount(std::max(framesCount / ytConfig.partitionSize, 1ul)),
        new DetectRoadMarkingWorker(*(ytConfig.frameLoader)),
        NYT::TOperationOptions()
            .Spec(makeDetectWorkerSpec(ytConfig))
            .SecureVault(SecureConfig::instance())
    );
}

} // namespace maps::mrc::eye
