from __future__ import annotations

from pathlib import Path

from ai_orchestrator.runtime.docker_sandbox import DockerSandbox
from ai_orchestrator.schemas.tool_result import ToolResult
from ai_orchestrator.schemas.workflow_models import StructuredError
from ai_orchestrator.tools.error_parser import extract_structured_errors


class ShellRunner:
    def __init__(self, sandbox: DockerSandbox, safety_guardrails=None) -> None:
        self.sandbox = sandbox
        self.safety_guardrails = safety_guardrails

    async def run_shell(
        self,
        *,
        command: str,
        repo_path: Path,
        timeout_seconds: int | None = None,
        use_docker: bool | None = None,
        sandbox_image: str | None = None,
    ) -> ToolResult:
        if self.safety_guardrails is not None:
            decision = self.safety_guardrails.validate_shell_command(command)
            if not bool(decision["allowed"]):
                return ToolResult(
                    success=False,
                    stderr=str(decision["reason"]),
                    command=command,
                    structured_errors=[
                        StructuredError(
                            error_type="CommandBlocked",
                            message=str(decision["reason"]),
                        )
                    ],
                )

        result = await self.sandbox.run_command(
            command=command,
            repo_path=repo_path,
            timeout_seconds=timeout_seconds,
            use_docker=use_docker,
            sandbox_image=sandbox_image,
        )
        result.structured_errors = extract_structured_errors(result.stdout, result.stderr)
        return result
