"""Vitals-Waechter: Tod und ungewollte Teleports erkennen.

Zwei Katastrophen-Signale:
  - hpPercentage == 0 → Charakter ist gestorben.
  - Koordinaten-Sprung > 40 SQM zwischen zwei Ticks → Respawn im Tempel
    oder GM-Teleport (beides: sofort anhalten und Beweis sichern).

Reise-Wegpunkte (Schiff/Teppich via NPC-Dialog) telefonieren legitim
weit — waehrend solcher Tasks wird der Sprung nicht gewertet.
"""
from src.gameplay.death import recordDeath, watchPlayersSeen
from src.gameplay.monitoring import logEvent, saveEventScreenshot

TELEPORT_SQMS = 40

_TRAVEL_TASKS = {
    'bbotSay', 'say', 'selectChatTab', 'bbotBuy', 'bbotWithdraw',
    'buyItem', 'openDoor',
}


def _halt(context, reason, details):
    context['ng_pause'] = True
    logEvent(reason, details)
    saveEventScreenshot(context.get('ng_screenshot'), reason)
    return context


def watchVitals(context):
    """Loop-Hook: haelt bei Tod oder ungewolltem Teleport sofort an."""
    if context['ng_pause']:
        return context
    context = watchPlayersSeen(context)
    hp = context['ng_statusBar'].get('hpPercentage')
    if hp == 0:
        # Der Todes-Manager klassifiziert (PK vs. Monster) und bergt.
        return recordDeath(context)

    coordinate = context['ng_radar']['coordinate']
    vitals = context.setdefault('ng_vitals', {})
    previous = vitals.get('coordinate')
    vitals['coordinate'] = coordinate
    if previous is None or coordinate is None:
        return context
    if any(value is None for value in previous) or any(
            value is None for value in coordinate):
        return context
    distance = (
        abs(coordinate[0] - previous[0])
        + abs(coordinate[1] - previous[1])
        + abs(coordinate[2] - previous[2]) * 15
    )
    if distance <= TELEPORT_SQMS:
        return context
    if context.get('ng_death'):
        # Respawn-Sprung waehrend der Bergung ist kein GM-Teleport.
        return context
    root = context['ng_tasksOrchestrator'].rootTask
    if root is not None and root.name in _TRAVEL_TASKS:
        return context
    return _halt(context, 'teleportDetected', {
        'from': list(previous), 'to': list(coordinate),
    })
