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"sentence_{lang}"
    prompt_map = {
        "prompt_1": f"{lang_dict[lang]}: {{{{{language_column_name}}}}} \nEnglish: ",
        "prompt_1_reverse": f"English: {{{{sentence_eng_Latn}}}} \n{lang_dict[lang]}: ",
        "prompt_2": f"You are a translation expert. Translate the following {lang_dict[lang]} sentences to English \n"
        f"{lang_dict[lang]}: {{{{{language_column_name}}}}}\nEnglish: ",
        "prompt_2_reverse": f"You are a translation expert. Translate the following English sentences to "
        f"{lang_dict[lang]} "
        "\nEnglish: {{sentence_eng_Latn}} "
        f"\n{lang_dict[lang]}: ",
        "prompt_3": f"As a {lang_dict[lang]} and English linguist, translate the following {lang_dict[lang]} sentences "
        f"to English \n{lang_dict[lang]}: {{{{{language_column_name}}}}}\nEnglish: ",
        "prompt_3_reverse": f"As a {lang_dict[lang]} and English linguist, translate the following English sentences to "
        f"{lang_dict[lang]} "
        "\nEnglish: {{sentence_eng_Latn}} "
        f"\n{lang_dict[lang]}: ",
    }
    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 = {
        "afr_Latn": "Afrikaans",
        "amh_Ethi": "Amharic",
        "arb_Arab": "Arabic",
        "bem_Latn": "Bemba",
        "ewe_Latn": "Ewe",
        "fra_Latn": "French",
        "hau_Latn": "Hausa",
        "ibo_Latn": "Igbo",
        "kin_Latn": "Kinyarwanda",
        "mey_Arab": "Hassaniya Arabic",
        "mlg_Latn": "Malagasy",
        "msa_Latn": "Malay",
        "nde_Latn": "North Ndebele",
        "nso_Latn": "Northern Sotho",
        "nya_Latn": "Chichewa",
        "orm_Ethi": "Oromo",
        "shi_Arab": "Tachelhit",
        "sna_Latn": "Shona (Latin)",
        "som_Latn": "Somali",
        "ssw_Latn": "Swati",
        "swa_Latn": "Swahili",
        "tam_Taml": "Tamil",
        "tel_Telu": "Telugu",
        "tir_Ethi": "Tigrinya",
        "ton_Latn": "Tongan",
        "tsn_Latn": "Tswana",
        "urd_Arab": "Urdu",
        "ven_Latn": "Venda",
        "wol_Latn": "Wolof",
        "xho_Latn": "Xhosa",
        "yor_Latn": "Yoruba",
        "zul_Latn": "Zulu",
    }

    for lang in languages.keys():
        try:
            if not reverse:
                file_name = f"ntrex_{lang}-eng_Latn.yaml"
                task_name = f"ntrex_{lang}-eng_Latn_{mode}"
                yaml_template = "ntrex"
                yaml_details = {
                    "include": yaml_template,
                    "dataset_name": f"{lang}",
                    "task": task_name,
                    "doc_to_target": "sentence_eng_Latn",
                    "doc_to_text": prompt_func(mode, lang, languages),
                }
                os.makedirs(f"{output_dir}/{mode}/african-english", exist_ok=True)
                with open(
                    f"{output_dir}/{mode}/african-english/{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,
                    )
            else:
                file_name = f"ntrex_eng_Latn-{lang}.yaml"
                task_name = f"ntrex_eng_Latn-{lang}_{mode}"
                yaml_template = "ntrex"
                yaml_details = {
                    "include": yaml_template,
                    "dataset_name": f"{lang}",
                    "task": task_name,
                    "doc_to_target": f"sentence_{lang}",
                    "doc_to_text": prompt_func(f"{mode}_reverse", lang, languages),
                }
                os.makedirs(f"{output_dir}/{mode}/english-african", exist_ok=True)
                with open(
                    f"{output_dir}/{mode}/english-african/{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_1",
        choices=["prompt_1", "prompt_2", "prompt_3"],
        help="Prompt number",
    )
    parser.add_argument(
        "--reverse",
        default=False,
        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()
