import logging
import random
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.physics.humanized_input import humanized_click
from GramAddict.core.physics.timing import wait_for_story_loaded

logger = logging.getLogger(__name__)


class StoryViewPlugin(BehaviorPlugin):
    """
    Views a target user's stories from their profile.

    Priority: 25.
    """

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        """Activates when story viewing is enabled and probability met."""
        config = self.get_config(ctx)
        stories_pct = float(config.get("percentage", getattr(ctx.configs.args, "stories_percentage", 0))) / 100.0

        if stories_pct <= 0:
            return False

        # Probability gate
        if random.random() >= stories_pct:
            return False

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """View stories with humanized timing."""
        config = self.get_config(ctx)

        # Parse story count
        stories_count_str = config.get("count", getattr(ctx.configs.args, "stories_count", "1-2"))
        try:
            if "-" in stories_count_str:
                min_st, max_st = map(int, stories_count_str.split("-"))
                count = random.randint(min_st, max_st)
            else:
                count = int(stories_count_str)
        except Exception:
            count = 1

        # Check for story ring
        xml = ctx.context_xml or ctx.device.dump_hierarchy()
        xml_lower = xml.lower()
        has_story = (
            "reel_ring" in xml
            or "has an unseen story" in xml_lower
            or "has a new story" in xml_lower
            or "story von" in xml_lower
        )

        if not has_story:
            return BehaviorResult(executed=False, metadata={"reason": "no_story"})

        # Navigate to story
        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)

        if not nav_graph.do("tap story ring avatar"):
            return BehaviorResult(executed=False, metadata={"reason": "nav_failed"})

        # Wait for story to load
        if not wait_for_story_loaded(ctx.device, timeout=5):
            logger.warning(f"❌ [StoryView] Story failed to open for @{ctx.username}.")
            return BehaviorResult(executed=False, metadata={"reason": "load_timeout"})

        logger.info(f"📸 [StoryView] Viewing @{ctx.username}'s story ({count} segments)...")

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

        for i in range(count):
            sleep(random.uniform(2.0, 5.0) * ctx.sleep_mod)
            if i < count - 1:
                humanized_click(ctx.device, int(w * 0.9), int(h * 0.5), sleep_mod=ctx.sleep_mod)

        ctx.device.press("back")
        sleep(random.uniform(1.0, 2.0) * ctx.sleep_mod)

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