# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['foo', 'convert_app']

# %% ../nbs/00_core.ipynb 3
from bs4 import BeautifulSoup, NavigableString
import copy 

# %% ../nbs/00_core.ipynb 4
def foo(): pass

def convert_app(soup):
    """
    Replace anchor elements in the soup object based on the 'from' and 'to' attributes of each <app> element.
    
    Args:
        soup (bs4.BeautifulSoup): A Beautiful Soup object representing the parsed XML document.
        
    Returns:
        bs4.BeautifulSoup: A Beautiful Soup object with updated <app> elements.
    """
    # Create a copy of the soup object to avoid modifying the original
    soup_copied = copy.copy(soup)
    
    # Find all <app> elements in the copied soup object
    apps = soup_copied.find_all("app")
    
    # Iterate through each <app> element
    for app in apps:
        app_from = app["from"].replace("#", "")
        app_to = app["to"].replace("#", "")

        # Remove 'from' and 'to' attributes from the <app> element
        del app["from"]
        del app["to"]

        # Find the start and end anchor elements corresponding to 'from' and 'to' attributes
        anchor_start = soup_copied.find("anchor", {"xml:id": app_from})
        anchor_end = soup_copied.find("anchor", {"xml:id": app_to})

        if anchor_start is None or anchor_end is None:
            print(f"anchor_start or anchor_end is None (app_from: {app_from}, app_to: {app_to})")
            continue

        # Insert the <app> element before the start anchor element
        anchor_start.insert_before(app)

        # Remove elements and text nodes between the start and end anchor elements
        current_element = anchor_start
        while current_element != anchor_end:
            next_element = current_element.next_sibling
            if isinstance(current_element, NavigableString):
                current_element.extract()
            else:
                current_element.decompose()
            current_element = next_element

        # Remove the end anchor element
        anchor_end.decompose()

    return soup_copied
