# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""CoNaLa dataset."""

import json
import datasets


_CITATION = """\
@article{zhou2022doccoder,
  title={DocCoder: Generating Code by Retrieving and Reading Docs},
  author={Zhou, Shuyan and Alon, Uri and Xu, Frank F and JIang, Zhengbao and Neubig, Graham},
  journal={arXiv preprint arXiv:2207.05987},
  year={2022}
}
"""

_DESCRIPTION = """This is the re-split of CoNaLa dataset. For each code snippet in the dev and test set, at least one function is held out from the training set. This split aims at testing a code generation model's capacity in generating unseen functions.
We further make sure that examples from the same StackOverflow post (same question_id before -) are in the same split."""

_HOMEPAGE = "https://github.com/shuyanzhou/docprompting"
_URLs = {
    "docs": "tldr-docs.jsonl",
    "data": {"train": "tldr-train.jsonl", "validation": "tldr-dev.jsonl", "test": "tldr-test.jsonl" },
}

class DocPromptingConala(datasets.GeneratorBasedBuilder):
    """TLDR natural language to bash generation dataset."""

    VERSION = datasets.Version("1.1.0")


    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="data",
            version=datasets.Version("1.1.0"),
            description=_DESCRIPTION,
        ),
        datasets.BuilderConfig(name="docs", version=datasets.Version("1.1.0"), description=_DESCRIPTION),
    ]

    DEFAULT_CONFIG_NAME = "data"
    
    
    def _info(self):
        if self.config.name == "data":
            features=datasets.Features({"question_id": datasets.Value("string"),
                                            "nl": datasets.Value("string"),
                                            "cmd": datasets.Value("string"),
                                            "oracle_man": datasets.Sequence(feature=datasets.Value("string")), 
                                            "canonical_cmd": datasets.Value("string"), 
                                            "cmd_name": datasets.Value("string"), 
                                            "tldr_cmd_name": datasets.Value("string"), 
                                            "manual_exist": datasets.Value("bool"),
                                            "matching_info": dict()
                                            })
        else:
            features=datasets.Features({"doc_id": datasets.Value("string"),
                                            "doc_content": datasets.Value("string"),
                                            })
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=None,
            citation=_CITATION,
            homepage=_HOMEPAGE)

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        config_urls = _URLs[self.config.name]
        data_dir = dl_manager.download_and_extract(config_urls)
        if self.config.name == "data":
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"filepath": data_dir["train"], "split": "train"},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    gen_kwargs={"filepath": data_dir["test"], "split": "test"},
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.VALIDATION,
                    gen_kwargs={"filepath": data_dir["validation"], "split": "validation"},
                ),
                ]
        else:
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"filepath": data_dir, "split": "train"},
                ),
                ]


    def _generate_examples(self, filepath, split):
        key = 0
        for line in open(filepath, encoding="utf-8"):
            line = json.loads(line)
            yield key, line   
            key += 1