from typing import Optional
from slack_bot.shell.manager import ShellManager
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

def execute_shell(command: str, channel_id: str, timeout: Optional[float] = 2.0) -> str:
    """
    Executes a shell command in a persistent session for the given channel.
    
    Args:
        command: The shell command to execute.
        channel_id: The Slack channel ID.
        timeout: Max time to wait for output (default 2.0s). Set higher for long running commands.
        
    Returns:
        The output of the command.
    """
    manager = ShellManager()
    try:
        session = manager.get_session(channel_id)
        
        # logger.info(f"Executing shell command in {channel_id}: {command}")
        output = session.execute(command, timeout=timeout)
        
        # Post-process output for better display
        if not output.strip():
            return "(No output)"
            
        return output
    except Exception as e:
        logger.error(f"Shell execution failed: {e}", exc_info=True)
        return f"Error executing command: {str(e)}"
