import os
from typing import Dict, Optional, Any


class EnvironmentManager:
    """Environment variable management module implemented as a singleton."""
    
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(EnvironmentManager, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        """Initialize the environment manager."""
        self._env_vars: Dict[str, str] = {}
    
    def set(self, key: str, value: str) -> None:
        """
        Set an environment variable.
        
        Args:
            key: The environment variable name
            value: The environment variable value
            
        Rules:
            1. Store in the internal dictionary
            2. Set to system temporary environment variables
        """
        self._env_vars[key] = value
        os.environ[key] = value
    
    def get(self, key: str) -> Optional[str]:
        """
        Get an environment variable.
        
        Args:
            key: The environment variable name
            
        Returns:
            The environment variable value or None if not found
            
        Rules:
            1. First check internal dictionary
            2. If not found, check system environment variables
            3. If found in system, store in dictionary and return
            4. If not found in either, return None
        """
        # First check internal dictionary
        if key in self._env_vars:
            return self._env_vars[key]
        
        # Then check system environment variables
        system_value = os.environ.get(key)
        if system_value is not None:
            # Store in dictionary for future access
            self._env_vars[key] = system_value
            return system_value
        
        # Not found in either
        return None
    
    def list_all(self) -> Dict[str, str]:
        """
        List all environment variables.
        
        Returns:
            Dictionary containing all environment variables from internal storage
            
        Rules:
            Return only variables from internal dictionary (not from system)
        """
        return self._env_vars.copy()
    
    def remove(self, key: str) -> bool:
        """
        Remove an environment variable.
        
        Args:
            key: The environment variable name to remove
            
        Returns:
            True if the variable was removed, False if it didn't exist
        """
        removed_from_dict = False
        removed_from_system = False
        
        # Remove from internal dictionary
        if key in self._env_vars:
            del self._env_vars[key]
            removed_from_dict = True
        
        # Remove from system environment variables
        if key in os.environ:
            del os.environ[key]
            removed_from_system = True
        
        return removed_from_dict or removed_from_system
    
    def clear(self) -> None:
        """Clear all environment variables from internal storage."""
        self._env_vars.clear()


def get_environment_manager() -> EnvironmentManager:
    """Get the singleton environment manager instance."""
    return EnvironmentManager()