"""
Profile Guard Behavior — Plugin Implementation.

Safety guards that reject profiles before any interactions occur:
- Private accounts
- Empty accounts
- Close friends (when configured)
- Visual vibe check (AI aesthetic quality)

Priority 100 (highest, exclusive) — if a guard fires, no other behavior runs.
"""

import logging

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

logger = logging.getLogger(__name__)


class ProfileGuardPlugin(BehaviorPlugin):
    """
    Guards against interacting with profiles that should be skipped.
    Exclusive: if this fires, no further interactions happen on this profile.
    """

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

    @property
    def priority(self) -> int:
        return 100  # Highest — runs before everything

    @property
    def exclusive(self) -> bool:
        return True  # Stop all other plugins if guard fires

    def can_activate(self, ctx: BehaviorContext) -> bool:
        """Only activates on Profile screens to prevent false-positives in Feed/Reels."""
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        is_profile = nav_graph and nav_graph.current_state == "ProfileView"
        return bool(ctx.username) and is_profile

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        """Check profile guards. Returns executed=True + should_skip=True if rejected."""
        from colorama import Fore

        xml_check = ctx.context_xml
        if not xml_check:
            return BehaviorResult(executed=False)

        xml_check_lower = xml_check.lower()

        # Self-interaction guard
        if hasattr(ctx.session_state, "my_username") and ctx.username == ctx.session_state.my_username:
            logger.info(f"🤝 [Profile Guard] Skipping own profile @{ctx.username}.")
            return BehaviorResult(executed=True, should_skip=True, metadata={"reason": "self_profile"})

        # Private account guard
        if "this account is private" in xml_check_lower or "konto ist privat" in xml_check_lower:
            logger.info(f"🔒 [Profile Guard] @{ctx.username} is private.", extra={"color": f"{Fore.YELLOW}"})
            return BehaviorResult(executed=True, should_skip=True, metadata={"reason": "private"})

        # Empty account guard
        if "no posts yet" in xml_check_lower or "noch keine beiträge" in xml_check_lower:
            logger.info(f"📭 [Profile Guard] @{ctx.username} has no posts.", extra={"color": f"{Fore.YELLOW}"})
            return BehaviorResult(executed=True, should_skip=True, metadata={"reason": "empty"})

        # Close friends guard
        if getattr(ctx.configs.args, "ignore_close_friends", False):
            if "close friend" in xml_check_lower:
                logger.info(
                    f"💚 [Profile Guard] @{ctx.username} is a Close Friend. Ignoring.", extra={"color": "\033[32m"}
                )
                return BehaviorResult(executed=True, should_skip=True, metadata={"reason": "close_friend"})

        # Visual Vibe Check (AI Aesthetic Quality Guard)
        import random

        vibe_check_pct = float(getattr(ctx.configs.args, "visual_vibe_check_percentage", 0)) / 100.0
        if vibe_check_pct > 0 and random.random() < vibe_check_pct:
            from GramAddict.core.telepathic_engine import TelepathicEngine

            telepathic = ctx.cognitive_stack.get("telepathic") or TelepathicEngine.get_instance()
            persona_interests = ctx.cognitive_stack.get("persona_interests", []) if ctx.cognitive_stack else []
            vibe_result = telepathic.evaluate_profile_vibe(ctx.device, persona_interests)

            if vibe_result:
                score = vibe_result.get("quality_score", 5)
                matches_niche = vibe_result.get("matches_niche", True)
                if score < 5 or not matches_niche:
                    logger.warning(
                        f"🚫 [Vibe Check] Profile @{ctx.username} rejected (Score: {score}, Niche: {matches_niche}). Reason: {vibe_result.get('reason')}"
                    )
                    return BehaviorResult(
                        executed=True, should_skip=True, metadata={"reason": "vibe_check_failed", "score": score}
                    )
                else:
                    logger.info(
                        f"✅ [Vibe Check] Profile @{ctx.username} approved (Score: {score}). Continuing interaction.",
                        extra={"color": "\033[36m"},
                    )

        # All guards passed — don't block further plugins
        return BehaviorResult(executed=False)
