import logging
import random

from colorama import Fore, Style

from GramAddict.core.session_state import SessionState

logger = logging.getLogger(__name__)


def _run_zero_latency_dm_loop(device, zero_engine, nav_graph, configs, session_state, current_target, cognitive_stack):
    """
    Executes the autonomous Direct Messaging logic in the Zero-Latency architecture.
    Assumes the bot is already at the "MessageInbox" UI state.
    """
    logger.info(
        f"🧠 [DM Engine] Initiating inbox processing in {current_target}...",
        extra={"color": f"{Style.BRIGHT}{Fore.CYAN}"},
    )

    telepathic = cognitive_stack.get("telepathic")
    dopamine = cognitive_stack.get("dopamine")

    from GramAddict.core.bot_flow import _humanized_click, sleep
    from GramAddict.core.llm_provider import query_llm
    from GramAddict.core.stealth_typing import ghost_type

    # Initialize session limits if missing
    if not hasattr(session_state, "totalMessages"):
        session_state.totalMessages = 0

    failed_attempts = 0

    while not dopamine.is_app_session_over():
        # Limits check
        limit_val = session_state.check_limit(SessionState.Limit.PM)
        if isinstance(limit_val, tuple) and limit_val[0]:
            logger.info("🛑 Messaging limit reached for session.")
            return "BOREDOM_CHANGE_FEED"
        elif limit_val is True:
            return "BOREDOM_CHANGE_FEED"

        try:
            xml_dump = device.dump_hierarchy()

            # --- Zero Trust Structural Guard ---
            # -----------------------------------
            # ZERO TRUST STRUCTURAL GUARD
            # -----------------------------------
            # Validate we are actually in the Inbox or a Thread.
            # Hallucinations can lead to "Privacy Settings" or "Profile" screens.
            is_inbox = (
                'resource-id="com.instagram.android:id/inbox_refreshable_thread_list_recyclerview"' in xml_dump
                or 'resource-id="com.instagram.android:id/direct_inbox_action_bar"' in xml_dump
            )
            is_thread = 'resource-id="com.instagram.android:id/direct_thread_header"' in xml_dump

            if is_thread:
                logger.warning("⚠️ [Structural Guard] DM Engine trapped in an open thread. Escaping...")
                device.press("back")
                from GramAddict.core.bot_flow import sleep

                sleep(1.5)
                continue

            if not is_inbox and not is_thread:
                # We have drifted somewhere entirely alien (like Privacy Settings)
                logger.error("🛑 [Structural Guard] Alien context detected. Not in Inbox. Triggering CONTEXT_LOST.")
                return "CONTEXT_LOST"
            # -----------------------------------

            # Step 1: Find unread conversation threads
            unread_threads = telepathic._extract_semantic_nodes(
                xml_dump, "find unread message threads or unread badges", threshold=0.7
            )

            if unread_threads and not unread_threads[0].get("skip"):
                target_node = unread_threads[0]
                logger.info("📨 Found unread message thread. Opening.")
                _humanized_click(device, target_node["x"], target_node["y"])
                sleep(2.0)

                # Step 2: Read the conversation context
                thread_xml = device.dump_hierarchy()
                msg_nodes = telepathic._extract_semantic_nodes(
                    thread_xml, "find the last received message text", threshold=0.6
                )

                context_text = "No previous context"
                if msg_nodes and not msg_nodes[0].get("skip") and msg_nodes[0].get("text"):
                    context_text = msg_nodes[0].get("text")

                logger.debug(f"Last received message context: {context_text}")

                # Verify we aren't at limits before sending
                if not getattr(configs.args, "disable_ai_messaging", False):
                    # Configure models
                    model = getattr(configs.args, "ai_condenser_model", "llama3.2:1b")
                    url = getattr(configs.args, "ai_condenser_url", "http://localhost:11434/api/generate")

                    # Generate response
                    prompt = f"You are replying to a direct message on Instagram. The last message you received was: '{context_text}'. Keep it short, casual, and friendly. Do not use hashtags."

                    response_dict = query_llm(
                        url=url,
                        model=model,
                        prompt=prompt,
                        format_json=False,
                        timeout=120,
                        max_tokens=100,
                        temperature=0.7,
                    )

                    if response_dict and "response" in response_dict:
                        response_text = response_dict["response"].strip()
                        # Find the input field
                        input_nodes = telepathic._extract_semantic_nodes(
                            thread_xml, "find the message input text field", threshold=0.7
                        )
                        if input_nodes and not input_nodes[0].get("skip"):
                            in_node = input_nodes[0]
                            _humanized_click(device, in_node["x"], in_node["y"])
                            sleep(1.0)

                            # Type the message
                            ghost_type(device, response_text, speed="fast")
                            sleep(1.0)

                            # Find Send button
                            send_xml = device.dump_hierarchy()
                            send_nodes = telepathic._extract_semantic_nodes(
                                send_xml, "find the send message button", threshold=0.8
                            )

                            if send_nodes and not send_nodes[0].get("skip"):
                                s_node = send_nodes[0]
                                _humanized_click(device, s_node["x"], s_node["y"])
                                logger.info(
                                    "✅ [DM Engine] Successfully sent a generated reply.", extra={"color": Fore.GREEN}
                                )

                                session_state.totalMessages += 1
                                dm_memory = cognitive_stack.get("dm_memory")
                                if dm_memory:
                                    dm_memory.log_sent_dm("unknown_target", response_text, "", [])

                # Return back to inbox
                device.press("back")
                sleep(1.5)

                # If keyboard was open, the first back only closed it. Check if still in thread.
                check_xml = device.dump_hierarchy()
                if (
                    'resource-id="com.instagram.android:id/direct_thread_header"' in check_xml
                    or 'resource-id="com.instagram.android:id/row_thread_composer_edittext"' in check_xml
                ):
                    device.press("back")
                    sleep(1.0)

                dopamine.boredom += random.uniform(5.0, 15.0)
                failed_attempts = 0
            else:
                logger.info("📭 No unread threads found. Inbox clear.")
                dopamine.boredom += 50.0  # Inbox clear = massive boredom = change feed

            if dopamine.wants_to_change_feed() or dopamine.boredom >= 100:
                logger.info("🧠 [DM Engine] Interaction complete. Transitioning back from inbox.")
                device.press("back")  # Go back from inbox
                return "BOREDOM_CHANGE_FEED"

        except Exception as e:
            logger.error(f"⚠️ [Anomaly Handler] Exception in DM Loop: {e}")
            device.press("back")
            sleep(1.0)

            check_xml = device.dump_hierarchy()
            if (
                'resource-id="com.instagram.android:id/direct_thread_header"' in check_xml
                or 'resource-id="com.instagram.android:id/row_thread_composer_edittext"' in check_xml
            ):
                device.press("back")
                sleep(1.0)

            failed_attempts += 1
            if failed_attempts > 2:
                return "CONTEXT_LOST"

    if dopamine.is_app_session_over():
        return "SESSION_OVER"

    return "FEED_EXHAUSTED"
