import json

import datasets


logger = datasets.logging.get_logger(__name__)


_DESCRIPTION = """\
Ukrainian News Dataset

This is a dataset of news articles downloaded from various Ukrainian websites and Telegram channels. The dataset contains approximately ~23M JSON objects (news)
"""


_URLS = [
    "ukrainian-news-vol1.jsonl",
    "ukrainian-news-vol2.jsonl",
    "ukrainian-news-vol3.jsonl",
    "ukrainian-telegram.jsonl"
]


class UkrainianNews(datasets.GeneratorBasedBuilder):
    """Ukrainian News Dataset"""
    VERSION = datasets.Version("0.0.2")
    DEFAULT_CONFIG_NAME = "default"
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="default", version=VERSION, description=""),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("int32"),
                    "url": datasets.Value("string"),
                    "title": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "owner": datasets.Value("string"),
                    "datetime": datasets.Value("string"),
                }
            )
        )

    def _split_generators(self, dl_manager):
        downloaded_files = dl_manager.download(_URLS)

        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_files})
        ]

    def _generate_examples(self, filepaths):
        """This function returns the examples in the raw (text) form."""
        logger.info("generating examples from = %s", filepaths)
        for path in filepaths:
            with open(path, encoding="utf-8") as f:
                for news_str in f:
                    news = json.loads(news_str)
                    yield news['id'], news