import logging
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.diagnostic_dump import dump_ui_state
from GramAddict.core.situational_awareness import SituationalAwarenessEngine, SituationType
from GramAddict.core.telepathic_engine import TelepathicEngine

logger = logging.getLogger(__name__)


class ObstacleGuardPlugin(BehaviorPlugin):
    """
    Guards against modals and checks marker presence to prevent infinite loops.

    Priority: 95.
    """

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

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

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

    @property
    def exclusive(self) -> bool:
        return True

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

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        sae = SituationalAwarenessEngine.get_instance(ctx.device)
        xml = ctx.context_xml if ctx.context_xml else ctx.device.dump_hierarchy()
        situation = sae.perceive(xml)

        misses = ctx.shared_state.get("consecutive_marker_misses", 0)

        # ── System Dialog / Permission Modal (e.g. "Allow Instagram to record audio?") ──
        if situation == SituationType.OBSTACLE_SYSTEM:
            logger.warning("⚠️ [ObstacleGuard] System permission dialog detected. Dismissing with BACK...")
            ctx.device.press("back")
            sleep(1.5 * ctx.sleep_mod)
            return BehaviorResult(executed=True, should_skip=True)

        # ── Foreign App Takeover (e.g. browser opened, wrong app in foreground) ──
        if situation == SituationType.OBSTACLE_FOREIGN_APP:
            logger.warning("⚠️ [ObstacleGuard] Foreign app detected. Pressing BACK to recover...")
            ctx.device.press("back")
            sleep(1.5 * ctx.sleep_mod)
            return BehaviorResult(executed=True, should_skip=True)

        # ── Instagram Modal / Overlay (survey, "Not Now" prompt, creation flow) ──
        if situation == SituationType.OBSTACLE_MODAL:
            if misses >= 2:
                logger.error("🛑 [ObstacleGuard] Failed to recover from OBSTACLE_MODAL after multiple attempts.")
                sae.unlearn_current_state(xml)
                dump_ui_state(ctx.device, f"fatal_obstacle_{ctx.session_state.job_target}")
                return BehaviorResult(executed=True, should_skip=True, metadata={"return_code": "CONTEXT_LOST"})

            logger.warning("⚠️ [ObstacleGuard] OBSTACLE_MODAL detected. Attempting to dismiss...")
            ctx.device.press("back")
            sleep(1.5 * ctx.sleep_mod)

            # Check recovery
            new_xml = ctx.device.dump_hierarchy()
            tele = TelepathicEngine.get_instance()
            best_node = tele.find_best_node(new_xml, intent_description="Dismiss obstacle", device=ctx.device)
            if best_node:
                ctx.device.click(best_node.get("x", 0), best_node.get("y", 0))

            if "row_feed_button_like" in new_xml:
                logger.info("✅ [ObstacleGuard] Successfully recovered from OBSTACLE_MODAL.")
                ctx.shared_state["consecutive_marker_misses"] = 0
            else:
                ctx.shared_state["consecutive_marker_misses"] = misses + 1

            return BehaviorResult(executed=True, should_skip=True)  # Restart loop for same post or next

        return BehaviorResult(executed=False)
