"""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 = 90
    allow_retry = True
    max_retries = 2

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

        if not shutil.which("systemctl"):
            return False, "systemctl not found — systemd is required"
        if not shutil.which("openclaw"):
            return False, "openclaw binary not found — step 3 must complete first"
        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"
            "\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"
            "# Resolve openclaw binary path\n"
            "OPENCLAW_BIN=$(which openclaw)\n"
            "echo \"OpenClaw binary: $OPENCLAW_BIN\"\n"
            "if [ ! -x \"$OPENCLAW_BIN\" ]; then\n"
            "  echo 'ERROR: openclaw binary not found or not executable' >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo ''\n"
            "\n"
            "# Load env vars so gateway can find its config\n"
            "if [ -f /etc/openclaw/env ]; then\n"
            "  set -a\n"
            "  . /etc/openclaw/env\n"
            "  set +a\n"
            "  echo 'Loaded /etc/openclaw/env'\n"
            "fi\n"
            "echo ''\n"
            "\n"
            "# --- openclaw-gateway.service ---\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"
            "EnvironmentFile=-/etc/openclaw/env\n"
            "Environment=NODE_ENV=production\n"
            "WorkingDirectory=/etc/openclaw\n"
            "\n"
            "[Install]\n"
            "WantedBy=multi-user.target\n"
            "SVCEOF\n"
            "\n"
            "# Verify file was written\n"
            "if [ ! -f /etc/systemd/system/openclaw-gateway.service ]; then\n"
            "  echo 'ERROR: failed to write openclaw-gateway.service' >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo '  -> /etc/systemd/system/openclaw-gateway.service'\n"
            "echo ''\n"
            "\n"
            "# --- openclaw.service (main worker) ---\n"
            "echo 'Creating openclaw.service ...'\n"
            "cat > /etc/systemd/system/openclaw.service << SVCEOF\n"
            "[Unit]\n"
            "Description=OpenClaw Service\n"
            "After=network.target\n"
            "\n"
            "[Service]\n"
            "Type=simple\n"
            "ExecStart=$OPENCLAW_BIN start --dir /etc/openclaw\n"
            "Restart=on-failure\n"
            "RestartSec=5\n"
            "EnvironmentFile=-/etc/openclaw/env\n"
            "Environment=NODE_ENV=production\n"
            "WorkingDirectory=/etc/openclaw\n"
            "\n"
            "[Install]\n"
            "WantedBy=multi-user.target\n"
            "SVCEOF\n"
            "\n"
            "if [ ! -f /etc/systemd/system/openclaw.service ]; then\n"
            "  echo 'ERROR: failed to write openclaw.service' >&2\n"
            "  exit 1\n"
            "fi\n"
            "echo '  -> /etc/systemd/system/openclaw.service'\n"
            "echo ''\n"
            "\n"
            "# Reload and enable\n"
            "echo 'Reloading systemd daemon...'\n"
            "systemctl daemon-reload\n"
            "echo ''\n"
            "\n"
            "echo 'Enabling services...'\n"
            "systemctl enable openclaw.service 2>&1\n"
            "systemctl enable openclaw-gateway.service 2>&1\n"
            "echo ''\n"
            "\n"
            "# Start services — disable set -e so we can show diagnostic logs on failure\n"
            "set +e\n"
            "echo 'Starting openclaw.service ...'\n"
            "systemctl start openclaw.service 2>&1\n"
            "OC_RC=$?\n"
            "echo 'Starting openclaw-gateway.service ...'\n"
            "systemctl start openclaw-gateway.service 2>&1\n"
            "GW_RC=$?\n"
            "set -e\n"
            "echo ''\n"
            "\n"
            "# Show status regardless\n"
            "echo '--- Service Status ---'\n"
            "systemctl --no-pager status openclaw.service 2>&1 || true\n"
            "echo ''\n"
            "systemctl --no-pager status openclaw-gateway.service 2>&1 || true\n"
            "echo ''\n"
            "\n"
            "# If either failed, show journal logs for debugging\n"
            "if [ $OC_RC -ne 0 ] || [ $GW_RC -ne 0 ]; then\n"
            "  echo '--- Recent Logs ---'\n"
            "  journalctl -u openclaw.service -u openclaw-gateway.service "
            "--no-pager -n 20 2>&1 || true\n"
            "  echo ''\n"
            "  echo 'WARNING: One or both services failed to start.' >&2\n"
            "  echo 'Service files created — agent can diagnose from logs above.' >&2\n"
            "  exit 1\n"
            "fi\n"
            "\n"
            "echo 'Systemd services configured and started.'"
        )
