# adapted from allenai/longformer/scripts/hp_preprocess.py
# all credit goes to the authors of Longformer

import json
import re
import xml.etree.ElementTree as ET
from functools import partial
from pathlib import Path

import numpy as np

DATA_DIR = "data/hyperpartisan"
FILE_PRE = "hyperpartisan"

re_sub = partial(re.sub, flags=re.MULTILINE | re.DOTALL)


def clean_txt(text):
    text = re.sub(r"[a-zA-Z]+\/[a-zA-Z]+", " ", text)
    text = re.sub(r"&#160;", "", text)

    # Remove URL
    text = re_sub(r"(http)\S+", "", text)
    text = re_sub(r"(www)\S+", "", text)
    text = re_sub(r"(href)\S+", "", text)
    # Remove multiple spaces
    text = re_sub(r"\s+", " ", text)

    # remove repetition
    text = re_sub(r"([!?.]){2,}", r"\1", text)
    text = re_sub(r"\b(\S*?)(.)\2{2,}\b", r"\1\2", text)

    return text.strip()


def main():
    # load raw data
    article_root = ET.parse(
        Path(DATA_DIR) / "articles-training-byarticle-20181122.xml"
    ).getroot()
    texts = article_root.findall("article")

    label_root = ET.parse(
        Path(DATA_DIR) / "ground-truth-training-byarticle-20181122.xml"
    ).getroot()
    labels = label_root.findall("article")

    assert len(texts) == len(labels)

    # clean raw data
    texts = np.array(
        list(
            map(
                lambda x: clean_txt(
                    ET.tostring(x, method="text", encoding="utf-8").decode("utf-8")
                ),
                texts,
            )
        )
    )
    labels = (
        (np.array(list(map(lambda y: y.attrib["hyperpartisan"], labels))) == "true")
        .astype(np.int_)
        .astype(np.str_)
    )

    # generate full-size dataset
    output = ["".join([y, "\t", x, "\n"]) for x, y in zip(texts, labels)]
    output[-1] = output[-1].strip()
    with open(Path(DATA_DIR) / f"{FILE_PRE}_raw_texts.txt", "w", encoding="utf-8") as f:
        f.writelines(output)

    # generate train-val-test datasets
    split_text_dict = {}
    split_label_dict = {}

    with open(Path(DATA_DIR) / "hp-splits.json", encoding="utf-8") as f:
        for split, idx in json.load(f).items():
            split_text_dict[split] = texts[idx].tolist()
            split_label_dict[split] = labels[idx].tolist()

    for split in split_text_dict.keys():
        output = [
            "".join([y, "\t", x, "\n"])
            for x, y in zip(split_text_dict[split], split_label_dict[split])
        ]
        output[-1] = output[-1].strip()
        split = "val" if split == "dev" else split
        with open(
            Path(DATA_DIR) / f"{FILE_PRE}_raw_texts_{split}.txt", "w", encoding="utf-8"
        ) as f:
            f.writelines(output)


if __name__ == "__main__":
    """Instructions for preparing the hyperpartisan dataset.

    1. Download the original data from PAN at SemEval 2019 Task 4: https://zenodo.org/record/1489920.
        - texts: "articles-training-byarticle-20181122.zip"
        - labels: "ground-truth-training-byarticle-20181122.zip"
    2. Decompress the files using "unzip -nq \*byarticle\*.zip".
    3. Download the split file at https://github.com/allenai/longformer/blob/master/scripts/hp-splits.json.
        Place it under the same directory as the original data.
    4. Run this script with appropriate file path defined in DATA_DIR.
    5. Compress the output files using "bzip2 -fkv *raw_texts*.txt".
    """
    main()
