import logging

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

logger = logging.getLogger(__name__)


class PerfectSnappingPlugin(BehaviorPlugin):
    """
    Aligns the current post in the viewport.

    Priority: 90 (Runs after guards, before extraction).
    """

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

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        if not getattr(self, "_enabled", True):
            return False

        # Perfect snapping is only for feed posts.
        # Do not snap if we are on a profile page, explore grid, or modal.
        from GramAddict.core.perception.feed_analysis import has_feed_markers

        if not has_feed_markers(ctx.context_xml):
            return False

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        aligned = _align_active_post(ctx.device)
        if aligned:
            logger.info("🎯 [PerfectSnapping] Post aligned. Refreshing context XML...")
            new_xml = ctx.device.dump_hierarchy()
            radome = ctx.cognitive_stack.get("radome")
            if radome:
                new_xml = radome.sanitize_xml(new_xml)
            ctx.context_xml = new_xml
            return BehaviorResult(executed=True)

        return BehaviorResult(executed=False)
