#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/log8/include/log8.h>
#include <yandex/maps/wiki/common/default_config.h>
#include <yandex/maps/wiki/common/extended_xml_doc.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>
#include <yandex/maps/wiki/revision/common.h>
#include <yandex/maps/wiki/pubsub/commit_consumer.h>

#include <iostream>

using namespace maps;
using namespace maps::wiki;

namespace {

const std::string DB_ID = "long-read";
const std::string POOL_ID = "long-read";
const std::string CONSUMER_ID = "MrcPedestrianTasksGenerator";

constexpr size_t WARN_QUEUE_SIZE {50000};
constexpr size_t ERROR_QUEUE_SIZE {2 * WARN_QUEUE_SIZE};

} // namespace

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

    maps::cmdline::Parser parser;
    auto servicesConfig = parser.file("config").help(
        "path to services configuration file");
    parser.parse(argc, argv);

    auto configPtr = servicesConfig.defined()
        ? std::make_unique<maps::wiki::common::ExtendedXmlDoc>(servicesConfig)
        : maps::wiki::common::loadDefaultConfig();

    wiki::common::PoolHolder pool(*configPtr, DB_ID, POOL_ID);
    auto txn = pool.pool().slaveTransaction();

    auto queueSize = pubsub::countCommitsInQueue(
        *txn,
        *txn,
        CONSUMER_ID,
        revision::TRUNK_BRANCH_ID);

    if (queueSize > ERROR_QUEUE_SIZE) {
        std::cout << "2;Error: queue size is " << queueSize << " commits" << std::endl;
    } else if (queueSize > WARN_QUEUE_SIZE) {
        std::cout << "1;Warning: queue size is " << queueSize << " commits" << std::endl;
    } else {
        std::cout << "0;Ok: queue size is " << queueSize << " commits" << std::endl;
    }
    return EXIT_SUCCESS;
} catch (const std::exception& e) {
    std::cout << "2;Error: " << e.what() << std::endl;
    return EXIT_SUCCESS;
}
