"""Quit command for disconnecting from the server."""

from mudlib.commands import CommandDefinition, register
from mudlib.player import Player, players
from mudlib.store import save_player


async def cmd_quit(player: Player, args: str) -> None:
    """Disconnect the player from the server.

    Args:
        player: The player executing the command
        args: Command arguments (unused)
    """
    # Block quitting during combat
    if player.mode == "combat":
        await player.send("You can't quit during combat!\r\n")
        return

    # Save player state before disconnecting
    save_player(player)

    player.writer.write("Goodbye!\r\n")
    await player.writer.drain()
    player.writer.close()

    # Remove from zone and player registry
    player.move_to(None)
    if player.name in players:
        del players[player.name]


# Register the quit command with its aliases
register(CommandDefinition("quit", cmd_quit, aliases=["q"], mode="*"))
