import logging

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

logger = logging.getLogger(__name__)


class ScrapeProfilePlugin(BehaviorPlugin):
    """
    Extracts profile metadata (followers, following, bio) when visiting a profile.

    Priority: 45. (Runs after ProfileGuard, before deep interactions like GridLike)
    """

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

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

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

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

        # Only activate if scrape_profiles is True in config
        if not getattr(ctx.configs.args, "scrape_profiles", False):
            return False

        # Only activate when we are actively visiting a profile (via ProfileVisitPlugin)
        nav_graph = ctx.cognitive_stack.get("nav_graph")
        if not nav_graph or nav_graph.current_state != "ProfileView":
            return False

        return True

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        from colorama import Fore

        logger.info(f"📊 [Scraping] Extracting metadata for @{ctx.username}...", extra={"color": f"{Fore.CYAN}"})

        telepathic = ctx.cognitive_stack.get("telepathic") or TelepathicEngine.get_instance()
        crm = ctx.cognitive_stack.get("crm")

        xml_check = ctx.context_xml or ctx.device.dump_hierarchy()

        f_node = telepathic.find_best_node(xml_check, "Followers count text or number", device=ctx.device)
        fg_node = telepathic.find_best_node(xml_check, "Following count text or number", device=ctx.device)
        bio_node = telepathic.find_best_node(xml_check, "User biography or description text", device=ctx.device)

        scraped_data = {
            "username": ctx.username,
            "followers": f_node.get("text") if f_node else "unknown",
            "following": fg_node.get("text") if fg_node else "unknown",
            "bio": bio_node.get("text") if bio_node else "No bio",
        }

        logger.info(
            f"✅ [Scraping] Data acquired: {scraped_data['followers']} followers, {scraped_data['following']} following."
        )

        ctx.session_state.add_interaction(source=ctx.username, succeed=False, followed=False, scraped=True)

        if crm:
            try:
                crm.enrich_lead(ctx.username, scraped_data)
                logger.info(f"💾 [CRM] Enriched lead @{ctx.username} in database.")
            except Exception as e:
                logger.error(f"❌ [CRM] Failed to enrich lead @{ctx.username}: {e}")

        # Return executed=True, but we don't return interactions=1 since it's just data extraction
        return BehaviorResult(executed=True)
