"""Read command for examining readable objects."""

from mudlib.commands import CommandDefinition, register
from mudlib.player import Player
from mudlib.thing import Thing


def _find_readable(player: Player, name: str) -> Thing | None:
    """Find a readable thing by name or alias in inventory or on ground."""
    name_lower = name.lower()

    # Check inventory first
    for obj in player.contents:
        if not isinstance(obj, Thing):
            continue
        if obj.name.lower() == name_lower:
            return obj
        if any(a.lower() == name_lower for a in obj.aliases):
            return obj

    # Check ground at player's position
    if player.location is not None:
        from mudlib.zone import Zone

        if isinstance(player.location, Zone):
            for obj in player.location.contents_at(player.x, player.y):
                if not isinstance(obj, Thing):
                    continue
                if obj.name.lower() == name_lower:
                    return obj
                if any(a.lower() == name_lower for a in obj.aliases):
                    return obj

    return None


async def cmd_read(player: Player, args: str) -> None:
    """Read a readable object."""
    target_name = args.strip()
    if not target_name:
        await player.send("Read what?\r\n")
        return

    thing = _find_readable(player, target_name)
    if thing is None:
        await player.send("You don't see that here.\r\n")
        return

    if not thing.readable_text:
        await player.send("There's nothing to read on that.\r\n")
        return

    await player.send(f"You read the {thing.name}:\r\n{thing.readable_text}\r\n")


register(CommandDefinition("read", cmd_read, help="Read a readable object"))
