

from mkdocs_addresses.auto_completion_handler import AutoCompletion, RefKind
from mkdocs_addresses.soup_excluding_codes import PluginSoupExcludingCodes
from mkdocs_addresses.static_handler.tracker_references import References





def gen_invalid_external_links_when_autorefs_used(
    soup:PluginSoupExcludingCodes,
    defined_refs:References,
):
    """
    The autorefs plugin is modifying the html of external links ()"[...][...]") into span tags:

             <span data-autorefs-identifier="identifier" ...>

    These are replacing the original markdown that the plugin expects to find in the html when
    a reference doesn't exist, while the others 'with existing ref) have already been replaced

    BUT these spans also appear in the html generated by mkdocstrings, and will be replaced with
    links only during a post processing step (I didn't search when exactly, but in on_page_context
    hooks, they are still present as <span>, and not <a>). So the invalid references must be searched
    for very carefully.
    """
    external_links = AutoCompletion.get_for(RefKind.Ext)
    links          = AutoCompletion.get_for(RefKind.Link)
    for span in soup.find_all('span'):
        if not span.has_attr("data-autorefs-identifier"):
            continue
        identifier = span['data-autorefs-identifier']
        link_id    = links.get_final_identifier(identifier)
        ext_id     = external_links.get_final_identifier(identifier)
        if not defined_refs.has_id(link_id) and not defined_refs.has_id(ext_id):
            # if neither an external ref nor a header generated by mkdocstrings, this is invalid
            yield identifier
