#include <maps/wikimap/mapspro/services/mrc/long_tasks/toloka_manager_cron_jobs/lib/include/image_quality.h>

namespace maps {
namespace mrc {
namespace toloka {

ImageQuality::TaskOutput ImageQuality::mergeSingleTaskResults(
    const ImageQuality::AssignmentResults& results,
    size_t taskIdx,
    ImageQuality::UserIdToStat& userIdToStat)
{
    std::vector<ImageQuality::TaskOutput> outputs;
    for (const auto& res : results) {
        outputs.push_back(res.outputs[taskIdx]);
    }

    std::sort(outputs.begin(), outputs.end());
    const auto pair = longestEqualRange(outputs.begin(), outputs.end());
    if ((size_t)std::distance(pair.first, pair.second) <= outputs.size()
                                                              / 2) {
        return ImageQuality::TaskOutput{ImageQuality::TaskAnswer::HasDefect};
    }
    ImageQuality::TaskOutput majorityOutput = *pair.first;

    for (const auto& res : results) {
        if (!userIdToStat.count(res.userId)) {
            userIdToStat.emplace(res.userId, ImageQuality::UserStat(res));
        }
        auto& stat = userIdToStat.at(res.userId);
        const auto& userOutput = res.outputs[taskIdx];
        if (userOutput == majorityOutput) {
            ++stat.correctCount;
        }
    }
    return majorityOutput;
}

ImageQuality::TaskSuiteResult ImageQuality::mergeTaskSuiteResults(
    const ImageQuality::AssignmentResults& assignmentResults)
{
    return mergeTaskSuiteResultsImpl<ImageQuality>(assignmentResults);
}

void ImageQuality::evaluateAssignments(
    const io::TolokaClient& tolokaClient,
    const ImageQuality::TaskSuiteResult& tsResult)
{
    evaluateAssignmentsImpl<ImageQuality>(tolokaClient, tsResult);
}

} // toloka
} // mrc
} // maps
