from typing import Any, Optional
import configparser
from ws_package.log.writer import LogWriter
from importlib.resources import files, as_file


logger = LogWriter.file(__name__)



class Config:
    def __init__(self):
        self.config = configparser.ConfigParser()
        # Resolve config file path - works in both dev and PyInstaller frozen apps
        config_resource = files('ws_package').joinpath("security.ini")
        with as_file(config_resource) as config_path:
            self.CONFIG_FILE = str(config_path)
        self.read()
    
    def read(self):
        try:
            logger.debug("Reading config file %s", self.CONFIG_FILE)
            self.config.read(self.CONFIG_FILE)
        except configparser.Error as e:
            raise RuntimeError(e)
    
    def __call__(self, value: Optional[Any] = None, section: Optional[str] = "Application", dtype: Optional[Any] = "str"):
        try:
            if dtype == "int":
                return self.config.getint(section, value)
            elif dtype == "bool":
                return self.config.getboolean(section, value)
            elif dtype == "float":
                return self.config.getfloat(section, value)
            else:
                return self.config.get(section, value)
        except (configparser.NoOptionError, configparser.NoSectionError, configparser.Error):
            logger.error("Cannot read %s of type %s in section %s from security file.", value, dtype, section)
            return None


Security_config = Config()
