import logging

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult
from GramAddict.core.perception.feed_analysis import extract_post_content

logger = logging.getLogger(__name__)


class PostDataExtractionPlugin(BehaviorPlugin):
    """
    Extracts post data (caption, hashtags, user) for later evaluation.

    Priority: 85 (Runs after guards, before evaluation).
    """

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

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

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

    def can_activate(self, ctx: BehaviorContext) -> bool:
        from GramAddict.core.perception.feed_analysis import has_feed_markers

        return getattr(self, "_enabled", True) and ctx.context_xml is not None and has_feed_markers(ctx.context_xml)

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        logger.debug("🧩 [PostDataExtraction] Extracting post metadata...")
        post_data = extract_post_content(ctx.context_xml, device=ctx.device)

        if post_data:
            ctx.post_data = post_data
            ctx.username = post_data.get("username", "")

            if post_data.get("username_missing") or not ctx.username:
                logger.error(
                    "❌ [PostDataExtraction] FAILED: Post author username is empty or missing! Halting interaction."
                )
                return BehaviorResult(executed=False, metadata={"error": "Empty username extracted"})

            logger.info(f"📝 [PostDataExtraction] Post by @{ctx.username} extracted.")
            return BehaviorResult(executed=True)

        return BehaviorResult(executed=False)
