#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/eye/lib/import_yt_panorama/include/constants.h>

#include <maps/libs/log8/include/log8.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>
#include <maps/libs/chrono/include/days.h>

namespace {

const maps::chrono::Days WARN_DAYS{3};
const maps::chrono::Days ERROR_DAYS{7};

} // namespace

int main(int /*argc*/, char** /*argv*/) try {
    using namespace maps::mrc;

    maps::log8::setLevel(maps::log8::Level::FATAL);

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

    auto lastRunTime = db::MetadataGateway{*txn}.tryLoadByKey(
        eye::DB_YT_PANORAMA_DATASET_UPDATED_AT_METADATA_KEY);
    if (!lastRunTime) {
        std::cout << "2;Error: Panoramas import has never run" << std::endl;
        return EXIT_SUCCESS;
    }

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

    if (lag > ERROR_DAYS) {
        std::cout << "2;Error: ";
    } else if (lag > WARN_DAYS) {
        std::cout << "1;Warning: ";
    } else {
        std::cout << "0;Ok: ";
    }
    std::cout << "Panoramas importer last update was " << lag.count()
              << " days ago." << std::endl;
    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;
}
