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.utils import is_ad

logger = logging.getLogger(__name__)


class AdGuardPlugin(BehaviorPlugin):
    """
    Checks for ads in the feed and scrolls past them.
    Implements a deadlock escape after 5 consecutive ads.

    Priority: 100 (Safety guard, runs first).
    Exclusive: True (if ad detected, stop other interactions).
    """

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

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

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

    @property
    def exclusive(self) -> bool:
        return True

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

        # We check for ad presence here to decide if we activate.
        # This is a bit more expensive than a percentage check but necessary for a guard.
        # Optimization: Only check if context_xml is available or do a quick string search.
        if ctx.context_xml:
            return is_ad(ctx.context_xml, ctx.cognitive_stack)

        return False

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        self.consecutive_ads += 1

        if self.consecutive_ads >= 5:
            logger.warning("🛡️ [AdGuard] Deadlock detected: 5 consecutive ads. Escaping to HomeFeed.")
            nav_graph = ctx.cognitive_stack.get("nav_graph")
            zero_engine = ctx.cognitive_stack.get("zero_latency_engine")
            if nav_graph:
                nav_graph.navigate_to("HomeFeed", zero_engine)
            self.consecutive_ads = 0
            return BehaviorResult(executed=True, should_skip=True)

        logger.info(f"🛡️ [AdGuard] Ad detected ({self.consecutive_ads}). Scrolling past it...")
        humanized_scroll(ctx.device, is_skip=True)
        sleep(1.0 * ctx.sleep_mod)

        # Aggressive double skip for triple ad
        if self.consecutive_ads >= 3:
            logger.info("🛡️ [AdGuard] Aggressive skip for consecutive ads.")
            humanized_scroll(ctx.device, is_skip=True)
            sleep(1.0 * ctx.sleep_mod)

        return BehaviorResult(executed=True, should_skip=True)

    def reset_counter(self):
        self.consecutive_ads = 0
