import json
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
from dev_tools.picoture.script import PICOTURE_DEPENDENCY_LICENSE


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)

    picoture_dependency_license = json.loads(PICOTURE_DEPENDENCY_LICENSE.read_text(encoding="utf-8"))
    picoture_deps = "\n".join(
        sorted(
            "%s - %s" % (dep["name"], ", ".join(lic["name"] for lic in dep["licenses"]))
            for dep in picoture_dependency_license["dependencies"]
        )
    )
    items.append(f"Dependencies of Picoture:\n{picoture_deps}\n")

    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")
