import logging
import random

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

logger = logging.getLogger(__name__)


class RepostPlugin(BehaviorPlugin):
    """
    Handles reposting (sharing to story) for posts.

    Priority: 45.
    """

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

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        """Determines if we should repost this post."""
        if not getattr(self, "_enabled", True):
            return False

        config = self.get_config(ctx)
        repost_pct = float(config.get("percentage", getattr(ctx.configs.args, "repost_percentage", 20))) / 100.0

        if repost_pct <= 0:
            return False

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

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Repost 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)

        # We must click the send post button first
        if nav_graph.do("tap send post button"):
            # A modal should appear, now click add to story
            if nav_graph.do("tap add to story"):
                logger.info(f"📤 [Repost] Shared post by @{ctx.username} to story ✓")
                return BehaviorResult(executed=True, interactions=1)

        return BehaviorResult(executed=False)
