import glob
import subprocess
import sys
import os
import shutil
from ninja import Writer
import pathlib

LIBRARIES = [ "comp" ]

COMPILER_CMD = f"-c -Cpp_exceptions off -maxerrors 1 -nodefaults -proc gekko -fp hard -lang=c++ -ipa file -inline auto -O4,s -rtti off -align powerpc -enum int -msgstyle gcc -I- -i include"
COMPILER_PATH = pathlib.Path("Compiler/mwcceppc.exe")

SOURCE_FILE_EXTS = [ ".c", ".cpp", ".s" ]

def cleanLibraryBuild(lib):
    if lib == "comp":
        build_path = "build"

    if os.path.exists(build_path):
        shutil.rmtree(build_path)

def fixLibName(name):
    return name.replace("++", "pp")

def genNinja(tasks):
    with open('build.ninja', 'w') as ninja_file:
        ninja_writer = Writer(ninja_file)
        for lib in LIBRARIES:
            libName = fixLibName(lib)
            cmd = f'{COMPILER_PATH} {COMPILER_CMD} $in -o $out'
            if os.name != "nt":
                wine = os.getenv("WINE", "wine")
                cmd = f"{wine} {cmd}"
            ninja_writer.rule(f"compile_{libName}", command=cmd, description=f'Compiling $in')

        for task in tasks:
            lib, source_path, build_path = task
            libName = fixLibName(lib)
            ninja_writer.build(outputs=[build_path], rule=f"compile_{libName}", inputs=[source_path])

def collectTasks(name, path):
    compile_tasks = list()

    if name == "comp":
        path = "source"

    for root, dirs, files in os.walk(path):
        for file in files:
            for ext in SOURCE_FILE_EXTS:
                if file.endswith(ext):
                    source_path = os.path.join(root, file)
                    build_path = source_path.replace("source", "build", 1).replace(ext, ".o")

                    os.makedirs(os.path.dirname(build_path), exist_ok=True)
                    compile_tasks.append((name, source_path, build_path))

    return compile_tasks

clean = '-clean' in sys.argv

if clean:
    for lib in LIBRARIES:
        cleanLibraryBuild(lib)

all_tasks = []
for lib in LIBRARIES:
    tasks = collectTasks(lib, f"libs/{lib}/source")
    all_tasks.extend(tasks)

genNinja(all_tasks)
subprocess.run(['ninja', '-f', 'build.ninja'], check=True)