"""Environment variable command"""

from .base import BuiltinCommand
from diona.project.environment import get_environment_manager


class EnvCommand(BuiltinCommand):
    """Environment variable management command"""
    name = "env"
    description = "Manage environment variables"
    
    def execute(self, args):
        """Execute environment command
        
        Args:
            args: Command arguments
                - set <key> <value>: Set an environment variable
                - get <key>: Get an environment variable
                - list: List all environment variables
                - remove <key>: Remove an environment variable
                - clear: Clear all environment variables
        """
        if not args:
            self._print_help()
            return False
        
        env_mgr = get_environment_manager()
        action = args[0] if args else None
        
        if action == "set":
            if len(args) < 3:
                print("Usage: /env set <key> <value>")
                return False
            key, value = args[1], args[2]
            env_mgr.set(key, value)
            print(f"Environment variable '{key}' set to '{value}'")
        
        elif action == "get":
            if len(args) < 2:
                print("Usage: /env get <key>")
                return False
            key = args[1]
            value = env_mgr.get(key)
            if value is not None:
                print(f"{key}={value}")
            else:
                print(f"Environment variable '{key}' not found")
        
        elif action == "list":
            env_vars = env_mgr.list_all()
            if env_vars:
                print("Environment variables:")
                for key, value in env_vars.items():
                    print(f"  {key}={value}")
            else:
                print("No environment variables set")
        
        elif action == "remove":
            if len(args) < 2:
                print("Usage: /env remove <key>")
                return False
            key = args[1]
            if env_mgr.remove(key):
                print(f"Environment variable '{key}' removed")
            else:
                print(f"Environment variable '{key}' not found")
        
        elif action == "clear":
            env_mgr.clear()
            print("All environment variables cleared")
        
        else:
            self._print_help()
        
        return False
    
    def _print_help(self):
        """Print help message"""
        print("Usage: /env <action> [arguments]")
        print("Actions:")
        print("  set <key> <value>  - Set an environment variable")
        print("  get <key>          - Get an environment variable")
        print("  list               - List all environment variables")
        print("  remove <key>       - Remove an environment variable")
        print("  clear              - Clear all environment variables")


env_command = EnvCommand()
