from collections import defaultdict

from datasets import load_dataset

from mteb.abstasks.retrieval import AbsTaskRetrieval
from mteb.abstasks.task_metadata import TaskMetadata


class NanoFEVERRetrieval(AbsTaskRetrieval):
    metadata = TaskMetadata(
        name="NanoFEVERRetrieval",
        description="NanoFEVER is a smaller version of "
        + "FEVER (Fact Extraction and VERification), which consists of 185,445 claims generated by altering sentences"
        + " extracted from Wikipedia and subsequently verified without knowledge of the sentence they were"
        + " derived from.",
        reference="https://fever.ai/",
        dataset={
            "path": "zeta-alpha-ai/NanoFEVER",
            "revision": "a8bfdf1bf15181167a7e22e69cf8754bdea9b4c8",
        },
        type="Retrieval",
        category="t2t",
        modalities=["text"],
        eval_splits=["train"],
        eval_langs=["eng-Latn"],
        main_score="ndcg_at_10",
        date=["2018-01-01", "2018-12-31"],
        domains=["Academic", "Encyclopaedic"],
        task_subtypes=["Claim verification"],
        license="cc-by-4.0",
        annotations_creators="expert-annotated",
        dialect=[],
        sample_creation="found",
        bibtex_citation=r"""
@inproceedings{thorne-etal-2018-fever,
  address = {New Orleans, Louisiana},
  author = {Thorne, James  and
Vlachos, Andreas  and
Christodoulopoulos, Christos  and
Mittal, Arpit},
  booktitle = {Proceedings of the 2018 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers)},
  doi = {10.18653/v1/N18-1074},
  editor = {Walker, Marilyn  and
Ji, Heng  and
Stent, Amanda},
  month = jun,
  pages = {809--819},
  publisher = {Association for Computational Linguistics},
  title = {{FEVER}: a Large-scale Dataset for Fact Extraction and {VER}ification},
  url = {https://aclanthology.org/N18-1074},
  year = {2018},
}
""",
        prompt={
            "query": "Given a claim, retrieve documents that support or refute the claim"
        },
        adapted_from=["FEVER"],
    )

    def load_data(self, num_proc: int | None = None, **kwargs) -> None:
        if self.data_loaded:
            return

        self.corpus = load_dataset(
            "zeta-alpha-ai/NanoFEVER",
            "corpus",
            revision="a8bfdf1bf15181167a7e22e69cf8754bdea9b4c8",
        )
        self.queries = load_dataset(
            "zeta-alpha-ai/NanoFEVER",
            "queries",
            revision="a8bfdf1bf15181167a7e22e69cf8754bdea9b4c8",
        )
        self.relevant_docs = load_dataset(
            "zeta-alpha-ai/NanoFEVER",
            "qrels",
            revision="a8bfdf1bf15181167a7e22e69cf8754bdea9b4c8",
        )

        self.corpus = {
            split: {
                sample["_id"]: {"_id": sample["_id"], "text": sample["text"]}
                for sample in self.corpus[split]
            }
            for split in self.corpus
        }

        self.queries = {
            split: {sample["_id"]: sample["text"] for sample in self.queries[split]}
            for split in self.queries
        }

        relevant_docs = {}

        for split in self.relevant_docs:
            relevant_docs[split] = defaultdict(dict)
            for query_id, corpus_id in zip(
                self.relevant_docs[split]["query-id"],
                self.relevant_docs[split]["corpus-id"],
            ):
                relevant_docs[split][query_id][corpus_id] = 1
        self.relevant_docs = relevant_docs

        self.data_loaded = True
