# 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.
"""Japanese Expressions Dataset from Human Rights Infringement on Internet"""


import json

import datasets as ds


# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@dataset{hisada_shohei_2023_7960519,
  author       = {HISADA, Shohei},
  title        = {{Japanese Expressions Dataset from Human Rights 
                   Infringement on Internet}},
  month        = jun,
  year         = 2023,
  publisher    = {Zenodo},
  version      = {0.2},
  doi          = {10.5281/zenodo.7960519},
  url          = {https://doi.org/10.5281/zenodo.7960519}
}
"""

# You can copy an official description
_DESCRIPTION = """\
Japanese Expressions Dataset from Human Rights Infringement on Internet
"""

_HOMEPAGE = "https://zenodo.org/record/7960519"

_LICENSE = "CC-BY-4.0"

# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
    "v0.2": "https://zenodo.org/record/7960519/files/Expressions_Infringement_human_rights_v02.jsonl"
}

_FEATURE_MAP = {
    "1: Text in Dispute": "text",
    "2: Context Utilized in Adjudication": "context",
    "3-1a: The types of Allegedly Infringed Right 1": "right_type_1",
    "3-1b: Judgement on the Infringement Allegation 1": "judgement_1",
    "3-2a: The types of Allegedly Infringed Right 1": "right_type_2",
    "3-2b: Judgement on the Infringement Allegation 2": "judgement_2",
    "5-3: Bibliography": "bibliography",
    "5-1: Case Number": "case_number",
    "5-2: Case Name": "case_name",
    "5-4: Article Number": "article_number",
    "5-5: Online Platform": "platform",
}


class JEDHRIDataset(ds.GeneratorBasedBuilder):
    """Japanese Expressions Dataset from Human Rights Infringement on Internet."""

    VERSION = ds.Version("0.2.0")

    BUILDER_CONFIGS = [
        ds.BuilderConfig(
            name="v0.2",
            version=VERSION,
        ),
    ]

    DEFAULT_CONFIG_NAME = "v0.2"

    def _info(self):
        features = ds.Features(
            {
                "text": ds.Value("string"),
                "context": ds.Value("string"),
                "platform": ds.Value("string"),
                "right_type_1": ds.Value("string"),
                "judgement_1": ds.Value("bool"),
                "right_type_2": ds.Value("string"),
                "judgement_2": ds.Value("bool"),
                "bibliography": ds.Sequence(ds.Value("string")),
                "case_number": ds.Value("string"),
                "case_name": ds.Value("string"),
                "article_number": ds.Value("string"),
            }
        )
        return ds.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        url = _URLS[self.config.name]

        if type(url) is not str:
            raise ValueError("url must be a string")

        data_dir = dl_manager.download(url)

        return [
            ds.SplitGenerator(
                name=ds.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": data_dir,
                    "split": "train",
                },
            ),
        ]

    def _generate_examples(self, filepath, split):
        # read json for each line
        with open(filepath, encoding="utf-8") as f:
            for id_, row in enumerate(f):
                data = json.loads(row)
                # rename keys
                data = {v: data[k] for k, v in _FEATURE_MAP.items()}

                for key in ["right_type_1", "right_type_2"]:
                    if data[key] == "":
                        data[key] = None

                for key in ["judgement_1", "judgement_2"]:
                    if data[key] == "":
                        data[key] = None
                    elif data[key] == "0":
                        data[key] = False
                    elif data[key] == "1":
                        data[key] = True

                data["bibliography"] = [
                    x for x in str(data["bibliography"]).split("\n") if x != ""
                ]

                yield id_, data