"""Step 13: Connect EasyClaw MCP server via mcporter."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult

MCP_URL = "https://mcp.easyclaw.help/mcp"


class McpStep(BaseStep):
    STEP_NUM = 13
    STEP_NAME = "MCP"

    async def run(self) -> StepResult:
        if not self.state.api_key:
            self.warn("No API key — skipping MCP connection")
            return StepResult(success=True)

        self.info("Connecting EasyClaw MCP server...")
        await self.run_cmd(
            f'mcporter config add easyclaw "{MCP_URL}" '
            f'--header "Authorization=Bearer {self.state.api_key}" '
            f'--description "EasyClaw Foreman Knowledge Hub" '
            f"--scope home 2>/dev/null || true"
        )

        # Verify
        rc, out, _ = await self.run_cmd("mcporter list easyclaw 2>/dev/null")
        if "easyclaw" in out.lower():
            self.ok("EasyClaw MCP connected")
            # Count tools
            _, schema_out, _ = await self.run_cmd(
                "mcporter list easyclaw --schema 2>/dev/null | grep -c tool || echo '?'"
            )
            self.info(f"Tools available: {schema_out.strip()}")
        else:
            self.warn("Could not verify MCP connection — check: mcporter list easyclaw --schema")

        return StepResult(True)
