"""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")
            self.panel.log_raw("")
            self.panel.log_raw("[bold yellow]═══ IMPORTANT: WhatsApp QR Pairing Required ═══[/bold yellow]")
            self.panel.log_raw("WhatsApp requires an interactive terminal to scan the QR code.")
            self.panel.log_raw("SSH into your server and run:")
            self.panel.log_raw("")
            ip = self.state.vps_ip or "YOUR_VPS_IP"
            self.panel.log_raw(f"  [bold]ssh root@{ip}[/bold]")
            self.panel.log_raw("  [bold]openclaw channels login --channel whatsapp[/bold]")
            self.panel.log_raw("")
            self.panel.log_raw("Then scan the QR code with your phone:")
            self.panel.log_raw("WhatsApp > Settings > Linked Devices > Link a Device")
            self.panel.log_raw("[bold yellow]═══════════════════════════════════════════════[/bold yellow]")

        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)
