import logging
import random
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult

logger = logging.getLogger(__name__)


class RabbitHolePlugin(BehaviorPlugin):
    """
    Randomly jumps into a user's profile if resonance is high.

    Priority: 20 (Secondary interaction).
    """

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

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

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

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

        res_score = ctx.shared_state.get("res_score", 0.0)
        if res_score < 0.8:
            return False

        config = self.get_config(ctx)
        percentage = float(config.get("percentage", 15))
        return random.random() < (percentage / 100.0)

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        logger.info("🕳️ [RabbitHole] Falling down the rabbit hole! Investigating user profile...")
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        if nav_graph:
            success = nav_graph.do("tap post username")
            if success:
                sleep(2.0 * ctx.sleep_mod)
                # Just a quick peek
                ctx.device.press("back")
                sleep(1.0 * ctx.sleep_mod)
                return BehaviorResult(executed=True)

        return BehaviorResult(executed=False)
