from mudlib.commands import CommandDefinition, register
from mudlib.player import Player
from mudlib.verbs import find_object


async def cmd_use(player: Player, args: str) -> None:
    """Use an object, optionally on a target."""
    args = args.strip()

    if not args:
        await player.send("Use what?\r\n")
        return

    # Parse "use X on Y" syntax
    if " on " in args:
        parts = args.split(" on ", 1)
        object_name = parts[0].strip()
        target_args = parts[1].strip()
    else:
        object_name = args
        target_args = ""

    # Find the object
    obj = find_object(object_name, player)
    if not obj:
        await player.send("You don't see that here.\r\n")
        return

    # Check if object has use verb
    if not obj.has_verb("use"):
        await player.send("You can't use that.\r\n")
        return

    # Call the use verb
    use_handler = obj.get_verb("use")
    assert use_handler is not None  # has_verb checked above
    await use_handler(player, target_args)


register(CommandDefinition("use", cmd_use, mode="*"))
