#include <maps/wikimap/mapspro/services/mrc/eye/lib/common/include/metadata.h>
#include <maps/wikimap/mapspro/services/mrc/eye/lib/monitoring/include/check.h>

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

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

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

#include <chrono>
#include <iostream>

using namespace maps::mrc;
using namespace maps::mrc::eye;

int main(int argc, char** argv) try {
    maps::log8::setLevel(maps::log8::Level::FATAL);

    maps::cmdline::Parser parser;

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

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

    auto gatewayName = parser.string("gateway")
        .help("queue gateway")
        .required();

    auto metadataName = parser.string("metadata")
        .help("service metadata key");

    auto txnIdKey = parser.string("txn-id-key")
        .help("txn id key in targets.metadata table");

    auto warnN = parser.num("warn")
        .help("warn size")
        .defaultValue(300000);

    auto errorN = parser.num("error")
        .help("error size")
        .defaultValue(1000000);

    parser.parse(argc, argv);

    REQUIRE(metadataName.defined() && !txnIdKey.defined() ||
            !metadataName.defined() && txnIdKey.defined(),
            "Should specified only 'metadata' or 'txn-id-key'");

    const auto config = common::templateConfigFromCmdPath(secretVersion, mrcConfigPath);

    QueueCheckerPtr checker = metadataName.defined() ?
          QueueChecker::byMetadataName(gatewayName, metadataName)
        : QueueChecker::byTxnIdKey(gatewayName, txnIdKey);

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

    std::cout << checker->checkQueueSize(*txn, warnN, errorN) << std::endl;

    return EXIT_SUCCESS;
} catch (const std::exception& e) {
    std::cout << juggler::error(e.what()) << std::endl;
    return EXIT_FAILURE;
} catch (...) {
    std::cout << juggler::error("unknown exception") << std::endl;
    return EXIT_FAILURE;
}
