__author__ = "Millet Romain"
__copyright__ = "Copyright 2025+, Consortium MonPaGe"
__license__ = "Creative Commons 4.0 By-Nc-Sa"
__maintainer__ = "Roland Trouville"
__email__ = "contact.monpage@gmail.com"
__status__ = "Production"

import os

class GrapheTraceStack():

    @staticmethod
    def GenerateTraceOfPackage(root: str, path: str, filename: str):
        """
        Generates class and package UML diagrams (PNG) for a specific package using `pyreverse`.

        Args:
            root (str): Root directory of the project (usually the base folder containing packages).
            path (str): Output directory where the diagrams will be stored.
            filename (str): The package (folder) name to analyze.
        """
        dirClass = os.path.join(path, "byclass")
        dirPackage = os.path.join(path, "byPackage")

        if(not os.path.isdir(dirClass)):
            os.makedirs(dirClass)

        if(not os.path.isdir(dirPackage)):
            os.makedirs(dirPackage)

        os.system(f"pyreverse -o png -p {filename} {filename}")

        ClassName = f"classes_{filename}.png"
        PackageName = f"packages_{filename}.png"
        ClassPath = os.path.join(root, ClassName)
        PackagePath = os.path.join(root, PackageName)

        if(os.path.isfile(ClassPath)):
            os.system(f"move {ClassName} {dirClass+os.path.sep}")
            # os.rename(ClassPath, os.path.join(dirClass, ClassName))

        if(os.path.isfile(PackagePath)):
            os.system(f"move {PackageName} {dirPackage+os.path.sep}")
            # os.rename(PackagePath, os.path.join(dirPackage, PackageName))

    @staticmethod
    def GenerateTraceOfPackageAll(dest: str = "graphtracestack"):
        """
        Automatically generates UML class and package diagrams for all sub-packages
        (folders) in the current working directory.

        Args:
            dest (str): Name of the output folder that will store all diagrams.
                        Default is "graphtracestack".
        """
        root = os.getcwd()
        path = root+ os.path.sep+ dest
        os.makedirs(path, exist_ok=True)
        with open(path + os.path.sep + ".gitignore", 'w') as f:
            f.write("# Ignore everything in this directory\n")
            f.write("*\n")
            f.write("# Except this file\n")
            f.write("!.gitignore")
            pass
        for d in os.listdir(root):
            if os.path.isdir(os.path.join(root, d)) and d[0] != '.' :
                GrapheTraceStack.GenerateTraceOfPackage(root, path, d)

        print("GenerateTraceOfPackageAll has Finished")

GrapheTraceStack.GenerateTraceOfPackageAll()