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

        # ── STRUCTURAL GUARD ──
        screen_type = ctx.shared_state.get("current_screen_type")
        if not screen_type and ctx.context_xml:
            from GramAddict.core.perception.screen_identity import ScreenIdentity

            screen_type = ScreenIdentity(getattr(ctx, "username", "")).identify(ctx.context_xml).get("screen_type")

        from GramAddict.core.perception.screen_identity import ScreenType

        if screen_type not in (ScreenType.OTHER_PROFILE, ScreenType.FOLLOW_LIST):
            return False

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

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Follow the target user. ONLY clicks 'Follow' buttons, never 'Following'."""
        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)

        # ── CRITICAL SAFETY GUARD ──
        # Pre-check: verify the button actually says "Follow" (not "Following" or "Requested").
        # Clicking "Following" opens a dangerous bottom sheet (Unfollow / Add to Favorites / Close Friends).
        xml = ctx.context_xml if ctx.context_xml else ctx.device.dump_hierarchy()

        from GramAddict.core.telepathic_engine import TelepathicEngine

        telepathic = ctx.cognitive_stack.get("telepathic") or TelepathicEngine.get_instance()

        classification = telepathic.classify_screen_content(xml.lower(), "profile_follow_status")
        if classification in ("following", "requested"):
            logger.info(
                f"🛡️ [Follow] Profile status is '{classification}' — user already followed. Skipping to avoid bottom sheet."
            )
            return BehaviorResult(executed=False, metadata={"reason": "already_following"})

        if nav_graph.do("tap follow 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"})
