"""Snap neck finisher command."""

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

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
    """
    # Parse target
    target_name = args.strip()
    if not target_name:
        await player.send("Snap whose neck?\r\n")
        return

    # Must be used during an active encounter.
    encounter = get_encounter(player)
    if encounter is None:
        await player.send("You're not in combat.\r\n")
        return

    # Find target on this tile.
    from mudlib.targeting import find_entity_on_tile

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

    if target is player:
        await player.send("You can't do that to yourself.\r\n")
        return

    # Snap neck can only target your current opponent.
    if target not in (encounter.attacker, encounter.defender):
        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 isinstance(target, Player):
        send_char_vitals(target)

    # Award kill/death stats on explicit finishers only.
    player.kills += 1
    if isinstance(target, Player):
        target.deaths += 1
    elif isinstance(target, Mob):
        player.mob_kills[target.name] = player.mob_kills.get(target.name, 0) + 1
        # Check for newly unlocked moves after a finisher kill.
        from mudlib.combat.commands import combat_moves
        from mudlib.combat.unlock import check_unlocks

        newly_unlocked = check_unlocks(player, combat_moves)
        for move_name in newly_unlocked:
            await player.send(f"You have learned {move_name}!\r\n")

    # Handle mob corpse/death
    if isinstance(target, Mob):
        from mudlib.corpse import create_corpse
        from mudlib.mobs import despawn_mob, mob_templates
        from mudlib.zone import Zone

        zone = target.location
        if isinstance(zone, Zone):
            template = mob_templates.get(target.name)
            loot_table = template.loot if template else None
            create_corpse(target, zone, loot_table=loot_table)
        else:
            despawn_mob(target)

    # Pop combat mode from both entities.
    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)",
    )
)
