#include "tool.h"

#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/common/include/exception.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>

namespace mrct = maps::mrc::toloka;

int main(int argc, char* argv[]) try {
    maps::cmdline::Parser parser;
    auto config = parser.string("config")
        .help("path to configuration");
    auto poolId = parser.string("pool-id")
        .required()
        .help("toloka pool id");
    auto outputFile = parser.string("output-file")
        .required()
        .help("file to write task results to");
    auto dryRun = parser.flag("dry-run")
        .defaultValue(false)
        .help("don't send accept/reject for assignments");
    parser.parse(argc, argv);

    std::string configPath = maps::mrc::common::CONFIG_PATH;
    if (config.defined()) {
        configPath = config;
    }
    maps::mrc::common::Config cfg{configPath};
    maps::mrc::toloka::io::TolokaClient tolokaClient(
        cfg.tolokaConfig().host(),
        cfg.tolokaConfig().authHeader());
    tolokaClient.setTimeout(std::chrono::seconds(60))
                .setMaxRequestAttempts(3)
                .setRetryInitialTimeout(std::chrono::seconds(1))
                .setRetryTimeoutBackoff(2);
    auto tsResults = mrct::loadAndMergeTasksResults(tolokaClient, poolId);

    for (const auto& tsResult : tsResults) {
        mrct::evaluateAssignments(tolokaClient, tsResult, dryRun);
    }

    mrct::writeTaskResults(tsResults, outputFile);

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