#include <maps/libs/chrono/include/time_point.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/pgpool/include/pgpool3.h>
#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>
#include <maps/wikimap/mapspro/services/mrc/libs/db/include/metadata_gateway.h>
#include <maps/wikimap/mapspro/services/mrc/long_tasks/user_activity_stat/lib/tools.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>

#include <cstdint>

using namespace maps::mrc::user_activity_stat;

namespace {

const std::chrono::hours WARN_HOURS{24};
const std::chrono::hours ERROR_HOURS{72};

}  // namespace

int main()
try {
    maps::log8::setLevel(maps::log8::Level::FATAL);

    auto cfg = maps::mrc::common::templateConfig();
    auto pool = cfg.makePoolHolder(maps::mrc::common::LONG_READ_DB_ID,
                                   maps::mrc::common::LONG_READ_POOL_ID);
    auto txn = pool.pool().slaveTransaction();

    auto lastRunTime =
        maps::mrc::db::MetadataGateway{*txn}.tryLoadByKey(LAST_RUN_TIME);
    if (!lastRunTime) {
        std::cout << "1;Warning: " << APP_NAME << " has never run" << std::endl;
        return EXIT_SUCCESS;
    }

    const auto lag = std::chrono::duration_cast<std::chrono::hours>(
        maps::chrono::TimePoint::clock::now() -
        maps::chrono::parseSqlDateTime(*lastRunTime));

    if (lag > ERROR_HOURS) {
        std::cout << "2;Error: ";
    }
    else if (lag > WARN_HOURS) {
        std::cout << "1;Warning: ";
    }
    else {
        std::cout << "0;Ok: ";
    }
    std::cout << APP_NAME << " ran " << lag.count() << " hours ago."
              << std::endl;
    return EXIT_SUCCESS;
}
catch (const std::exception& e) {
    std::cout << "2;Error: " << e.what() << std::endl;
    return EXIT_SUCCESS;
}
