import logging
from time import sleep

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

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:
        return getattr(self, "_enabled", True)

    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", []))

        humanized_scroll(ctx.device)
        sleep(1.5 * ctx.sleep_mod)

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