import shutil
import subprocess
import sys
from pathlib import Path

from clarabot_nano.picoture import PICOTURE_JAR, PICOTURE_ROOT
from clarabot_nano.utility.path.java import java_compatible_absolute_path
from dev_tools.utility.git import path_has_uncommitted_changes_by_git

PICOTURE_LICENSES = PICOTURE_ROOT / "dist" / "THIRDPARTYSOFTWARE.txt"


def build_picoture(force: bool = True) -> Path:
    if not PICOTURE_JAR.is_file() or force or path_has_uncommitted_changes_by_git("clarabot_nano/picoture/"):
        # clean dist
        picoture_dist_dir = PICOTURE_JAR.parent
        if picoture_dist_dir.exists():
            shutil.rmtree(picoture_dist_dir)
        # check Java and Maven
        java_exe = shutil.which("java.exe" if sys.platform.startswith("win") else "java")
        if not java_exe:
            raise Exception("Java 11+ is needed to compile Pictorue")
        maven_exe = shutil.which("mvn.cmd" if sys.platform.startswith("win") else "mvn")
        if not maven_exe:
            raise Exception("Maven is needed to compile Pictorue")
        if sys.platform.startswith("win"):
            maven_exe = ["cmd.exe", "/C", maven_exe]
        else:
            maven_exe = [maven_exe]
        # build
        try:
            subprocess.check_output(
                [
                    *maven_exe,
                    "clean",
                    "package",
                    "dependency:copy-dependencies",
                    "license:download-licenses",
                    "license:add-third-party",
                ],
                stderr=subprocess.STDOUT,
                universal_newlines=True,
                # Even the cmd.exe utility has no support for UNC... who would have guessed...
                cwd=java_compatible_absolute_path(PICOTURE_ROOT),
            )
        except subprocess.CalledProcessError as e:
            print(e.stdout)
            raise e
        shutil.move(PICOTURE_ROOT / "target" / "dist", picoture_dist_dir)
        if not PICOTURE_JAR.is_file():
            raise Exception("Picoture.jar is not found after build.")
        if not PICOTURE_LICENSES.is_file():
            raise Exception("Third-party licenses file for Picoture is not found after build.")
        try:
            subprocess.check_output(
                [java_exe, "-jar", java_compatible_absolute_path(PICOTURE_JAR), "--version"],
                stderr=subprocess.STDOUT,
                universal_newlines=True,
            )
        except subprocess.CalledProcessError as e:
            print(e.stdout)
            raise e
    return PICOTURE_JAR
