from bs4 import BeautifulSoup


def clean_field_html(soup: BeautifulSoup) -> str:
    """
    Given the raw HTML for a field, such as "question" or "answer", neaten it
    up by removing anything that doesn't belong on the Anki card, such as
    outer <p> tags and internal links, and return the string of HTML that belongs
    in the field.
    """
    for elem in soup.find_all("a"):
        classes = elem.attrs.get('class', None)
        if (classes is not None
                and 'href' in elem.attrs
                and 'tc-tiddlylink-external' in classes):
            # External links lose their attributes but stay links.
            elem.attrs = {'href': elem.attrs['href']}
        else:
            # Internal links just get whacked and replaced with their plaintext.
            elem.replace_with(elem.get_text())

    return ''.join(str(i) for i in soup.contents)