#include "tool.h"

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

#include <utility>

namespace mrct = maps::mrc::toloka;

int main(int argc, char* argv[]) try {
    maps::cmdline::Parser parser;
    auto configParam = parser.string("config")
        .help("path to configuration");
    auto poolId = parser.string("toloka-pool-id")
        .help("toloka pool ID to post task suites to")
        .required();
    auto inputFile = parser.string("input-file")
        .help("path to json file containing result of signs detection")
        .required();
    auto startImageUrl = parser.string("start-image-url")
        .help("image url in the input file to start with");
    auto taskSuitesCount = parser.num("task-suites-count")
        .help("number of task suites to create, default is 1")
        .required();
    auto tasksPerSuite = parser.num("tasks-per-suite")
        .help("number of tasks in each task suite")
        .required();
    auto overlap = parser.num("overlap")
        .help("number of Toloka users handling each tasks, default is 3")
        .defaultValue(3);
    parser.parse(argc, argv);

    std::string configPath = maps::mrc::common::CONFIG_PATH;
    if (configParam.defined()) {
        configPath = configParam;
    }
    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);

    mrct::ClassificationTasksGenerator generator(tolokaClient, poolId, inputFile);
    generator.setOverlap(overlap);

    std::string stopUrl = generator.generate(startImageUrl,
                                             taskSuitesCount,
                                             tasksPerSuite);
    if (!stopUrl.empty()) {
        INFO() << "Next time start with imageUrl: " << stopUrl;
    } else {
        INFO() << "All images processed";
    }
    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;
}
