import subprocess
from .config import detect_host_repos_path


def run_in_sandbox(repo_name: str, host_repos_path: str, command: str, image: str = "node:22-alpine") -> tuple[bool, str]:
    """Spustí příkaz (např. npm install && npm run build) v izolovaném jednorázovém kontejneru."""
    real_host_repos = detect_host_repos_path(fallback=host_repos_path)
    host_repo_dir = f"{real_host_repos}/{repo_name}"
    docker_cmd = [
        "docker", "run", "--rm",
        "--user", "1000:1000",
        "--memory", "2g",
        "--cpus", "1.5",
        "-v", f"{host_repo_dir}:/workspace",
        "-w", "/workspace",
        image,
        "sh", "-c", command
    ]
    proc = subprocess.run(docker_cmd, capture_output=True, text=True, timeout=600)
    output = (proc.stdout + "\n" + proc.stderr).strip()
    return proc.returncode == 0, output
