import logging
import random

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

logger = logging.getLogger(__name__)


class CommentPlugin(BehaviorPlugin):
    """
    Handles commenting on posts.

    Priority: 55.
    """

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

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

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

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

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

        # Safety Guard: Do not comment on stories or grids
        xml_lower = (ctx.context_xml or "").lower()
        STORY_MARKERS = (
            "reel_viewer_media_layout",
            "reel_viewer_header",
            "reel_viewer_progress_bar",
            "reel_viewer_root",
        )
        if any(marker in xml_lower for marker in STORY_MARKERS):
            return False

        if "explore_action_bar" in xml_lower or "profile_tabs_container" in xml_lower:
            return False

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

        if comment_pct <= 0:
            return False

        # Probability gate (includes resonance weighting if available in shared_state)
        res_score = ctx.shared_state.get("res_score", 1.0)
        chance = comment_pct * res_score

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

        return True

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

        config = self.get_config(ctx)

        # 1. Open comment section
        if nav_graph.do("open comments"):
            # 2. Generate comment text
            writer = ctx.cognitive_stack.get("writer")
            if not writer:
                logger.warning("✍️ [Comment] No 'writer' found in cognitive stack. Cannot generate comment.")
                ctx.device.press("back")
                return BehaviorResult(executed=False)

            text = writer.generate_comment(ctx.post_data)
            logger.info(f"✍️ [Comment] Generated: '{text}'")

            # 3. Handle Dry Run
            if config.get("dry_run", getattr(ctx.configs.args, "dry_run_comments", False)):
                logger.info("🧪 [Comment] Dry run enabled. Skipping actual post.")
                ctx.device.press("back")
                return BehaviorResult(executed=True, interactions=0, metadata={"text": text, "dry_run": True})

            # 4. Type and post
            if nav_graph.do("type and post comment", text=text):
                logger.info(f"💬 [Comment] Posted to @{ctx.username} ✓")
                ctx.session_state.add_interaction(source=ctx.username, succeed=True, followed=False, scraped=False)
                ctx.session_state.totalComments += 1
                return BehaviorResult(executed=True, interactions=1, metadata={"text": text})

        return BehaviorResult(executed=False)
