"""
Carousel Browsing Behavior — Plugin Implementation.

Migrated from bot_flow.py's _interact_with_carousel function.
Now independently testable and composable.
"""

import logging
import random
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.perception.feed_analysis import has_carousel_in_view
from GramAddict.core.physics.humanized_input import humanized_horizontal_swipe

logger = logging.getLogger(__name__)


class CarouselBrowsingPlugin(BehaviorPlugin):
    """
    Browses carousel posts with humanized swiping and curiosity dwells.

    Priority: 70 (Primary interaction).
    """

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

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

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

        # Analysis requires XML
        xml = ctx.context_xml if ctx.context_xml else ctx.device.dump_hierarchy()
        if not has_carousel_in_view(xml):
            return False

        config = self.get_config(ctx)
        percentage = float(config.get("percentage", getattr(ctx.configs.args, "carousel_percentage", 0)))
        return random.random() < (percentage / 100.0)

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Browse carousel with humanized swiping."""
        from colorama import Fore

        config = self.get_config(ctx)
        carousel_count_str = config.get("count", getattr(ctx.configs.args, "carousel_count", "1-2"))
        try:
            min_c, max_c = map(int, carousel_count_str.split("-"))
            count = random.randint(min_c, max_c)
        except Exception:
            count = 1

        logger.info(
            f"📸 [Carousel] Interacting with carousel. Swiping {count} times...", extra={"color": f"{Fore.CYAN}"}
        )

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

        # Curiosity Peak: One slide gets extra attention
        curiosity_slide = random.randint(0, count - 1) if count > 0 else 0

        for i in range(count):
            # Normal transition wait
            sleep(random.uniform(1.5, 3.5) * ctx.sleep_mod)

            # ── Curiosity Dwell ──
            if i == curiosity_slide:
                dwell = random.uniform(3.0, 7.0)
                logger.debug(f"📸 [Carousel] Curiosity Peak hit on slide {i+1}. " f"Gazing for {dwell:.1f}s...")
                sleep(dwell * ctx.sleep_mod)

            # Horizontal swipe: Right to left
            humanized_horizontal_swipe(ctx.device, start_x=w * 0.8, end_x=w * 0.2, y=h * 0.5, duration_ms=250)

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

        return BehaviorResult(
            executed=True, interactions=count, metadata={"slides_viewed": count, "curiosity_slide": curiosity_slide}
        )
