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

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

#include <maps/libs/common/include/exception.h>

#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/sql_chemistry/include/batch_load.h>

using namespace maps;
using namespace maps::mrc;

int main(int argc, const char** argv) try {
    NYT::Initialize(argc, argv);

    maps::cmdline::Parser parser;

    auto secretVersion = parser.string("secret-version")
            .help("version for secrets from yav.yandex-team.ru");

    auto mrcConfigPath = parser.string("mrc-config")
            .required()
            .help("path to mrc config");

    auto ytTablePath = parser.string("yt-table")
            .required()
            .help("path to yt table");

    parser.parse(argc, const_cast<char**>(argv));

    NYT::IClientPtr client = NYT::CreateClient("hahn");

    const auto config = mrc::common::templateConfigFromCmdPath(secretVersion, mrcConfigPath);
    auto pool = config.makePoolHolder();

    auto writer = client->CreateTableWriter<NYT::TNode>(TString(ytTablePath));

    const size_t BATCH_SIZE = 10000;
    sql_chemistry::BatchLoad<db::eye::table::Recognition> batch(BATCH_SIZE);

    auto txn = pool.pool().slaveTransaction();

    INFO() << "Saving recognitions";
    size_t batchIndx = 0;
    while (batch.next(*txn)) {
        batchIndx++;
        INFO() << "Batch indx: " << batchIndx;

        for (const auto& recognition : batch) {
            writer->AddRow(yt::serialize<db::eye::Recognition>(recognition));
        }
    }

    writer->Finish();

    return EXIT_SUCCESS;
} catch (const maps::Exception& ex) {
    FATAL() << "Failed: " << ex;
    return EXIT_FAILURE;
} catch (const std::exception& ex) {
    FATAL() << "Failed: " << ex.what();
    return EXIT_FAILURE;
} catch (...) {
    FATAL() << "Unknown error!";
}
