import collections


def merge(queries, qp, qc, qrels):
    """ Merge queries, qrels, <query, passage> pairs, <query, chunk> pairs into a single dict. """
    data = collections.OrderedDict()

    for qid in qc:
        passage_ids = list()
        labels = list()
        for passage_id in qp[qid]:
            doc_id = passage_id.split("_")[0]
            label = 0
            if doc_id in qrels[qid]:  # leave unjudged documents as non-relevant
                label = 1
            passage_ids.append(passage_id)
            labels.append(label)
        assert len(passage_ids) == len(labels)

        chunk_id_list = list(qc[qid].keys())
        data[qid] = (queries[qid], chunk_id_list, passage_ids, labels)

    return data