#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/process.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/serialize.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/yt_spec.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/detect_road_marking/impl/yt_exec.h>
#include <maps/wikimap/mapspro/services/mrc/libs/yt/include/io.h>

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

namespace maps::mrc::eye {

db::eye::Recognitions process(
    const eye::YtWorkerConfig& ytConfig,
    db::IdTo<db::eye::Frame> frameById,
    const db::IdTo<db::eye::Recognition>& panelByFrameId)
{
    NYT::ITransactionPtr ytTxn = ytConfig.client->StartTransaction();
    const TString root(ytConfig.rootPath);
    if (!ytTxn->Exists(root)) {
        INFO() << "Create node " << root;
        ytTxn->Create(root, NYT::NT_MAP, NYT::TCreateOptions().Recursive(true));
    }

    const TString input = root + "/frame";
    const TString output = root + "/recognition";

    INFO() << "Save to table " << input;
    writeFrames(ytTxn, input, frameById, panelByFrameId);

    INFO() << "Run detection";
    runRoadMarkingDetection(ytTxn, ytConfig, input, output);

    INFO() << "Load table " << output;
    db::eye::Recognitions recognitions
        = yt::loadFromTable<db::eye::Recognitions>(*ytTxn, output);

    if (ytConfig.commit) {
        INFO() << "Yt commited!";
        ytTxn->Commit();
    }

    return recognitions;
}

} // namespace maps::mrc::eye
