"""Step 14: Configure messaging channel."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult


class ChannelStep(BaseStep):
    STEP_NUM = 14
    STEP_NAME = "Channel"

    async def run(self) -> StepResult:
        ch = self.state.channel

        if ch == "none":
            self.info("No channel configured — add one later: openclaw channels add --channel <name>")
            return StepResult(True)

        if ch == "whatsapp":
            await self.run_cmd("openclaw plugins enable whatsapp 2>/dev/null || true")
            await self.run_cmd("openclaw channels add --channel whatsapp 2>/dev/null || true")
            await self.run_cmd("openclaw config set channels.whatsapp.dmPolicy pairing 2>/dev/null || true")
            await self.run_cmd(self.sudo("systemctl restart openclaw-gateway"))
            self.ok("WhatsApp configured with pairing DM policy")
            ip = self.state.vps_ip or "YOUR_VPS_IP"
            self.warn("WhatsApp QR Pairing Required — SSH in and run: openclaw channels login --channel whatsapp")
            self.info(f"  ssh root@{ip}")
            self.info("  openclaw channels login --channel whatsapp")
            self.info("Then scan with: WhatsApp > Settings > Linked Devices > Link a Device")

        elif ch == "telegram":
            await self.run_cmd("openclaw config set channels.telegram.dmPolicy pairing 2>/dev/null || true")
            await self.run_cmd(self.sudo("systemctl restart openclaw-gateway"))
            self.ok("Telegram configured")

        elif ch == "discord":
            await self.run_cmd("openclaw config set channels.discord.dmPolicy pairing 2>/dev/null || true")
            await self.run_cmd(self.sudo("systemctl restart openclaw-gateway"))
            self.ok("Discord configured")

        return StepResult(True)
