"""Auto-Open-Backpacks: oeffnet Main/Loot automatisch wieder.

Nach Relogin, Respawn oder manuellem Schliessen sind die Backpacks zu —
der Bot oeffnet Main und Loot alle 30s selbst (Klick auf das
Slot-Icon, wie OpenBackpackTask es tut). Geschlossene Backpacks waren
bisher ein stiller Produktivitaetskiller: Looter/Router laufen ins
Leere, ohne dass es jemand merkt.
"""
from time import monotonic

import src.repositories.inventory.core as inventoryCore
from src.repositories.inventory.config import images
from src.utils.core import locate
from src.utils.mouse import useClick

CHECK_INTERVAL_SECONDS = 30


def ensureBackpacksOpen(context):
    """Loop-Hook: oeffnet konfigurierte Backpacks, wenn sie fehlen."""
    if context['ng_pause'] or not context['ng_cave']['enabled']:
        return context
    state = context.setdefault('ng_backpackWatch', {})
    now = monotonic()
    if now - state.get('lastCheckAt', 0) < CHECK_INTERVAL_SECONDS:
        return context
    state['lastCheckAt'] = now
    screenshot = context['ng_screenshot']
    if screenshot is None:
        return context
    for name in dict.fromkeys(
            name for name in (
                context['ng_backpacks'].get('main'),
                context['ng_backpacks'].get('loot'),
            ) if name):
        if inventoryCore.isContainerOpen(screenshot, name):
            continue
        slotImage = images['slots'].get(name)
        if slotImage is None:
            continue
        position = locate(screenshot, slotImage, confidence=0.75)
        if position is not None:
            useClick((position[0] + 5, position[1] + 5))
    return context
