import yaml
import os
import time
import threading

class ConfigLoader:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls, config_file_path):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance.config_file_path = config_file_path
                cls._instance.config = None
                cls._instance._load_config()
                cls._instance._start_auto_reload()
            return cls._instance

    def _load_config(self):
        try:
            with open(self.config_file_path, 'r') as f:
                self.config = yaml.safe_load(f)
            print(f"Configuration loaded from {self.config_file_path}")
        except FileNotFoundError:
            print(f"Error: Configuration file not found at {self.config_file_path}")
            self.config = {}
        except yaml.YAMLError as e:
            print(f"Error parsing YAML file: {e}")
            self.config = {}

    def get_config(self):
        return self.config

    def _auto_reload(self):
        while True:
            time.sleep(self.config.get('refresh_interval', 60))
            self._load_config()

    def _start_auto_reload(self):
        if self.config.get('refresh_interval', 0) > 0:
            reload_thread = threading.Thread(target=self._auto_reload, daemon=True)
            reload_thread.start()


if __name__ == '__main__':
    # Example Usage
    config_path = 'aiva/config/threshold_adjustment_config.yaml'
    config_loader = ConfigLoader(config_path)

    # Simulate re-loading the configuration after a delay
    time.sleep(5)
    config = config_loader.get_config()
    print("Current config:", config)

    time.sleep(5)
    config = config_loader.get_config()
    print("Current config:", config)
