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

#include <util/charset/utf8.h>
#include <util/charset/wide.h>

namespace maps {
namespace mrc {
namespace toloka {

DetectionPairMatch::TaskOutput DetectionPairMatch::mergeSingleTaskResults(
    const DetectionPairMatch::AssignmentResults& results,
    size_t taskIdx)
{
    std::vector<DetectionPairMatchResult> answers;
    for (const auto& res : results) {
        answers.push_back(res.outputs[taskIdx].result());
    }

    std::sort(answers.begin(), answers.end());
    const auto pair = longestEqualRange(answers.begin(), answers.end());
    if ((size_t)std::distance(pair.first, pair.second) <= answers.size() / 2) {
        return DetectionPairMatch::TaskOutput{DetectionPairMatch::TaskAnswer::Unknown};
    }

    return DetectionPairMatch::TaskOutput{*pair.first};
}

DetectionPairMatch::TaskSuiteResult DetectionPairMatch::mergeTaskSuiteResults(
    const DetectionPairMatch::AssignmentResults& assignmentResults)
{
    DetectionPairMatch::TaskSuiteResult tsResult;

    REQUIRE(!assignmentResults.empty(), "Empty task suite results");
    size_t tasksCount = assignmentResults[0].inputs.size();

    for (size_t i = 0; i < tasksCount; ++i) {
        DetectionPairMatch::TaskInput input = assignmentResults[0].inputs[i];
        DetectionPairMatch::TaskOutput output = mergeSingleTaskResults(assignmentResults, i);

        tsResult.taskResults.push_back({input, output});
    }

    return tsResult;
}

void DetectionPairMatch::evaluateAssignments(
    const io::TolokaClient& /*tolokaClient*/,
    const DetectionPairMatch::TaskSuiteResult& /*tsResult*/)
{
    return;
}

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