#!/bin/bash
set -euo pipefail

readonly results_dir="$1"
readonly implementations_matching_majority_dir="$2"
readonly consensus_dir="$3"
readonly implementation_dir="$4"
readonly implementation="$(basename "$implementation_dir")"

. src/shared.sh

all_queries() {
    find ./queries -type d -maxdepth 1 -mindepth 1 -print0 | xargs -0 -n1 basename | sort
}

is_implementation_in_majority_for() {
    local query="$1"
    grep "^${implementation}\$" < "${implementations_matching_majority_dir}/${query}" > /dev/null
}

has_consensus() {
    local query="$1"
    test -s "${consensus_dir}/${query}"
}

implementation_status() {
    local query="$1"

    if is_query_error "${results_dir}/${query}/${implementation}"; then
        echo "error"
        return
    fi

    if ! has_consensus "$query"; then
        echo "open"
        return
    fi

    if is_implementation_in_majority_for "$query"; then
        echo "pass"
        return
    fi

    echo "fail"
}

query_entry() {
    local query="$1"
    local status
    status="$(implementation_status "$query")"

    if [[ "$status" != "pass" ]]; then
        echo "  - id: ${query}"
        echo "    status: ${status}"
        if [[ "$status" != "error" ]]; then
            echo -n "    result: "
            all_query_result "${results_dir}/${query}/${implementation}"
        fi
    fi
}

main() {
    local query

    echo "# This file was generated by src/compile_implementation_report.sh from https://github.com/cburgmer/json-path-comparison/"
    echo
    echo "# This file tracks all results of the given implementation for queries which the implementation either does not match"
    echo "# an existing consensus or where no consensus exists."
    echo "# It can be used to track changes in the underlying implementation and complements the regression report."
    echo

    echo "implementation: ${implementation}"

    echo "queries:"
    while IFS= read -r query; do
        query_entry "$query"
    done <<< "$(all_queries)"
}

main
