import logging
import random
from time import sleep

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

logger = logging.getLogger(__name__)


class FollowPlugin(BehaviorPlugin):
    """
    Follows a target user from their profile page or feed.

    Priority: 40.
    """

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        """Activates when follow is enabled and limits not reached."""
        from GramAddict.core.session_state import SessionState

        config = self.get_config(ctx)
        follow_pct = float(config.get("percentage", getattr(ctx.configs.args, "follow_percentage", 0))) / 100.0

        if follow_pct <= 0:
            return False

        if ctx.session_state.check_limit(SessionState.Limit.FOLLOWS):
            return False

        # Probability gate
        if random.random() >= follow_pct:
            return False

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Follow the target user."""
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        if not nav_graph:
            from GramAddict.core.q_nav_graph import QNavGraph

            nav_graph = QNavGraph(ctx.device)

        if nav_graph.do("tap 'Follow' button") or nav_graph.do("tap 'Following' button"):
            logger.info(f"🤝 [Follow] Followed @{ctx.username} ✓")
            ctx.session_state.add_interaction(source=ctx.username, succeed=True, followed=True, scraped=False)

            # Buffer for follow animations to close
            sleep(random.uniform(1.8, 3.2) * ctx.sleep_mod)

            return BehaviorResult(executed=True, interactions=1, metadata={"followed": ctx.username})

        return BehaviorResult(executed=False, metadata={"reason": "nav_failed"})
