import re
from glob import glob
from pathlib import Path

from tqdm import tqdm

DATA_DIR = "data/imdb-sentiment"
FILE_PRE = DATA_DIR.rsplit("/", maxsplit=1)[1].replace("-", "_")


def clean_text(text):
    text = re.sub(r"\s+", " ", text, flags=re.MULTILINE | re.DOTALL)

    return text.strip()


def main():
    # load raw data
    splits = ["train", "test"]
    classes = ["pos", "neg"]

    split_text_dict = dict(map(lambda s: (s, []), splits))
    split_label_dict = dict(map(lambda s: (s, []), splits))

    for split in splits:
        for cls in classes:
            for g in tqdm(
                sorted(glob(str(Path(DATA_DIR) / f"aclImdb/{split}/{cls}/*"))),
                total=12500,
                desc=f"{split}-{cls}",
            ):
                with open(g, encoding="utf-8") as f:
                    split_text_dict[split].append(clean_text(f.readlines()[0]))
                    split_label_dict[split].append("1" if cls == "pos" else "0")

    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()
        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 imdb-sentiment dataset.

    1. Download the original data, Large Movie Review Dataset v1.0, at https://ai.stanford.edu/~amaas/data/sentiment/.
    2. Decompress the files using "tar -fxz aclImdb_v1.tar.gz". This may take a while.
    3. Run this script with appropriate file path defined in DATA_DIR.
    4. Compress the output files using "bzip2 -fkv *raw_texts*.txt".
    """
    main()
