import logging
import random
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 ResonanceEvaluatorPlugin(BehaviorPlugin):
    """
    Evaluates how much the bot likes a post based on its descriptions, vibes, etc.
    Decides whether to proceed with interactions or skip the post.

    Priority: 80 (Runs after data extraction).
    """

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

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

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

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

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        resonance = ctx.cognitive_stack.get("resonance")
        if not resonance:
            logger.warning("🧠 [Resonance] Engine missing. Defaulting to 1.0")
            res_score = 1.0
        else:
            post_data = ctx.post_data or {}
            res_score = resonance.calculate_resonance(post_data)

        # Check visual vibe
        config = self.get_config(ctx)
        visual_chance = float(
            config.get("visual_vibe_check_percentage", getattr(ctx.configs.args, "visual_vibe_check_percentage", 0))
        )
        if visual_chance > 0 and random.random() < (visual_chance / 100.0):
            tele = ctx.cognitive_stack.get("telepathic")
            if tele:
                logger.info("✨ [Resonance] Performing visual vibe check...")

                # BUG 5 Fix: Read target_audience or persona_interests
                raw_interests = getattr(ctx.configs.args, "persona_interests", "")
                if not raw_interests:
                    raw_interests = getattr(ctx.configs.args, "target_audience", "")

                if isinstance(raw_interests, list):
                    persona_interests = [str(i).strip() for i in raw_interests if str(i).strip()]
                else:
                    persona_interests = [i.strip() for i in str(raw_interests).split(",") if i.strip()]

                vibe = tele.evaluate_post_vibe(ctx.device, persona_interests)
                if vibe is None:
                    logger.warning(
                        "✨ [Resonance] VLM vibe check returned None (truncated JSON?). Keeping neutral score."
                    )
                else:
                    if vibe.get("is_ad"):
                        logger.info("🛡️ [Resonance Oracle] Visually identified post as an Ad! Skipping...")
                        marker = vibe.get("ad_marker_text")
                        if marker and marker.strip():
                            from GramAddict.core.utils import learn_ad_marker
                            learn_ad_marker(marker, ctx.context_xml)
                        humanized_scroll(ctx.device)
                        return BehaviorResult(executed=True, should_skip=True)

                    # BUG 6 Fix: VLM returns {"should_like": true/false}, not "quality_score"
                    should_like = vibe.get("should_like", False)
                    vibe_score = 1.0 if should_like else 0.2
                    res_score = (res_score * 0.3) + (vibe_score * 0.7)

        ctx.shared_state["res_score"] = res_score
        logger.info(f"📊 [Resonance] Post Score: {res_score:.2f}")

        interact_chance = float(getattr(ctx.configs.args, "interact_percentage", 100))

        # Determine if we should skip the entire post
        # Threshold could be dynamic, but let's say 0.2 is the floor for absolute garbage
        if res_score < 0.2 or random.random() >= (interact_chance / 100.0):
            logger.info(f"⏭️ [Resonance] Skipping post (score={res_score:.2f}, chance check failed).")

            if "session_outcomes" not in ctx.shared_state:
                ctx.shared_state["session_outcomes"] = []

            ctx.shared_state["session_outcomes"].append(
                {"username": ctx.username, "resonance": res_score, "action": "skip"}
            )

            # If we skip here, we MUST scroll to next post and terminate chain
            humanized_scroll(ctx.device)
            sleep(1.0 * ctx.sleep_mod)
            return BehaviorResult(executed=True, should_skip=True)

        dopamine = ctx.cognitive_stack.get("dopamine")
        if dopamine:
            quality = "high" if res_score > 0.7 else ("medium" if res_score > 0.4 else "low")
            dopamine.process_content({"score": res_score * 10, "quality": quality})

        return BehaviorResult(executed=True, should_skip=False)
