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}")