from src.gameplay.targeting import ignoreCreatureTemporarily
from src.repositories.battleList.core import (
    getCreatures, getCreaturesHpPercentages, getFilledSlotsCount,
    isAttackingSomeCreature,
)
from src.repositories.battleList.extractors import getContent
from ...typings import Context


def _trackCreaturesHp(context: Context, content, creatures):
    """HP-Karte je Kreaturname + Killsteal-Erkennung.

    Faellt die HP einer Kreatur, die nicht unser Ziel ist, waehrend
    Spieler auf dem Screen sind, kaempft jemand anders um sie
    (BBot AvoidKS): Name wird kurzfristig ignoriert.
    ponytail: Erkennung laeuft pro Name, nicht pro Exemplar — bei
    mehreren gleichnamigen Kreaturen gilt die Art (Upgrade-Trigger:
    Exemplar-Tracking ueber Battlelist-Zeilen). Eigenes AoE unter
    Spielern kann faelschlich als KS wirken; die Sperre heilt sich
    nach 30s selbst.
    """
    battleList = context['ng_battleList']
    previous = battleList.get('previousCreaturesHp', {})
    if content is None:
        battleList['creaturesHp'] = {}
        battleList['previousCreaturesHp'] = {}
        return
    hps = getCreaturesHpPercentages(content, getFilledSlotsCount(content))
    current = {}
    ourTarget = None
    for creature, hp in zip(creatures, hps):
        name = creature['name']
        if name in ('Unknown', 'Dusted') or hp is None:
            continue
        current[name] = min(hp, current.get(name, hp))
        if creature['isBeingAttacked']:
            ourTarget = name
    battleList['creaturesHp'] = current
    players = context.get('gameWindow', {}).get('players', [])
    for name, hp in current.items():
        if name == ourTarget:
            continue
        old = previous.get(name)
        if old is not None and hp < old and players:
            ignoreCreatureTemporarily(context, name)
    battleList['previousCreaturesHp'] = current


# TODO: add unit tests
def setBattleListMiddleware(context: Context) -> Context:
    content = getContent(context['ng_screenshot'])
    creatures = getCreatures(content)
    context['ng_battleList']['creatures'] = creatures
    context['ng_cave']['isAttackingSomeCreature'] = len(creatures) > 0 and isAttackingSomeCreature(creatures)
    _trackCreaturesHp(context, content, creatures)
    return context
