import logging
import random
from time import sleep

from colorama import Fore, Style

from GramAddict.core.version import __version__

logger = logging.getLogger(__name__)


def sanitize_text(text):
    return (text or "").strip()


def random_sleep(inf=1.0, sup=3.0, modulable=True):
    from GramAddict.core.config import Config

    configs = Config()
    try:
        multiplier = float(getattr(configs.args, "speed_multiplier", 1.0))
    except (ValueError, TypeError):
        multiplier = 1.0
    delay = random.uniform(inf, sup) / (multiplier if modulable else 1.0)
    sleep(max(delay, 0.2))


def config_examples():
    logger.debug("Config examples handled by documentation.")


def check_if_updated():
    logger.info(f"GramAddict v.{__version__}", extra={"color": f"{Style.BRIGHT}{Fore.MAGENTA}"})


def get_instagram_version(device):
    try:
        output = device.shell(f"dumpsys package {device.app_id}").output
        import re

        version_match = re.findall("versionName=(\\S+)", output)
        return version_match[0] if version_match else "unknown"
    except Exception:
        return "unknown"


def close_instagram(device, force_kill=False):
    if force_kill:
        logger.info("Force-closing Instagram app to clean session state.")
        try:
            device.app_stop(device.app_id)
        except Exception as e:
            logger.debug(f"Error closing app: {e}")
    else:
        logger.info("Backgrounding Instagram app (minimizing).")
        try:
            device.press("home")
        except Exception as e:
            logger.debug(f"Error pressing home: {e}")


def open_instagram(device, force_restart=False):
    if force_restart:
        logger.info("Opening Instagram app (Fresh Start).")
        close_instagram(device, force_kill=True)
        device.app_start(device.app_id)
        random_sleep(3, 5, modulable=False)
    else:
        logger.info("Bringing Instagram app to foreground.")
        device.app_start(device.app_id)
        random_sleep(1, 2, modulable=False)
    return True


def set_time_delta(args):
    args.time_delta_session = random.randint(-300, 300)


def wait_for_next_session(time_left, session_state, sessions, device):
    logger.info(f"Waiting {time_left} until next working hours.")
    sleep(60)


def get_value(count, name, default=0):
    if count is None:
        return default
    if isinstance(count, (int, float)):
        return count
    try:
        if "-" in str(count):
            parts = str(count).split("-")
            return random.randint(int(parts[0]), int(parts[1]))
        return int(count)
    except Exception:
        return default


def is_ad(xml_hierarchy: str, cognitive_stack: dict = None) -> bool:
    """
    Checks if the current view contains an advertisement using autonomous learning.

    If a cognitive_stack is provided, it uses the Telepathic Engine for
    semantic classification (Zero-Latency vector lookup).
    """
    import re
    import xml.etree.ElementTree as ET

    if cognitive_stack:
        telepathic = cognitive_stack.get("telepathic")
        if telepathic:
            # Semantic classification (ZERO hardcoded strings)
            classification = telepathic.classify_screen_content(xml_hierarchy, "sponsored_content")
            if classification == "sponsored":
                return True

    # --- Legacy Fallback ---
    # Regex word boundaries prevent false positives like 'brunette_abroad'
    AD_RESOURCE_IDS = [
        "com.instagram.android:id/ad_cta_button",
        "com.instagram.android:id/sponsored_label",
        "com.instagram.android:id/clips_single_image_ads_media_content",
        "com.instagram.android:id/ads_carousel_progress_bar",
        "com.instagram.android:id/ad_not_interested_button",
    ]

    AD_MARKERS = [r"\b(sponsored|ad|advertisement)\b", r"\b(gesponsert|anzeige|werbung)\b"]

    try:
        root = ET.fromstring(xml_hierarchy)
        for node in root.iter("node"):
            attrib = node.attrib
            content_desc = attrib.get("content-desc", "")
            text = attrib.get("text", "")
            res_id = attrib.get("resource-id", "")

            # Structural check (Instagram specific)
            if any(marker_id in res_id for marker_id in AD_RESOURCE_IDS):
                return True

            # Content check (Legacy)
            searchable = f"{content_desc} {text}".lower()
            for pattern in AD_MARKERS:
                if re.search(pattern, searchable):
                    return True
    except Exception:
        pass

    return False
