import logging
import random
from time import sleep

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

logger = logging.getLogger(__name__)


class ProfileVisitPlugin(BehaviorPlugin):
    """
    Handles visiting a user's profile from the feed.

    Priority: 35.
    """

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

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

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

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

        # 1. Guard against recursive calls or being already on profile
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        if nav_graph and nav_graph.current_state == "ProfileView":
            return False

        # 2. Probability gate
        config = self.get_config(ctx)
        visit_pct = float(config.get("percentage", getattr(ctx.configs.args, "profile_visit_percentage", 30))) / 100.0

        if visit_pct <= 0:
            return False

        # 3. Probability gate (weighted by resonance)
        res_score = ctx.shared_state.get("res_score", 1.0)
        chance = visit_pct * res_score

        if random.random() >= chance:
            return False

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Visit the user's profile and execute nested plugins."""
        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 post username"):
            logger.info(f"👤 [ProfileVisit] Visiting @{ctx.username}...")
            sleep(2.0 * ctx.sleep_mod)

            # Create a new context for the profile interaction
            from GramAddict.core.behaviors import BehaviorContext, PluginRegistry

            # Update nav state to ProfileView
            original_state = nav_graph.current_state
            nav_graph.current_state = "ProfileView"

            profile_xml = ctx.device.dump_hierarchy()
            profile_ctx = BehaviorContext(
                device=ctx.device,
                configs=ctx.configs,
                session_state=ctx.session_state,
                cognitive_stack=ctx.cognitive_stack,
                context_xml=profile_xml,
                sleep_mod=ctx.sleep_mod,
                post_data=ctx.post_data,
                username=ctx.username,
                shared_state=ctx.shared_state,
            )

            logger.info(f"🕵️ [ProfileVisit] Executing interactions on @{ctx.username}'s profile...")
            registry = PluginRegistry.get_instance()

            # Execute all active plugins on the profile view (including ProfileGuard)
            registry.execute_all(profile_ctx)

            # Restore nav state
            nav_graph.current_state = original_state

            logger.info(f"🔙 [ProfileVisit] Returning from @{ctx.username}.")
            ctx.device.press("back")
            sleep(1.0 * ctx.sleep_mod)

            return BehaviorResult(executed=True, interactions=1)

        return BehaviorResult(executed=False)
