#include <maps/libs/log8/include/log8.h>
#include <maps/wikimap/mapspro/services/mrc/libs/common/include/ecstatic_client.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/export_gen/lib/tools.h>
#include <maps/libs/common/include/exception.h>

#include <cstdint>
#include <iostream>
#include <sstream>

namespace {

const std::chrono::hours WARN_HOURS{30};
const std::chrono::hours ERROR_HOURS{60};

} // namespace

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

    auto cfg = maps::mrc::common::templateConfig();
    auto ecstaticClient = maps::mrc::common::EcstaticClient(
            maps::mrc::common::EcstaticClient::ECSTATIC_PATH,
            cfg.externals().ecstaticEnvironmentOverride());

    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(
        maps::mrc::export_gen::LAST_RUN_TIME);
    auto lag = std::optional<std::chrono::hours>{};
    if (lastRunTime) {
        lag = std::chrono::duration_cast<std::chrono::hours>(
            maps::chrono::TimePoint::clock::now() -
            maps::chrono::parseSqlDateTime(*lastRunTime));
    }

    if (lag && lag > ERROR_HOURS) {
        std::cout << "2;Error: ";
    } else if (!lag || lag > WARN_HOURS) {
        std::cout << "1;Warning: ";
    } else {
        std::cout << "0;Ok: ";
    }
    if (lag) {
        std::cout << " ran " << lag->count() << " hours ago";
    }
    else {
        std::cout << " has never run";
    }
    std::cout << "\n";
    return EXIT_SUCCESS;
}
catch (const std::exception& e) {
    std::cout << "2;Error: " << e.what() << std::endl;
    return EXIT_SUCCESS;
}
catch (...) {
    std::cout << "2;Error: unknown exception" << std::endl;
    return EXIT_SUCCESS;
}
