"""Sleep command for fastest stamina recovery."""

from mudlib.commands.movement import send_nearby_message
from mudlib.gmcp import send_char_status
from mudlib.player import Player


async def cmd_sleep(player: Player, args: str) -> None:
    """Toggle sleeping state for deep rest and fastest stamina recovery.

    Cannot sleep if stamina is already full or if in combat.
    While sleeping, players are blind to nearby events but recover stamina 3x faster.
    Broadcasts to nearby players when falling asleep and waking up.
    """
    # Check if in combat
    if player.mode == "combat":
        await player.send("You can't sleep in the middle of combat!\r\n")
        return

    # Check if stamina is already full
    if player.stamina >= player.max_stamina:
        await player.send("You're not tired.\r\n")
        return

    # Toggle sleeping state
    if player.sleeping:
        # Wake up
        player.sleeping = False
        player.resting = False
        send_char_status(player)
        await player.send("You wake up.\r\n")
        await send_nearby_message(
            player, player.x, player.y, f"{player.name} wakes up.\r\n"
        )
    else:
        # Fall asleep
        player.sleeping = True
        player.resting = True  # sleeping implies resting
        send_char_status(player)
        await player.send("You fall asleep.\r\n")
        await send_nearby_message(
            player, player.x, player.y, f"{player.name} falls asleep.\r\n"
        )
