"""Step 12: Create and enable systemd service units for OpenClaw."""

from ..base_step import BaseStep


class SystemdStep(BaseStep):
    name = "Systemd Services"
    description = "Create and enable systemd units for OpenClaw"
    timeout = 60
    allow_retry = True
    max_retries = 1

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

        if not shutil.which("systemctl"):
            return False, "systemctl not found — systemd is required"
        return True, ""

    def command(self) -> str:
        return (
            "set -e\n"
            "# Stop any gateway process started during step 11 to avoid port conflict\n"
            "echo 'Stopping any running gateway process...'\n"
            "pkill -f 'openclaw.*gateway' 2>/dev/null || true\n"
            "sleep 2\n"
            "echo ''\n"
            "echo 'Creating systemd service units...'\n"
            "openclaw service install --dir /etc/openclaw 2>&1\n"
            "echo ''\n"
            "echo 'Reloading systemd daemon...'\n"
            "systemctl daemon-reload\n"
            "echo ''\n"
            "echo 'Enabling OpenClaw services...'\n"
            "systemctl enable openclaw.service 2>&1\n"
            "systemctl enable openclaw-gateway.service 2>&1\n"
            "echo ''\n"
            "echo 'Starting services...'\n"
            "systemctl start openclaw.service 2>&1\n"
            "systemctl start openclaw-gateway.service 2>&1\n"
            "echo ''\n"
            "echo 'Service status:'\n"
            "systemctl --no-pager status openclaw.service || true\n"
            "echo ''\n"
            "echo 'Systemd services configured and started.'"
        )
