"""Stamina cue broadcasts for combat strain visibility."""

from mudlib.commands.movement import send_nearby_message
from mudlib.entity import Entity


async def check_stamina_cues(entity: Entity) -> None:
    """Broadcast stamina strain messages when thresholds are crossed.

    Thresholds (escalating severity):
    - Below 75%: breathing heavily
    - Below 50%: drenched in sweat
    - Below 25%: visibly shaking from exhaustion
    - Below 10%: can barely stand

    Each threshold triggers only ONCE per descent. Track the last triggered
    threshold to prevent spam.

    Args:
        entity: The entity to check stamina for
    """
    if entity.max_stamina == 0:
        return

    stamina_pct = entity.stamina / entity.max_stamina

    # Define thresholds from lowest to highest (check in reverse order)
    thresholds = [
        (
            0.10,
            "You can barely stand.",
            f"{entity.name} can barely stand.",
        ),
        (
            0.25,
            "You're visibly shaking from exhaustion.",
            f"{entity.name} is visibly shaking from exhaustion.",
        ),
        (
            0.50,
            "You're drenched in sweat.",
            f"{entity.name} is drenched in sweat.",
        ),
        (
            0.75,
            "You're breathing heavily.",
            f"{entity.name} is breathing heavily.",
        ),
    ]

    # Find the current threshold (highest threshold we're below)
    current_threshold = None
    self_msg = None
    nearby_msg = None

    for threshold, self_text, nearby_text in thresholds:
        if stamina_pct < threshold:
            current_threshold = threshold
            self_msg = self_text
            nearby_msg = nearby_text
            break

    # If we found a threshold and it's lower than the last triggered one
    if current_threshold is not None and current_threshold < entity._last_stamina_cue:
        # Send self-directed message
        await entity.send(f"{self_msg}\r\n")

        # Broadcast to nearby players (only if entity has a location)
        if entity.location is not None:
            await send_nearby_message(entity, entity.x, entity.y, f"{nearby_msg}\r\n")

        # Update tracking
        entity._last_stamina_cue = current_threshold
