#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/wikimap/mapspro/services/mrc/eye/lib/sync_detection/impl/sync.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>

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

using namespace maps;
using namespace maps::mrc;

static const size_t BATCH_SIZE = 10000;

int main(int argc, const char** argv) try {
    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 txnId = parser.num("txn-d")
            .required()
            .help("max txn id");

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

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

    db::TIds emptyRecognitionIds;

    {
        auto filter = db::eye::table::Recognition::txnId <= txnId;
        sql_chemistry::BatchLoad<db::eye::table::Recognition> batch(BATCH_SIZE, filter);

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

        INFO() << "Loading recognitions";
        while (batch.next(*txn)) {
            INFO() << "recognitions: " << emptyRecognitionIds.size();

            for (const auto& recognition : batch) {
                if (recognition.empty() && eye::mayBeRemoved(recognition.source())) {
                    emptyRecognitionIds.push_back(recognition.id());
                }
            }
        }
    }


    for (const auto& batch : maps::common::makeBatches(emptyRecognitionIds, BATCH_SIZE)) {
        db::TIds recognitionIds{batch.begin(), batch.end()};

        auto txn = pool.pool().masterWriteableTransaction();
        db::eye::RecognitionGateway(*txn).removeByIds(recognitionIds);
        txn->commit();
    }

    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!";
}
