"""Step 7: Create openclaw.json configuration file."""

from __future__ import annotations

import json

from easyclaw_tui.steps.base import BaseStep, StepResult


class WriteConfigStep(BaseStep):
    STEP_NUM = 7
    STEP_NAME = "Write Config"

    async def run(self) -> StepResult:
        await self.run_cmd("mkdir -p ~/.openclaw")

        config = {
            "gateway": {
                "mode": "local",
                "bind": self.state.bind,
                "auth": {"token": self.state.gateway_token},
            },
            "agents": {
                "defaults": {
                    "model": {
                        "primary": self.state.model_path,
                        "fallbacks": [self.state.fallback_path],
                    },
                    "subagents": {
                        "model": self.state.fallback_path,
                        "thinking": "low",
                        "maxConcurrent": 4,
                    },
                    "heartbeat": {"every": "30m"},
                    "memorySearch": {
                        "enabled": self.state.memory_enabled,
                        "provider": "openai",
                    },
                }
            },
            "session": {
                "scope": "per-sender",
                "resetTriggers": ["/new", "/reset"],
                "reset": {"mode": "daily", "atHour": 4},
            },
            "tools": {
                "profile": "full",
                "exec": {"security": "allowlist"},
            },
            "security": {
                "configRedaction": True,
                "obfuscatedCommandPolicy": "prompt",
            },
        }

        # Channel config
        ch = self.state.channel
        if ch == "whatsapp":
            config["channels"] = {
                "whatsapp": {"dmPolicy": "pairing", "accounts": {"default": {}}}
            }
            config["plugins"] = {"whatsapp": {"enabled": True}}
        elif ch == "telegram" and self.state.telegram_token:
            config["channels"] = {
                "telegram": {
                    "enabled": True,
                    "botToken": self.state.telegram_token,
                    "dmPolicy": "pairing",
                }
            }
        elif ch == "discord" and self.state.discord_token:
            config["channels"] = {
                "discord": {
                    "enabled": True,
                    "botToken": self.state.discord_token,
                    "dmPolicy": "pairing",
                }
            }

        config_json = json.dumps(config, indent=2)

        # Write via shell to handle ~ expansion
        # Escape for bash
        escaped = config_json.replace("'", "'\\''")
        rc, _, err = await self.run_cmd(f"echo '{escaped}' > ~/.openclaw/openclaw.json")
        if rc != 0:
            return StepResult(False, message=f"Failed to write config: {err}")

        self.ok("Config written to ~/.openclaw/openclaw.json")
        return StepResult(True)
