File size: 4,388 Bytes
858bf77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os
from pathlib import Path
from typing import Any, Dict, Optional

import yaml

from core.logger.core_logger import CoreLogger


class Settings:
    __slots__ = (
        "_config",
        "_file_path",
        "_logger",
        "_max_size_file",
        "_env_vars_to_load",
    )

    def __init__(self):
        self._config: Dict[str, Any] = {}
        self._file_path: Optional[Path] = None
        self._logger: CoreLogger = CoreLogger(name="settings")
        self._max_size_file: int = 5 * 1024 * 1024

        self._env_vars_to_load = [
            "ANTHROPIC_KEY",
            "ANTHROPIC_VERSION",
            "OPENAI_API_KEY",
        ]

        self.load_configuration_file(Path(__file__).resolve().parents[2] / "config.yml")

    @property
    def all_settings(self) -> Dict[str, Any]:
        return self._config.copy()

    @property
    def logger(self):
        return self._logger

    def _load_env_variable(self) -> None:
        for key in self._env_vars_to_load:
            if key in os.environ:
                self._config[key] = os.environ.get(key)

    def check_file_permission(self, file_path: Optional[Path]) -> bool:
        if file_path:
            path = Path(file_path)
            if not path.exists():
                self._logger.error(f"🛑 Le fichier de configuration est introuvable.")
                return False

            if not path.is_file():
                self._logger.error(f"Le fichier de configuration n'est pas un fichier.")
                return False

            if path.suffix.lower() not in (".yaml", ".yml"):
                self._logger.error(
                    f"🛑 Le fichier de configuration n'est pas un fichier yaml."
                )
                return False

            return True
        
        return False

    def load_configuration_file(self, file_path: str | Path) -> None:
        path = Path(file_path).resolve()
        self._file_path = path

        try:
            permission = self.check_file_permission(path)

            if permission:
                size = path.stat().st_size
                if size > self._max_size_file:
                    self._logger.error(
                        "🛑 Le fichier de configuration ne doit pas dépasser la taille maximal"
                    )

                with open(path, "r", encoding="utf-8") as file:
                    self._config = yaml.safe_load(file) or {}

                    if not self._config:
                        self._logger.error(
                            "🛑 La configuration doit être un dictionnaire."
                        )

                    self._logger.info(
                        "✅ Chargement de la configuration terminée avec succès."
                    )

        except PermissionError as exc:
            self._logger.error(
                f"🛑 Impossible de lire le fichier de configuration : {exc}"
            )
            if "e" in locals() and exc:
                self._config = {}
            raise
        except Exception as e:
            self._logger.error(
                f"🛑 Erreur lors de la lecture du fichier de configuration : {e}"
            )
            if "e" in locals() and e:
                self._config = {}
            raise
        finally:
            self._logger.clear_log()

    def settings_is_initialized(self) -> bool:
        return bool(self._config)

    def reload(self) -> None:
        if not self._file_path:
            self._logger.error("🛑 Aucun fichier de configuration trouvée.")
            return

        self.load_configuration_file(self._file_path)

    def get(self, key: str, default: Any = None) -> Any:
        return self._config.get(key, default)

    def __getattr__(self, item: str) -> Any:
        if item in self._config:
            return self._config[item]
        else:
            self._logger.error(
                f"Le paramètre {item} n'existe pas dans la configuration."
            )
            return None

    def __setattr__(self, key: str, value: Any) -> None:
        if key in self.__slots__:
            super().__setattr__(key, value)
        else:
            self._logger.error("Impossible de modifier les configurations.")


if __name__ == "__main__":
    settings = Settings()
    if settings.settings_is_initialized():
        settings.logger.info(f"{settings.all_settings}")