import subprocess
from pathlib import Path

from clarabot_nano_common.utility.path.java import java_compatible_absolute_path

from clarabot_nano.utility.java import get_java_version_output, parse_java_major_version
from dev_tools.build.sign.file import sign_file_for_authenticity


def get_java_version(major_version_only=False):
    output = get_java_version_output()
    major = parse_java_major_version(output)
    assert major and major >= 11, f"{major}\n{output}"
    if major_version_only:
        return major
    return "\t" + "\n\t".join(line.strip() for line in output.split("\n") if line)


def get_java_modules():
    return [
        line.rpartition("@")[0]
        for line in subprocess.check_output(
            ["java", "--list-modules"], encoding="utf-8", universal_newlines=True
        ).split("\n")
        if line
    ]


def build_deps_jre(deps_dir: Path, java_modules, skip_signing: bool = False):
    jre_dir = deps_dir / "jre"
    subprocess.check_call(
        [
            "jlink",
            "--no-header-files",
            "--no-man-pages",
            "--compress=2",
            "--strip-debug",
            "--add-modules",
            ",".join(java_modules),
            "--output",
            java_compatible_absolute_path(jre_dir),
        ]
    )
    if not skip_signing:
        sign_file_for_authenticity(*[item for item in (jre_dir / "bin").iterdir() if item.name.endswith(".exe")])
    return jre_dir
