#include <yandex/maps/wiki/outsource/config.h>
#include <yandex/maps/wiki/outsource/task_result.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 <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/log8/include/log8.h>

#include <library/cpp/resource/resource.h>


namespace maps::wiki::outsource {

namespace rev = revision;

namespace {

void run(int argc, char** argv)
{
    cmdline::Parser parser;
    auto configFilename = parser.file("config")
        .help("services config file")
        .defaultValue("/etc/yandex/maps/wiki/services/services.xml");
    auto branchId = parser.num("branch-id")
        .help("branch id, default: 0")
        .defaultValue(0);
    auto regionId = parser.size_t("region")
        .help("outsource_region id")
        .defaultValue(0);

    parser.parse(argc, argv);

    if (!regionId.defined()) {
        parser.printUsageAndExit(EXIT_FAILURE);
    }

    auto loadConfig = [&] {
        if (configFilename.defined()) {
            return std::make_unique<common::ExtendedXmlDoc>(configFilename);
        }
        return common::loadDefaultConfig();
    };
    auto configPtr = loadConfig();

    maps::wiki::diffalert::EditorConfig editorConfig(
        configPtr->get<std::string>("/config/services/editor/config"));
    maps::wiki::outsource::Config outsourceConfig(
        NResource::Find(maps::wiki::outsource::OUTSOURCE_CONFIG_RESOURCE_ID));

    common::PoolHolder holder(*configPtr, "long-read", "long-read");

    auto taskResults = calcTaskResults(
        {regionId}, RegionCalcPolicy::CurrentTask,
        rev::TRUNK_BRANCH_ID, holder.pool(), editorConfig, outsourceConfig);

    REQUIRE(taskResults.size() == 1, "Failed to calculate stat for region " << regionId);

    for (const auto& taskResult : taskResults.begin()->second) {
        INFO() << "Result id: " << taskResult.regionId
               << " name: " << taskResult.regionName
               << " company: " <<taskResult.companyName
               << " outsourcerLogin: " << taskResult.outsourcerLogin
               << " qaulity: " << taskResult.quality
               << " workAmount: " << taskResult.workAmount
               << " moneyAmount: " << taskResult.moneyAmount
               << " workStart: " << taskResult.workStart
               << " workEnd: " << taskResult.workEnd;
    }
}

} // namespace
} // namespace maps::wiki::outsource

int main(int argc, char** argv) {
    try {
        maps::wiki::outsource::run(argc, argv);
        return EXIT_SUCCESS;
    } catch (const maps::Exception& ex) {
        ERROR() << "maps::Exception: " << ex;
    } catch (const std::exception& ex) {
        ERROR() << "std::exception: " << ex.what();
    }
    return EXIT_FAILURE;
}
