import logging
import random

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

logger = logging.getLogger(__name__)


class LikePlugin(BehaviorPlugin):
    """
    Handles liking posts.

    Priority: 50.
    """

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

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        """Determines if we should like this post."""
        from GramAddict.core.session_state import SessionState

        if ctx.session_state.check_limit(SessionState.Limit.LIKES):
            logger.error("LikePlugin: limit check failed")
            return False

        config = self.get_config(ctx)
        likes_pct = float(config.get("percentage", getattr(ctx.configs.args, "likes_percentage", 80))) / 100.0

        if likes_pct <= 0:
            return False

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

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Like the current post."""
        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 like button"):
            logger.info(f"❤️ [Like] Liked post by @{ctx.username} ✓")
            ctx.session_state.add_interaction(source=ctx.username, succeed=True, followed=False, scraped=False)
            ctx.session_state.totalLikes += 1
            return BehaviorResult(executed=True, interactions=1)

        return BehaviorResult(executed=False)
