"""Step 1: Preflight checks — OS, architecture, disk, RAM, root."""

from ..base_step import BaseStep


class PreflightStep(BaseStep):
    name = "Preflight Checks"
    description = "Verify OS, architecture, disk space, RAM, and root access"
    timeout = 30
    allow_retry = False

    def command(self) -> str:
        return (
            "set -e\n"
            "echo '--- Operating System ---'\n"
            ". /etc/os-release && echo \"$PRETTY_NAME\"\n"
            "echo ''\n"
            "echo '--- Architecture ---'\n"
            "ARCH=$(uname -m)\n"
            "echo \"$ARCH\"\n"
            "if [ \"$ARCH\" != \"x86_64\" ] && [ \"$ARCH\" != \"aarch64\" ]; then\n"
            "  echo \"ERROR: Unsupported architecture: $ARCH\" >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo ''\n"
            "echo '--- Disk Space ---'\n"
            "AVAIL=$(df --output=avail -BG / | tail -1 | tr -d ' G')\n"
            "echo \"Available: ${AVAIL}GB\"\n"
            "if [ \"$AVAIL\" -lt 2 ]; then\n"
            "  echo \"ERROR: Need >= 2GB free disk space (have ${AVAIL}GB)\" >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo ''\n"
            "echo '--- Memory ---'\n"
            "free -h | head -2\n"
            "TOTAL_MB=$(free -m | awk '/^Mem:/{print $2}')\n"
            "if [ \"$TOTAL_MB\" -lt 512 ]; then\n"
            "  echo \"ERROR: Need >= 512MB RAM (have ${TOTAL_MB}MB)\" >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo ''\n"
            "echo '--- User ---'\n"
            "if [ \"$(id -u)\" -ne 0 ]; then\n"
            "  echo 'ERROR: Must run as root' >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo \"Running as: $(whoami)\"\n"
            "echo ''\n"
            "echo '--- Package Manager ---'\n"
            "if command -v apt-get >/dev/null 2>&1; then\n"
            "  echo 'apt-get: available'\n"
            "else\n"
            "  echo 'WARNING: apt-get not found. This installer requires Ubuntu/Debian.' >&2\n"
            "  echo 'Steps that install packages (Node.js, npm) may fail on this system.' >&2\n"
            "fi\n"
            "echo ''\n"
            "echo 'All preflight checks passed.'"
        )
