"""Snap neck finisher command."""

from mudlib.combat.engine import end_encounter, get_encounter
from mudlib.commands import CommandDefinition, register
from mudlib.player import Player, players

DEATH_PL = -100.0


async def cmd_snap_neck(player: Player, args: str) -> None:
    """Snap the neck of an unconscious target.

    Args:
        player: The player executing the command
        args: Target name
    """
    # Get encounter
    encounter = get_encounter(player)
    if encounter is None:
        await player.send("You're not in combat.\r\n")
        return

    # Parse target
    target_name = args.strip()
    if not target_name:
        await player.send("Snap whose neck?\r\n")
        return

    # Find target
    target = players.get(target_name)
    if target is None and player.location is not None:
        from mudlib.mobs import get_nearby_mob
        from mudlib.zone import Zone

        if isinstance(player.location, Zone):
            target = get_nearby_mob(target_name, player.x, player.y, player.location)

    if target is None:
        await player.send(f"You don't see {target_name} here.\r\n")
        return

    # Verify target is in the encounter
    if encounter.attacker is not player and encounter.defender is not player:
        await player.send("You're not in combat with that target.\r\n")
        return

    if encounter.attacker is not target and encounter.defender is not target:
        await player.send("You're not in combat with that target.\r\n")
        return

    # Check if target is unconscious
    if target.posture != "unconscious":
        await player.send(f"{target.name} is not unconscious.\r\n")
        return

    # Execute the finisher
    target.pl = DEATH_PL

    # Send dramatic messages
    await player.send(f"You snap {target.name}'s neck!\r\n")
    await target.send(f"{player.name} snaps your neck!\r\n")

    # Send GMCP vitals update (only for Players)
    from mudlib.entity import Mob
    from mudlib.gmcp import send_char_vitals

    if not isinstance(target, Mob):
        send_char_vitals(target)

    # Handle mob despawn
    if isinstance(target, Mob):
        from mudlib.mobs import despawn_mob

        despawn_mob(target)

    # Pop combat mode from both entities if they're Players
    from mudlib.gmcp import send_char_status

    if isinstance(player, Player) and player.mode == "combat":
        player.mode_stack.pop()
        send_char_status(player)

    if isinstance(target, Player) and target.mode == "combat":
        target.mode_stack.pop()
        send_char_status(target)

    # End the encounter
    end_encounter(encounter)


# Register command
register(
    CommandDefinition(
        name="snapneck",
        handler=cmd_snap_neck,
        aliases=["sn"],
        mode="*",
        help="Snap the neck of an unconscious opponent (instant kill)",
    )
)
