# automatically generated by auxilium
import contextlib
import sys
import typing as tp
from pathlib import Path

from bs4 import BeautifulSoup


def main() -> None:
    filename = Path(sys.argv[1])

    with modify_html_file(filename) as soup:
        rename_external_link(soup)
        switch_internal_external_link(soup)
        remove_private_module_parts(soup)


@contextlib.contextmanager
def modify_html_file(filename: Path) -> tp.Iterator[BeautifulSoup]:
    with open(filename, "rb") as f:
        soup = BeautifulSoup(f, "html.parser")
    yield soup
    with open(filename, "wb") as f:
        f.write(soup.encode(formatter="html"))


def rename_external_link(soup: BeautifulSoup) -> None:
    for x in soup.select(".reference.external .viewcode-link .pre"):
        x.string = "[git]"


def switch_internal_external_link(soup: BeautifulSoup) -> None:
    for x in soup.select(".sig.sig-object.py"):
        to_add = list(x.children)
        external = to_add[-3]
        internal = to_add[-2]

        if "internal" in internal["class"] and "external" in external["class"]:
            to_add[-3] = internal
            to_add[-2] = external

            x.clear()

            for i, y in enumerate(to_add):
                x.insert(i, y)


def remove_private_module_parts(soup: BeautifulSoup) -> None:
    for x in soup.select(".reference.internal"):
        title = x.get("title")
        if not title:
            continue

        if "._" in x.string:
            x.string = ".".join(x for x in x.string.split(".") if not x.startswith("_"))
            x["title"] = x.string

    for x in soup.select(".reference.external"):
        title = x.get("title")
        if not title:
            continue
        if "._" in x.string:
            x.string = ".".join(x for x in x.string.split(".") if not x.startswith("_"))


if __name__ == "__main__":
    main()
