"""Step 2: Node.js v22+ — check, install, or upgrade."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult

REQUIRED_NODE = 22


class NodejsStep(BaseStep):
    STEP_NUM = 2
    STEP_NAME = "Node.js"

    async def run(self) -> StepResult:
        # Check existing
        ver_str = await self.cmd_output("node --version 2>/dev/null")
        if ver_str:
            try:
                major = int(ver_str.lstrip("v").split(".")[0])
                if major >= REQUIRED_NODE:
                    npm_ver = await self.cmd_output("npm --version 2>/dev/null")
                    self.ok(f"Node.js {ver_str} — npm {npm_ver}")
                    self.state.node_version = ver_str
                    return StepResult(True)
                else:
                    self.warn(f"Node.js v{major} found — upgrading to v{REQUIRED_NODE}")
            except ValueError:
                self.warn(f"Cannot parse Node version: {ver_str}")
        else:
            self.info("Node.js not found")

        # Install
        self.info(f"Installing Node.js {REQUIRED_NODE}...")
        await self.run_cmd(
            f"curl -fsSL https://deb.nodesource.com/setup_{REQUIRED_NODE}.x | {self.sudo('bash -')} >/dev/null 2>&1"
        )
        await self.run_cmd(self.sudo("apt-get install -y -qq nodejs"))

        # Verify
        ver_str = await self.cmd_output("node --version 2>/dev/null")
        if not ver_str:
            return StepResult(False, message="Node.js installation failed")

        try:
            major = int(ver_str.lstrip("v").split(".")[0])
            if major < REQUIRED_NODE:
                return StepResult(False, message=f"Node.js upgrade failed — got v{major}")
        except ValueError:
            return StepResult(False, message=f"Cannot verify Node version: {ver_str}")

        npm_ver = await self.cmd_output("npm --version 2>/dev/null")
        self.ok(f"Node.js {ver_str} — npm {npm_ver}")
        self.state.node_version = ver_str
        return StepResult(True)
