#
# Pyserini: Python interface to the Anserini IR toolkit built on Lucene
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import argparse
import json
"""
Evaluates the (1) percentage of fully supported claims and (2) oracle accuracy
for retrieval given an anserini run file. Intends to replicate the metrics in
Table 2 in this paper: https://www.aclweb.org/anthology/N18-1074.pdf.
"""

def evaluate_retrieval(args):
    evidences = {}
    top_ks = [1, 5, 10, 25, 50, 100]
    fully_supported = {k: 0 for k in top_ks}
    oracle_accuracy = {k: 0 for k in top_ks}
    num_queries = 0
    num_supported_queries = 0

    # read in ground truth file and save each query's evidences
    with open(args.truth_file, 'r', encoding='utf-8') as f:
        for line in f:
            line_json = json.loads(line.strip())
            query_id = line_json['id']
            if line_json['label'] == 'NOT ENOUGH INFO':
                evidences[query_id] = []
            else:  # line_json['label'] == 'SUPPORTS' or line_json['label'] == 'REFUTES'
                evidences[query_id] = [[evid[2] for evid in evid_set] for evid_set in line_json['evidence']]
                num_supported_queries += 1
            num_queries += 1

    # evaluates whether a query's predicted docs covers one complete set of evidences
    def evaluate(query_id, predicted_docs):
        for k in top_ks:
            if not evidences[query_id]:  # query is labelled "NOT ENOUGH INFO"
                oracle_accuracy[k] += 1
            else:  # query is labelled "SUPPORTS" or "REFUTES"
                for evid_set in evidences[query_id]:
                    if all([evid in predicted_docs[:k] for evid in evid_set]):
                        fully_supported[k] += 1
                        oracle_accuracy[k] += 1
                        break

    # read in run file and calculate metrics: % of fully supported and oracle accuracy
    with open(args.run_file, 'r', encoding='utf-8') as f:
        curr_query = -1
        predicted_docs = []
        for i, line in enumerate(f):
            query_id, _, doc_id, rank, _, _ = line.strip().split(' ')
            query_id = int(query_id)

            # if we reach a new query in the run file, evaluate the previous query
            if query_id != curr_query:
                if i > 0:  # do not evaluate if no queries have been processed yet
                    evaluate(curr_query, predicted_docs)
                curr_query = query_id
                predicted_docs.clear()

            if int(rank) <= max(top_ks):
                predicted_docs.append(doc_id)

        # evaluate final query
        evaluate(query_id, predicted_docs)

    # print evaluation metrics
    print(f'k\tFully Supported\tOracle Accuracy')
    for k in top_ks:
        print(f'{k}\t{fully_supported[k] / num_supported_queries:.4f}\t{oracle_accuracy[k] / num_queries:.4f}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Evaluates an anserini run file in the context of the FEVER task.')
    parser.add_argument('--truth_file', required=True, help='Ground truth evidences JSONL file from FEVER dataset.')
    parser.add_argument('--run_file', required=True, help='Run file, generated by running retrieval with anserini.')
    args = parser.parse_args()

    evaluate_retrieval(args)
