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

#include <fstream>

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

    cmdline::Parser parser("Merge Toloka results from multiple users");
    auto inputPath = parser.string("input").required().help(
        "input Json file with Toloka assignments");
    auto aggregatePath
        = parser.string("aggregate")
              .required()
              .help("output Json file with aggregated results");
    auto statusPath = parser.string("status").required().help(
        "output Json file to approve/reject");
    parser.parse(argc, const_cast<char**>(argv));

    INFO() << "Start Toloka results merging";
    std::ifstream inputFile(inputPath);
    auto answers = parseTolokaAnswers(inputFile);
    INFO() << "Parsed answers: " << answers.size();
    auto aggregatedPhotos = aggregatePhotos(answers);
    INFO() << "Aggregated photos: " << aggregatedPhotos.size();
    auto aggregatedAssignments
        = aggregateAssignments(answers, aggregatedPhotos);
    std::ofstream aggregateFile(aggregatePath);
    save(aggregatedPhotos, aggregateFile);
    INFO() << "Aggregated assignments: " << aggregatedAssignments.size();
    std::ofstream statusFile(statusPath);
    save(aggregatedAssignments, statusFile);
    INFO() << "Finish Toloka results merging";
} catch (const maps::Exception& e) {
    INFO() << e;
    return EXIT_FAILURE;
} catch (const std::exception& e) {
    INFO() << e.what();
    return EXIT_FAILURE;
}
