"""Step 3: Install OpenClaw CLI."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult


class OpenClawStep(BaseStep):
    STEP_NUM = 3
    STEP_NAME = "OpenClaw"

    async def run(self) -> StepResult:
        # Check existing
        ver = await self.cmd_output("openclaw --version 2>/dev/null")
        if ver:
            self.ok(f"OpenClaw already installed: {ver}")
            self.state.openclaw_version = ver
            return StepResult(True)

        # Try official installer (fails on non-TTY, expected)
        self.info("Running OpenClaw installer...")
        await self.run_cmd("curl -fsSL https://openclaw.ai/install.sh 2>/dev/null | bash 2>&1 || true")

        if not await self.cmd_ok("command -v openclaw"):
            # Fallback: npm
            self.info("Installer wizard failed (expected). Installing via npm...")
            await self.run_cmd("npm install -g openclaw@latest 2>/dev/null")

        if not await self.cmd_ok("command -v openclaw"):
            return StepResult(False, message="OpenClaw installation failed")

        ver = await self.cmd_output("openclaw --version 2>/dev/null")
        self.ok(f"OpenClaw installed: {ver or 'unknown'}")
        self.state.openclaw_version = ver or "unknown"
        return StepResult(True)
