import docker

class VMSandbox:
    def __init__(self, sandbox_id: str = "default-sandbox"):
        self.sandbox_id = sandbox_id
        self.mounts = {}
        try:
            self.client = docker.from_env()
            self.image = "ubuntu:latest"
        except Exception as e:
            self.client = None
            self.error = str(e)

    def mount_workspace(self, src: str, dest: str) -> None:
        """
        Prepares a workspace mount for the docker container.
        """
        self.mounts[dest] = src

    def execute_isolated(self, cmd: str) -> str:
        """
        Executes the command inside an ephemeral Docker container.
        """
        if not self.client:
            return f"Docker Error: {getattr(self, 'error', 'Client not initialized')}"
            
        try:
            # Pull image if not local
            try:
                self.client.images.get(self.image)
            except docker.errors.ImageNotFound:
                self.client.images.pull(self.image)

            volumes = {}
            for dest, src in self.mounts.items():
                volumes[src] = {'bind': dest, 'mode': 'rw'}
                
            container = self.client.containers.run(
                self.image,
                cmd,
                volumes=volumes,
                detach=False,
                remove=True, # Auto-destroy the container when done
                stdout=True,
                stderr=True
            )
            return container.decode('utf-8')
        except docker.errors.ContainerError as e:
            return f"Command Failed (Exit {e.exit_status}): {e.stderr.decode('utf-8')}"
        except Exception as e:
            return f"Sandbox Execution Failed: {e}"
