"""Step 2: Install Node.js 22.x LTS via NodeSource.

OpenClaw requires Node.js >= 22.12.0 (checked in its CLI entry point).
"""

from ..base_step import BaseStep


class NodejsStep(BaseStep):
    name = "Node.js Runtime"
    description = "Install or verify Node.js >= 22.x LTS"
    timeout = 300
    allow_retry = True
    max_retries = 2

    def validate_preconditions(self) -> tuple[bool, str]:
        import shutil

        # If Node.js is already installed, skip the apt-get requirement
        if shutil.which("node"):
            return True, ""
        # Need apt-get to install Node.js
        if not shutil.which("apt-get"):
            return (
                False,
                "Node.js not found and apt-get unavailable. "
                "EasyClaw requires Ubuntu/Debian for automatic Node.js installation. "
                "Install Node.js 22.x manually and re-run.",
            )
        return True, ""

    def command(self) -> str:
        return (
            "set -e\n"
            "echo 'Checking for Node.js...'\n"
            "if command -v node >/dev/null 2>&1; then\n"
            "  NODE_VER=$(node -v)\n"
            "  echo \"Found Node.js $NODE_VER\"\n"
            "  MAJOR=$(echo \"$NODE_VER\" | sed 's/v//' | cut -d. -f1)\n"
            "  if [ \"$MAJOR\" -ge 22 ]; then\n"
            "    echo \"Node.js version OK (>= 22).\"\n"
            "    echo \"npm: $(npm -v)\"\n"
            "    exit 0\n"
            "  fi\n"
            "  echo 'Node.js too old (OpenClaw requires >= 22.12.0), upgrading...'\n"
            "fi\n"
            "echo 'Installing Node.js 22.x LTS via NodeSource...'\n"
            "apt-get update -qq\n"
            "apt-get install -y -qq ca-certificates curl gnupg\n"
            "mkdir -p /etc/apt/keyrings\n"
            "curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key "
            "| gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg --yes\n"
            "echo 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] "
            "https://deb.nodesource.com/node_22.x nodistro main' "
            "> /etc/apt/sources.list.d/nodesource.list\n"
            "apt-get update -qq\n"
            "apt-get install -y nodejs\n"
            "echo \"Installed: $(node -v)\"\n"
            "echo \"npm: $(npm -v)\"\n"
            "echo 'Node.js installation complete.'"
        )
