import logging
import random
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.physics.humanized_input import humanized_click, humanized_scroll
from GramAddict.core.physics.timing import wait_for_post_loaded

logger = logging.getLogger(__name__)


class GridLikePlugin(BehaviorPlugin):
    """
    Opens profile grid and likes posts with humanized behavior.

    Priority: 30.
    """

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

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

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

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

        if likes_pct <= 0:
            return False

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

        # ── STRUCTURAL GUARD ──
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        if nav_graph and nav_graph.current_state != "ProfileView":
            return False

        # Fallback XML check
        xml = ctx.context_xml if ctx.context_xml else ctx.device.dump_hierarchy()
        xml_lower = xml.lower()
        if "followers" not in xml_lower and "beiträge" not in xml_lower and "posts" not in xml_lower:
            return False

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

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Open grid and like posts."""
        config = self.get_config(ctx)

        # Parse like count
        likes_count_str = config.get("count", getattr(ctx.configs.args, "likes_count", "1-2"))
        try:
            if "-" in likes_count_str:
                min_l, max_l = map(int, likes_count_str.split("-"))
                count = random.randint(min_l, max_l)
            else:
                count = int(likes_count_str)
        except Exception:
            count = 1

        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 not nav_graph.do("tap first image post in profile grid"):
            return BehaviorResult(executed=False, metadata={"reason": "grid_nav_failed"})

        if not wait_for_post_loaded(ctx.device, timeout=5):
            logger.warning(f"❌ [GridLike] Post failed to open from profile grid of @{ctx.username}.")
            return BehaviorResult(executed=False, metadata={"reason": "post_load_failed"})

        logger.info(f"❤️ [GridLike] Dropping {count} likes on @{ctx.username} profile grid...")

        info = ctx.device.get_info()
        w = info.get("displayWidth", 1080)
        h = info.get("displayHeight", 2400)

        growth = ctx.cognitive_stack.get("growth_brain")
        total_liked = 0

        for i in range(count):
            xml_dump = ctx.device.dump_hierarchy()
            xml_dump_lower = xml_dump.lower()

            is_reel = "reel_viewer" in xml_dump_lower or "clips_viewer" in xml_dump_lower

            # Use growth brain for decision making (double tap vs heart button)
            use_double_tap = growth.wants_to_double_tap(is_reel=is_reel) if growth else False

            if use_double_tap:
                offset_x = random.randint(int(w * 0.2), int(w * 0.8))
                offset_y = random.randint(int(h * 0.3), int(h * 0.7))
                humanized_click(ctx.device, offset_x, offset_y, double=True, sleep_mod=ctx.sleep_mod)
                ctx.session_state.totalLikes += 1
                total_liked += 1
                logger.debug(f"Liked grid post {i+1}/{count} via Double-Tap")
            else:
                if nav_graph.do("tap like button"):
                    ctx.session_state.totalLikes += 1
                    total_liked += 1
                    logger.debug(f"Liked grid post {i+1}/{count} via Heart Button")
                else:
                    logger.debug(f"Skipped liking grid post {i+1}/{count}")

            sleep(random.uniform(1.0, 2.0) * ctx.sleep_mod)

            if i < count - 1:
                if is_reel:
                    humanized_scroll(ctx.device, is_skip=True)
                else:
                    humanized_scroll(ctx.device, is_skip=False)
                sleep(random.uniform(1.5, 3.0) * ctx.sleep_mod)

        ctx.device.press("back")
        sleep(random.uniform(1.0, 2.0) * ctx.sleep_mod)

        return BehaviorResult(
            executed=True, interactions=total_liked, metadata={"posts_viewed": count, "posts_liked": total_liked}
        )
