import argparse
import os

import yaml


class FunctionTag:
    def __init__(self, value):
        self.value = value


def prompt_func(mode, lang, lang_dict):
    language_column_name = f"{lang}_text"
    prompt_map = {
        "prompt_1": "You are an advanced Translator, a specialized assistant designed to translate documents from "
        f"{lang_dict[lang]} into English. \nYour main goal is to ensure translations are grammatically "
        f"correct and human-oriented. \n{lang_dict[lang]}: {{{{{language_column_name}}}}} \nEnglish: ",
        "prompt_1_reverse": "You are an advanced Translator, a specialized assistant designed to translate documents "
        f"from English into {lang_dict[lang]}. \nYour main goal is to ensure translations are "
        f"grammatically correct and human-oriented. "
        f"\nEnglish: {{eng_text}} \n{lang_dict[lang]}: ",
        "prompt_2": f"{lang_dict[lang]} sentence: {{{{{language_column_name}}}}} \nEnglish sentence: ",
        "prompt_2_reverse": "English sentence: {{eng_text}} "
        f"\n{lang_dict[lang]} sentence: ",
        "prompt_3": f"You are a translation expert. Translate the following {lang_dict[lang]} sentences to English \n"
        f"{lang_dict[lang]} sentence: {{{{{language_column_name}}}}}\nEnglish sentence: ",
        "prompt_3_reverse": f"You are a translation expert. Translate the following English sentences to "
        f"{lang_dict[lang]} "
        "\nEnglish sentence: {{eng_text}} "
        f"\n{lang_dict[lang]} sentence: ",
    }
    return prompt_map[mode]


def gen_lang_yamls(output_dir: str, overwrite: bool, mode: str, reverse: bool) -> None:
    """
    Generate a yaml file for each language.

    :param output_dir: The directory to output the files to.
    :param overwrite: Whether to overwrite files if they already exist.
    """
    err = []
    languages = {
        "amh": "Amharic",
        "bam": "Bambara",
        "bbj": "Gbomala",
        "ewe": "Ewe",
        "fon": "Fon",
        "hau": "Hausa",
        "ibo": "Igbo",
        "kin": "Kinyarwanda",
        "lug": "Luganda",
        "luo": "Luo",
        "mos": "Mossi",
        "nya": "Chichewa",
        "pcm": "Nigerian Pidgin",
        "sna": "Shona",
        "swa": "Swahili",
        "tsn": "Setswana",
        "twi": "Twi",
        "wol": "Wolof",
        "xho": "Xhosa",
        "yor": "Yoruba",
        "zul": "Zulu",
    }

    french_langs = ["bam", "bbj", "ewe", "fon", "wol", "mos"]

    for lang in languages.keys():
        try:
            norm_lang = f"{lang}-en" if lang not in french_langs else f"{lang}-fr"
            reverse_lang = f"en-{lang}" if lang not in french_langs else f"fr-{lang}"
            dataset_name = norm_lang if reverse else reverse_lang
            file_name = f"mafand_{dataset_name}.yaml"
            task_name = f"mafand_{dataset_name}_{mode}"
            yaml_template = "mafand"
            yaml_details = {
                "include": yaml_template,
                "task": task_name,
                "dataset_name": reverse_lang,
            }
            file_dir = (
                f"{output_dir}/{mode}/african-english"
                if reverse
                else f"{output_dir}/{mode}/english-african"
            )
            os.makedirs(file_dir, exist_ok=True)
            with open(
                f"{file_dir}/{file_name}",
                "w" if overwrite else "x",
                encoding="utf8",
            ) as f:
                f.write("# Generated by utils.py\n")
                yaml.dump(
                    yaml_details,
                    f,
                    allow_unicode=True,
                )

        except FileExistsError:
            err.append(file_name)

    if len(err) > 0:
        raise FileExistsError(
            "Files were not created because they already exist (use --overwrite flag):"
            f" {', '.join(err)}"
        )


def main() -> None:
    """Parse CLI args and generate language-specific yaml files."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--overwrite",
        default=True,
        action="store_true",
        help="Overwrite files if they already exist",
    )
    parser.add_argument(
        "--output-dir",
        default="./",
        help="Directory to write yaml files to",
    )
    parser.add_argument(
        "--mode",
        default="prompt_3",
        choices=["prompt_1", "prompt_2", "prompt_3"],
        help="Prompt number",
    )
    parser.add_argument(
        "--reverse",
        default=True,
        choices=[True, False],
        help="Reverse the translation direction",
    )
    args = parser.parse_args()

    gen_lang_yamls(
        output_dir=args.output_dir,
        overwrite=args.overwrite,
        mode=args.mode,
        reverse=args.reverse,
    )


if __name__ == "__main__":
    main()
