import re
from pathlib import Path

from dev_tools.build.licensing.deps import get_bundled_dependencies
from dev_tools.build.licensing.py_extra import get_extra_python_dependencies
from dev_tools.build.licensing.py_libs import get_dependencies_from_library_zip


def build_3rd_party_licensing(nano_root):
    """
    Create a licensing file with attribution included for all dependencies for the given distribution.
    """
    nano_root = Path(nano_root)
    deps = []
    deps.extend(get_dependencies_from_library_zip(nano_root / "lib"))
    deps.extend(get_extra_python_dependencies())

    deps.extend(get_bundled_dependencies(nano_root / "deps"))

    separator = ":" * 80
    separator = f"\n\n{separator}\n"
    items = [
        "Software included in this distribution of Clarabot Nano.\n"
        "NOTE: There is no coherent standard for specifying the contributions and legal\n"
        "documents of a software. The de facto rules that everyone tries to follow\n"
        "generate a lot of inaccuracies, so this list may be lacking.\n"
        "We made a strong effort to acknowledge all used software. If you're an author\n"
        "of some software in this distribution that is lacking proper attribution,\n"
        "please let us know!"
    ]
    deps.sort(key=lambda d: d.name.lower())
    items.extend(d.format() for d in deps)

    text = separator.join(items)
    # Make sure no ascii formatting characters remain in the text. Some of them prevent proper display on darwin.
    text = re.sub("[" + re.escape("".join(chr(i) for i in range(ord(" ")) if i != 10)) + "]", "", text)
    (nano_root / "THIRDPARTYSOFTWARE.txt").write_text(text, encoding="utf-8")
