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

logger = logging.getLogger(__name__)


class ZeroLatencyEngine:
    """
    The Zero-Latency Executor
    This engine receives a pre-compiled heuristic (Regex/XPath) from the memory cache
    and executes it against the local XML layout in under 5ms.
    It is completely deterministic. No LLM calls happen here.
    """

    def __init__(self, device):
        self.device = device

    def evaluate_heuristic(self, rule: dict, context_xml: str):
        """
        Executes a compiled heuristic rule against the provided XML dump.
        Rule schema: {"rule_type": "regex", "target_attribute": "text", "pattern": "..."}
        Returns True/False for intent (e.g. is_ad, is_liked), or extracted strings (e.g. post_owner).
        """
        if not rule or not context_xml:
            return None

        rule_type = rule.get("rule_type", "regex")
        target_attr = rule.get("target_attribute", "text")
        pattern = rule.get("pattern", "")

        if not pattern:
            return None

        try:
            root = ET.fromstring(context_xml)

            if rule_type == "regex":
                # Remove (?i) if present because we compile with re.IGNORECASE anyway
                clean_pattern = pattern.replace("(?i)", "")
                regex = re.compile(clean_pattern, re.IGNORECASE)
                for node in root.iter("node"):
                    val = ""
                    if target_attr == "text":
                        val = node.attrib.get("text", "")
                    elif target_attr == "content-desc":
                        val = node.attrib.get("content-desc", "")
                    elif target_attr == "resource-id":
                        val = node.attrib.get("resource-id", "")
                    else:
                        # Fallback all
                        val_text = node.attrib.get("text", "")
                        val_desc = node.attrib.get("content-desc", "")
                        val_resid = node.attrib.get("resource-id", "")
                        val = f"{val_text} | {val_desc} | {val_resid}"

                    match = regex.search(val)
                    if match:
                        if len(match.groups()) > 0:
                            return match.group(1)  # Return captured group (e.g., username)
                        return True  # Return boolean existence (e.g. is_ad)

            elif rule_type == "xpath":
                # Basic xpath parsing over ET
                nodes = root.findall(pattern)
                if nodes:
                    return nodes[0].attrib.get(target_attr, "")

            return False  # Rule ran but found nothing

        except Exception as e:
            logger.debug(f"ZeroLatencyEngine failed to evaluate rule {pattern}: {e}")
            return None
