"""Behavior for the Littlehand robot."""

from __future__ import annotations

from typing import Callable

from ...core.behavior import ActionContext, RobotBehavior
from .actions import LITTLEHAND_ACTIONS


class LittlehandBehavior(RobotBehavior):
    """Littlehand behavior using the default pick-and-place actions."""

    ACTIONS = LITTLEHAND_ACTIONS

    def action_handlers(self) -> dict[str, Callable[[ActionContext], bool]]:
        return {
            "subir": self.action_subir,
            "bajar": self.action_bajar,
            "ir": self.action_ir,
            "tomar": self.action_tomar,
            "soltar": self.action_soltar,
            "reiniciar": self.action_reiniciar,
        }

    def action_subir(self, ctx: ActionContext) -> bool:
        """Move up by step_mm."""
        target_z = ctx.pose[2] + self.config.step_mm
        return self._queue_move(ctx, ctx.pose[0], ctx.pose[1], target_z)

    def action_bajar(self, ctx: ActionContext) -> bool:
        """Move down by step_mm."""
        target_z = ctx.pose[2] - self.config.step_mm
        return self._queue_move(ctx, ctx.pose[0], ctx.pose[1], target_z)

    def action_ir(self, ctx: ActionContext) -> bool:
        """Move to object X/Y while keeping current Z."""
        if ctx.pose is None or ctx.target is None:
            return False
        pos = ctx.target.position_mm
        return self._queue_move(ctx, pos[0], pos[1], ctx.pose[2])

    def action_tomar(self, ctx: ActionContext) -> bool:
        """Activate tool (low-level grab)."""
        self._queue_steps(ctx, self.robot_adapter.grab())
        return True

    def action_soltar(self, ctx: ActionContext) -> bool:
        """Deactivate tool (low-level release)."""
        self._queue_steps(ctx, self.robot_adapter.release())
        return True

    def action_reiniciar(self, ctx: ActionContext) -> bool:
        """Reset: release tool, move home, clear objects."""
        self._queue_steps(ctx, self.robot_adapter.reset_tool())
        self._queue_steps(ctx, self.robot_adapter.move(ctx.home_pose))
        ctx.scene.clear_detected()
        return True
