"""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:
        # Write service files manually — openclaw service install / daemon
        # install don't work for root (CLAUDE.md gotcha #13).
        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"
            "\n"
            "# Find openclaw binary location\n"
            "OPENCLAW_BIN=$(which openclaw)\n"
            "echo \"OpenClaw binary: $OPENCLAW_BIN\"\n"
            "echo ''\n"
            "\n"
            "# Write gateway service file\n"
            "echo 'Creating openclaw-gateway.service ...'\n"
            "cat > /etc/systemd/system/openclaw-gateway.service << SVCEOF\n"
            "[Unit]\n"
            "Description=OpenClaw API Gateway\n"
            "After=network.target\n"
            "\n"
            "[Service]\n"
            "Type=simple\n"
            "ExecStart=$OPENCLAW_BIN gateway start --dir /etc/openclaw\n"
            "Restart=on-failure\n"
            "RestartSec=5\n"
            "Environment=NODE_ENV=production\n"
            "WorkingDirectory=/etc/openclaw\n"
            "\n"
            "[Install]\n"
            "WantedBy=multi-user.target\n"
            "SVCEOF\n"
            "echo '  -> /etc/systemd/system/openclaw-gateway.service'\n"
            "echo ''\n"
            "\n"
            "echo 'Reloading systemd daemon...'\n"
            "systemctl daemon-reload\n"
            "echo ''\n"
            "echo 'Enabling OpenClaw gateway...'\n"
            "systemctl enable openclaw-gateway.service 2>&1\n"
            "echo ''\n"
            "echo 'Starting gateway service...'\n"
            "systemctl start openclaw-gateway.service 2>&1\n"
            "echo ''\n"
            "echo 'Service status:'\n"
            "systemctl --no-pager status openclaw-gateway.service || true\n"
            "echo ''\n"
            "echo 'Systemd service configured and started.'"
        )
