import logging

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

logger = logging.getLogger(__name__)


class PostInteractionPlugin(BehaviorPlugin):
    """
    Runs after all interactions on a post are complete.
    Handles scrolling to the next post and logging outcomes.

    Priority: 10 (lowest, runs last).
    Exclusive: True (ends the behavior chain for this post).
    """

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

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

    @property
    def priority(self) -> int:
        return 10  # Lowest priority, runs last

    @property
    def exclusive(self) -> bool:
        return True  # Ends the behavior chain for this post

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

        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

        valid_screens = [ScreenType.HOME_FEED, ScreenType.POST_DETAIL, ScreenType.REELS_FEED, ScreenType.STORY_VIEW]
        return screen_type in valid_screens

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        logger.info("🏁 [PostInteraction] Interactions complete. Moving to next post...")

        # Log to CRM or telemetry if active
        telemetry = ctx.cognitive_stack.get("telemetry")
        if telemetry:
            telemetry.log_post_interaction(ctx.post_data, ctx.shared_state.get("session_outcomes", []))

        return BehaviorResult(
            executed=True, should_skip=True, skip_type="normal"
        )  # should_skip=True signals the feed loop to restart for the next post
