"""Checker for glossary usage."""

import re

from padpo.checkers.baseclass import Checker
from padpo.pofile import PoItem


class GlossaryChecker(Checker):
    """Checker for glossary usage."""

    name = "Glossary"

    def check_item(self, item: PoItem):
        """Check an item in a `*.po` file."""
        if not item.msgstr_full_content:
            return  # no warning
        original_content = item.msgid_rst2txt.lower()
        original_content = re.sub(r"« .*? »", "", original_content)
        translated_content = item.msgstr_full_content.lower()
        for word, translations in glossary.items():
            if re.match(fr"\b{word.lower()}\b", original_content):
                for translated_word in translations:
                    if translated_word.lower() in translated_content:
                        break
                else:
                    possibilities = '"'
                    possibilities += '", "'.join(translations[:-1])
                    if len(translations) > 1:
                        possibilities += '" or "'
                    possibilities += translations[-1]
                    possibilities += '"'
                    item.add_warning(
                        self.name,
                        f'Found "{word}" that is not translated in '
                        f"{possibilities} in ###{item.msgstr_full_content}"
                        "###.",
                    )


# https://github.com/python/python-docs-fr/blob/
# 8a8a9f8dda4d7f40863f8b0d28f547d84f016ad3/CONTRIBUTING.rst
glossary = {
    "-like": ["-compatible"],
    "abstract data type": ["type abstrait"],
    "abstract data types": ["types abstraits"],
    "argument": ["argument"],
    "arguments": ["arguments"],
    "backslash": ["antislash", "*backslash*"],
    "backslashes": ["antislashs", "*backslashes*"],
    "backtrace": ["trace d'appels", "trace de pile"],
    "backtraces": ["traces d'appels", "traces de pile"],
    "big-endian": ["gros-boutiste"],
    "bound": ["lié"],
    "bug": ["bogue", "*bug*"],
    "bugs": ["bogues", "*bugs*"],
    "built-in": ["native"],
    "built-ins": ["fonctions natives"],
    "callback": ["fonction de rappel"],
    "callbacks": ["fonctions de rappel"],
    "call stack": ["pile d'appels"],
    "call stacks": ["piles d'appels"],
    "debugging": ["débogage"],
    "deep copy": ["copie récursive", "copie profonde"],
    "double quote": ["guillemet"],
    "double quotes": ["guillemets"],
    "deprecated": ["obsolète"],
    "e.g.": ["p. ex.", "par exemple"],
    "et al.": ["et autre", "et ailleurs"],
    "export": ["exporter", "exportation"],
    "exports": ["exportations"],
    "expression": ["expression"],
    "expressions": ["expressions"],
    "garbage collector": ["ramasse-miettes"],
    "getter": ["accesseur"],
    "getters": ["accesseurs"],
    "i.e": ["c.-à-d.", "c'est-à-dire"],
    "identifier": ["identifiant"],
    "identifiers": ["identifiants"],
    "immutable": ["immuable"],
    "import": ["importer", "importation"],
    "imports": ["importations"],
    "installer": ["installateur"],
    "installers": ["installateurs"],
    "interpreter": ["interpréteur"],
    "interpreters": ["interpréteurs"],
    "library": ["bibliothèque"],
    "libraries": ["bibliothèques"],
    "list comprehension": ["liste en compréhension"],
    "list comprehensions": ["listes en compréhension"],
    "little-endian": ["petit-boutiste"],
    "mixin type": ["type de mélange"],
    "mixin types": ["types de mélange"],
    "mutable": ["muable"],
    "namespace": ["espace de nommage", "espace de noms"],
    "namespaces": ["espaces de nommage", "espaces de noms"],
    "parameter": ["paramètre"],
    "parameters": ["paramètres"],
    "pickle": ["sérialiser"],
    "prompt": ["invite"],
    "raise": ["lever"],
    "raised": ["levé"],
    "regular expression": ["expression rationnelle", "expression régulière"],
    "regular expressions": [
        "expressions rationnelles",
        "expressions régulières",
    ],
    "return": ["renvoie"],
    "returns": ["renvoie"],
    "returned": ["renvoyé"],
    "setter": ["mutateur"],
    "setters": ["mutateurs"],
    "simple quote": ["guillemet simple"],
    "simple quotes": ["guillemets simples"],
    "socket": ["connecteur", "interface de connexion"],
    "sockets": ["connecteurs", "interfaces de connexion"],
    "statement": ["instruction"],
    "statements": ["instructions"],
    "subprocess": ["sous-processus"],
    "subprocesses": ["sous-processus"],
    "thread": ["fil d'exécution"],
    "threads": ["fils d'exécution"],
    "traceback": ["trace d'appels", "trace de pile"],
    "tracebacks": ["traces d'appels", "traces de pile"],
    "underscore": ["tiret bas", "*underscore*"],
    "underscores": ["tirets bas", "*underscores*"],
    "whitespace": ["caractère d'espacement"],
    "whitespaces": ["caractères d'espacement"],
}

# https://github.com/python/python-docs-fr/blob/
# ccc2e5863e8d814c3ec9463be70db6bbaf611462/glossary.po
glossary.update(
    {
        "abstract base class": ["classe de base abstraite"],
        "abstract base classes": ["classes de base abstraites"],
        "annotation": ["annotation"],
        "annotations": ["annotations"],
        "asynchronous context manager": [
            "gestionnaire de contexte asynchrone"
        ],
        "asynchronous context managers": [
            "gestionnaires de contexte asynchrone"
        ],
        "asynchronous generator": ["générateur asynchrone"],
        "asynchronous generators": ["générateurs asynchrones"],
        "asynchronous iterable": ["itérable asynchrone"],
        "asynchronous iterables": ["itérables asynchrones"],
        "asynchronous": ["asynchrone"],
        "attribute": ["attribut"],
        "attributes": ["attributs"],
        "awaitable": ["*awaitable*"],
        "BDFL": ["*BDFL*"],
        "binary file": ["fichier binaire"],
        "binary files": ["fichiers binaires"],
        "bytes-like object": ["objet octet-compatible"],
        "bytes-like objects": ["objets octet-compatible"],
        "bytecode": ["code intermédiaire", "*bytecode*"],
        "class": ["classe"],
        "classes": ["classes"],
        "class variable": ["variable de classe"],
        "class variables": ["variables de classe"],
        "coercion": ["coercition"],
        "coercions": ["coercitions"],
        "complex number": ["nombre complexe"],
        "complex numbers": ["nombres complexes"],
        "context manager": ["gestionnaire de contexte"],
        "context managers": ["gestionnaires de contexte"],
        "context variable": ["variable de contexte"],
        "context variables": ["variables de contexte"],
        "contiguous": ["contigu"],
        "coroutine": ["coroutine"],
        "coroutines": ["coroutines"],
        "CPython": ["CPython"],
        "decorator": ["décorateur"],
        "decorators": ["décorateurs"],
        "descriptor": ["descripteur"],
        "descriptors": ["descripteurs"],
        "dictionary": ["dictionnaire"],
        "dictionaries": ["dictionnaires"],
        "dictionary view": ["vue de dictionnaire"],
        "dictionary views": ["vues de dictionnaire"],
        "docstring": ["*docstring*", "chaîne de documentation"],
        "docstrings": ["*docstrings*", "chaînes de documentation"],
        "duck-typing": ["*duck-typing*"],
        "extension module": ["module d'extension"],
        "extension modules": ["modules d'extension"],
        "f-string": ["f-string"],
        "f-strings": ["f-strings"],
        "file object": ["objet fichier"],
        "file objects": ["objets fichier"],
        "file-like object": ["objet fichier-compatible"],
        "file-like objects": ["objets fichier-compatible"],
        "finder": ["chercheur"],
        "finders": ["chercheurs"],
        "floor division": ["division entière"],
        "floor divisions": ["divisions entières"],
        "function": ["fonction"],
        "functions": ["fonctions"],
        "function annotation": ["annotation de fonction"],
        "function annotations": ["annotations de fonction"],
        "__future__": ["__future__"],
        "garbage collection": ["ramasse-miettes"],
        "generator": ["générateur", "génératrice"],
        "generators": ["générateurs"],
        "generator iterator": ["itérateur de générateur"],
        "generator iterators": ["iterateurs de générateur"],
        "generator expression": ["expression génératrice"],
        "generator expressions": ["expressions génératrices"],
        "generic function": ["fonction générique"],
        "generic functions": ["fonctions génériques"],
        "GIL": ["GIL"],
        "global interpreter lock": ["verrou global de l'interpréteur"],
        "hash-based pyc": ["*pyc* utilisant le hachage"],
        "hashable": ["hachable"],
        # "IDLE": ["IDLE"],  # confusion with "idle"
        "immutable": ["immuable"],
        "import path": ["chemin des importations"],
        "import paths": ["chemins des importations"],
        "importing": ["importer", "important", "importation"],
        "importer": ["importateur"],
        "importers": ["importateurs"],
        "interactive": ["interactif", "interactive"],
        "interpreted": ["interprété"],
        "interpreter shutdown": ["arrêt de l'interpréteur"],
        "iterable": ["itérable"],
        "iterables": ["itérables"],
        "iterator": ["itérateur"],
        "iterators": ["itérateurs"],
        "key function": ["fonction clé"],
        "key functions": ["fonctions clé"],
        "keyword argument": ["argument nommé"],
        "keyword arguments": ["arguments nommés"],
        "lambda": ["lambda"],
        "list": ["*list*", "liste"],
        "lists": ["listes"],
        "list comprehension": ["liste en compréhension", "liste en intension"],
        "loader": ["chargeur"],
        "loaders": ["chargeurs"],
        "magic method": ["méthode magique"],
        "magic methods": ["méthodes magiques"],
        "mapping": ["tableau de correspondance"],
        "mappings": ["tableaux de correspondance"],
        "meta path finder": ["chercheur dans les méta-chemins"],
        "meta path finders": ["chercheurs dans les méta-chemins"],
        "metaclass": ["métaclasse"],
        "metaclasses": ["métaclasses"],
        "method": ["méthode"],
        "methods": ["méthodes"],
        "method resolution order": ["ordre de résolution des méthodes"],
        "module": ["module"],
        "modules": ["modules"],
        "module spec": ["spécificateur de module"],
        "module specs": ["spécificateurs de module"],
        "MRO": ["MRO"],
        "mutable": ["muable"],
        "named tuple": ["n-uplet nommé"],
        "named tuples": ["n-uplets nommés"],
        "tuple": ["n-uplet"],
        "tuples": ["n-uplets"],
        "namespace": ["espace de nommage", "espace de noms"],
        "namespaces": ["espaces de nommage", "espaces de noms"],
        "namespace package": ["paquet-espace de nommage"],
        "namespace packages": ["paquets-espace de nommage"],
        "nested scope": ["portée imbriquée"],
        "nested scopes": ["portées imbriquées"],
        "new-style class": ["nouvelle classe"],
        "new-style classes": ["nouvelles classes"],
        "object": ["objet"],
        "objects": ["objets"],
        "package": ["paquet"],
        "packages": ["paquets"],
        "parameter": ["paramètre"],
        "parameters": ["paramètres"],
        "path entry": ["entrée de chemin"],
        "path entries": ["entrées de chemin"],
        "path entry finder": ["chercheur de chemins"],
        "path entry finders": ["chercheurs de chemins"],
        "path entry hook": ["point d'entrée pour la recherche dans *path*"],
        "path entry hooks": ["points d'entrée pour la recherche dans *path*"],
        "path based finder": ["chercheur basé sur les chemins"],
        "path based finders": ["chercheurs basés sur les chemins"],
        "path-like object": ["objet simili-chemin"],
        "path-like objects": ["objets simili-chemin"],
        "PEP": ["PEP"],
        "portion": ["portion"],
        "portions": ["portions"],
        "positional argument": ["argument positionnel"],
        "positional arguments": ["arguments positionnels"],
        "provisional API": ["API provisoire"],
        "provisional package": ["paquet provisoire"],
        "provisional packages": ["paquets provisoires"],
        "pythonic": ["*pythonique*", "*pythoniques*"],
        "qualified name": ["nom qualifié"],
        "qualified names": ["noms qualifiés"],
        "reference count": ["nombre de références"],
        "regular package": ["paquet classique"],
        "regular packages": ["paquets classiques"],
        "__slots__": ["``__slots__``"],
        "sequence": ["séquence"],
        "sequences": ["séquences"],
        "single dispatch": ["distribution simple"],
        "slice": ["tranche"],
        "slices": ["tranches"],
        "special method": ["méthode spéciale"],
        "special methods": ["méthodes spéciales"],
        "statement": ["instruction"],
        "statements": ["instructions"],
        "text encoding": ["encodage de texte"],
        "text encodings": ["encodages de texte"],
        "text file": ["fichier texte"],
        "text files": ["fichiers texte"],
        "triple quoted string": ["chaîne entre triple guillemets"],
        "triple quoted strings": ["chaîne entre triple guillemets"],
        "type": ["type"],
        "types": ["types"],
        "type alias": ["alias de type"],
        "type aliases": ["alias de type"],
        "type hint": ["indication de type"],
        "type hints": ["indications de type"],
        "universal newlines": ["retours à la ligne universels"],
        "variable annotation": ["annotation de variable"],
        "variable annotations": ["annotations de variables"],
        "virtual environment": ["environnement virtuel"],
        "virtual environments": ["environnements virtuels"],
        "virtual machine": ["machine virtuelle"],
        "virtual machines": ["machines virtuelles"],
        "zen of Python": ["le zen de Python"],
    }
)
