import logging
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.physics.humanized_input import humanized_scroll
from GramAddict.core.telepathic_engine import TelepathicEngine

logger = logging.getLogger(__name__)


class AnomalyHandlerPlugin(BehaviorPlugin):
    """
    Handles anomalies like zero interactive nodes on screen.

    Priority: 98 (Runs after AdGuard, before others).
    """

    def __init__(self):
        super().__init__()
        self._enabled = True

    @property
    def name(self) -> str:
        return "anomaly_handler"

    @property
    def priority(self) -> int:
        return 98

    def can_activate(self, ctx: BehaviorContext) -> bool:
        return getattr(self, "_enabled", True)

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        telepathic = ctx.cognitive_stack.get("telepathic") or TelepathicEngine.get_instance()
        xml = ctx.context_xml if ctx.context_xml else ctx.device.dump_hierarchy()
        nodes = telepathic._extract_semantic_nodes(xml)

        ctx.shared_state["interactive_nodes"] = nodes

        if len(nodes) == 0:
            logger.warning("🚨 [Anomaly] Zero interactive nodes found. Executing recovery...")
            ctx.device.press("back")
            sleep(1.0 * ctx.sleep_mod)
            humanized_scroll(ctx.device)
            sleep(1.0 * ctx.sleep_mod)
            return BehaviorResult(executed=True, should_skip=True)

        return BehaviorResult(executed=False)
