"""Step 8: Set up environment variables for OpenClaw."""

from ..base_step import BaseStep
from ...constants import OPENCLAW_FREE_KEY


class EnvVarsStep(BaseStep):
    name = "Environment Variables"
    description = "Configure environment variables in /etc/openclaw/env"
    timeout = 30
    allow_retry = False

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

        if not os.path.isdir("/etc/openclaw"):
            return False, "/etc/openclaw not found — run config wizard first"
        return True, ""

    def command(self) -> str:
        return (
            "set -e\n"
            "echo 'Setting up environment variables...'\n"
            "openclaw env setup --dir /etc/openclaw 2>&1\n"
            "echo ''\n"
            "# Ensure env file exists (create if openclaw env setup didn't)\n"
            "touch /etc/openclaw/env\n"
            "echo ''\n"
            "# Add free OpenRouter API key for OpenClaw LLM\n"
            "if ! grep -q 'OPENROUTER_API_KEY' /etc/openclaw/env 2>/dev/null; then\n"
            f"  echo 'OPENROUTER_API_KEY={OPENCLAW_FREE_KEY}' >> /etc/openclaw/env\n"
            "  echo 'Added free OpenRouter API key for OpenClaw LLM'\n"
            "else\n"
            "  echo 'OpenRouter API key already configured'\n"
            "fi\n"
            "echo ''\n"
            "if [ -f /etc/openclaw/env ]; then\n"
            "  echo 'Environment file:'\n"
            "  wc -l < /etc/openclaw/env | xargs -I{} echo '  {} variables configured'\n"
            "else\n"
            "  echo 'Warning: env file not found' >&2\n"
            "fi\n"
            "echo ''\n"
            "echo 'Environment setup complete.'"
        )
