from page_scraper.core.utils import process_breadcrumbs, infer_categories


def has_type(node: dict, type_name: str) -> bool:
    t = node.get("@type", [])

    if isinstance(t, str):
        return t == type_name
    return type_name in t

def has_types(node: dict, *type_names: str) -> bool:
    t = node.get("@type", [])
    if isinstance(t, str):
        return t in type_names

    return any(t_type in type_names for t_type in t)


def has_attrs(node: dict, *keys) -> bool:
    return any(node.get(key) for key in keys)

def path_contains(path: tuple, *keys) -> bool:
    return any(k in path for k in keys)


def has_bread_crumbs(node: dict):
    return has_type(node,"BreadcrumbList")

def get_categories(bread_crumbs:list[dict]) -> list[dict]:
    return infer_categories(bread_crumbs)

def build_entity_index(nodes: list[dict]) -> dict[str, dict]:
    index = {}
    for entry in nodes:
        node = entry["node"] if isinstance(entry, dict) and "node" in entry else entry
        node_id = node.get("@id")
        if node_id:
            index[node_id] = node
    return index

def extract_breadcrumbs(nodes:list) -> list:
    result = []
    for entry in nodes:
        node = entry["node"]
        if not has_bread_crumbs(node):
            continue
        return process_breadcrumbs(node)
        # result.append(cats)
    return result