#include <maps/wikimap/mapspro/services/social/src/libs/yacare/error.h>
#include <maps/wikimap/mapspro/services/social/src/api/globals.h>
#include <maps/wikimap/mapspro/libs/sqs_client/include/aws_api.h>

#include <yandex/maps/wiki/common/extended_xml_doc.h>

#include <maps/libs/log8/include/log8.h>
#include <maps/infra/yacare/include/yacare.h>

#include <string>

namespace {

const std::string DEFAULT_CFG_PATH =
    "/etc/yandex/maps/wiki/services/services.xml";

maps::log8::Level logLevel(const maps::wiki::common::ExtendedXmlDoc& cfg)
{
    return cfg.get<maps::log8::Level>(
        "/config/log/level", maps::log8::Level::INFO);
}

} // namespace

yacare::VirtualHost vhost {
    yacare::VirtualHost::SLB { "wiki-social" }, // for monrun checks

    // for future nginx config
    yacare::VirtualHost::SLB { "social.um" },
    yacare::VirtualHost::SLB { "core-nmaps-social" },

    yacare::VirtualHost::Real { "social.um.um-back" }, // for testing, load
};

YCR_SET_DEFAULT(vhost);

// The number of seconds before the shutdown to serve requests while not
// responding to /ping.
YCR_OPTIONS.shutdown().grace_period() = 10;

YCR_CREATE_METRIC("notification-queue-write-errors", YCR_SUM);

YCR_MAIN(argc, argv) {
    try {
        maps::wiki::sqs::AwsAPI awsApi;

        const std::string cfgPath = argc >= 2 ? argv[1] : DEFAULT_CFG_PATH;
        INFO() << "using config: " << cfgPath;
        maps::wiki::common::ExtendedXmlDoc cfg(cfgPath);
        maps::log8::setLevel(logLevel(cfg));
        maps::wiki::socialsrv::GlobalsScope globalsScope(cfg);

        yacare::setErrorReporter(maps::wiki::socialsrv::errorReporter);
        yacare::run(yacare::RunSettings{.useSystemDefaultLocale = true});

        return EXIT_SUCCESS;
    } catch (const maps::Exception& e) {
        ERROR() << "maps::Exception: " << e;
    } catch (const std::exception& e) {
        ERROR() << "std::exception: " << e.what();
    }
    return EXIT_FAILURE;
}
