import logging
import re
import time
import xml.etree.ElementTree as ET

logger = logging.getLogger(__name__)


def verify_and_switch_account(device, nav_graph, target_username):
    logger.info(f"🛂 [Identity Guard] Verifying if active account matches target: '{target_username}'")

    # 1. Navigate to OwnProfile to reliably check identity
    success = nav_graph.navigate_to("OwnProfile", zero_engine=None)
    if not success:
        logger.error("❌ [Identity Guard] Failed to reach OwnProfile to verify account.")
        return False

    time.sleep(2.0)
    xml_dump = device.dump_hierarchy()

    # 2. Check if already active
    # The action_bar_title on OwnProfile contains the username.
    is_active = False
    try:
        clean_xml = re.sub(r"<\?xml.*?\?>", "", xml_dump).strip()
        root = ET.fromstring(clean_xml)
        for elem in root.iter("node"):
            res_id = elem.attrib.get("resource-id", "")
            text = elem.attrib.get("text", "").lower()
            if "action_bar_title" in res_id and target_username.lower() in text:
                is_active = True
                break
    except Exception as e:
        logger.warning(f"Error parsing XML for identity check: {e}")

    if is_active:
        logger.info(f"✅ [Identity Guard] Successfully verified active account is already '{target_username}'.")
        return True

    logger.warning(f"🔄 [Identity Guard] Account mismatch detected! Switching to '{target_username}'...")

    # 3. Find the Profile Tab to long press using Telepathic Engine (Blank Start)
    profile_tab = None
    try:
        from GramAddict.core.telepathic_engine import TelepathicEngine

        telepath = TelepathicEngine.get_instance()

        # We ask the semantic engine to find the profile tab, ensuring 100% ID-agnostic behavior
        profile_tab_node = telepath.find_best_node(xml_dump, "tap profile tab", min_threshold=0.3, device=device)
        if profile_tab_node:
            profile_tab = (profile_tab_node["x"], profile_tab_node["y"])
    except Exception as e:
        logger.warning(f"Error resolving profile tab via telepathic engine: {e}")

    if not profile_tab:
        logger.error("❌ [Identity Guard] Cannot find profile_tab semantically to initiate account switch!")
        return False

    # Long press to open account selector
    device.long_click(profile_tab[0], profile_tab[1], 1.5)
    time.sleep(3.0)

    # 4. Find the target account in the selector list
    xml_dump = device.dump_hierarchy()
    account_node = None
    try:
        clean_xml = re.sub(r"<\?xml.*?\?>", "", xml_dump).strip()
        root = ET.fromstring(clean_xml)
        for elem in root.iter("node"):
            text = elem.attrib.get("text", "").lower()
            content_desc = elem.attrib.get("content-desc", "").lower()

            # Exact match or starts with username followed by spaces/punctuation
            target_l = target_username.lower()
            is_match = False

            if text == target_l or content_desc == target_l:
                is_match = True
            elif target_l in text.split() or target_l in content_desc.split():
                is_match = True
            elif text.startswith(target_l + "\n") or text.startswith(target_l + " "):
                is_match = True
            elif target_l in text or target_l in content_desc:
                # Fallback purely to literal inclusion (might match backups, but better than failing)
                is_match = True

            if is_match:
                bounds_str = elem.attrib.get("bounds")
                if bounds_str:
                    coords = re.findall(r"\d+", bounds_str)
                    if len(coords) == 4:
                        x = (int(coords[0]) + int(coords[2])) // 2
                        y = (int(coords[1]) + int(coords[3])) // 2
                        account_node = (x, y)
                        break
    except Exception:
        pass

    if account_node:
        logger.info(f"🖱️ [Identity Guard] Found account '{target_username}' in selector. Tapping!")
        device.click(account_node[0], account_node[1])
        time.sleep(6.0)  # Wait heavily for app to reload context
        nav_graph.current_state = "UNKNOWN"  # Force graph to re-evaluate after massive state shift
        return True
    else:
        logger.error(
            f"❌ [Identity Guard] Target account '{target_username}' not found in the account switcher! Is it logged in?"
        )
        try:
            from GramAddict.core.diagnostic_dump import dump_ui_state

            dump_ui_state(
                device, "identity_guard", {"reason": "account_not_found_in_bottom_sheet", "target": target_username}
            )
        except Exception:
            pass
        # Escape the bottom sheet
        device.press("back")
        return False
