from pathlib import Path
from rougail import Rougail, RougailConfig
import shutil


TUTORIAL_ROUGAIL = "../rougail-tutorials_builder/examples/"
TMP = Path("tutorial_tmp")
RESULT = Path("tests") / "result_tutorial"

def test_tutorial():
    structural_files = TMP / "structural"
    types_files = TMP / "types"
    if TMP.is_dir():
        shutil.rmtree(TMP)
    structural_files.mkdir(parents=True)
    types_files.mkdir()
    namespace_support = False
    RESULT.mkdir(exist_ok=True)
    for exercice in sorted(Path(TUTORIAL_ROUGAIL).iterdir()):
        result_files = RESULT / exercice.name
        result_files.mkdir(exist_ok=True)
        tiramisu_file = result_files / "tiramisu.py"
        if (exercice / "namespace").is_file():
            namespace_support = True
        types_src_dir = exercice / "types"
        if types_src_dir.is_dir():
            for types in types_src_dir.iterdir():
                for t in types.iterdir():
                    shutil.copy(t, types_files / t.name)
        for namespace in (exercice / "structural_files").iterdir():
            if not namespace.is_dir():
                continue
            structure_directory = structural_files / namespace.name
            structure_directory.mkdir(exist_ok=True)
            for filename in namespace.iterdir():
                if not filename.name.endswith('.yml'):
                    continue
                shutil.copyfile(filename, structure_directory / filename.name)
        rougailconfig = RougailConfig.copy()
        if namespace_support:
            rougailconfig['main_namespace'] = 'firefox'
            rougailconfig['main_structural_directories'] = [str(structural_files / "firefox")]
            if (structural_files / 'foxyproxy').is_dir():
                rougailconfig['extra_namespaces'] = {"foxyproxy": [str(structural_files / "foxyproxy")]}  # extra_namespaces
        else:
            rougailconfig['main_namespace'] = None
            rougailconfig['main_structural_directories'] = [str(structure_directory)]
        types = [str(t) for t in types_files.iterdir()]
        if types:
            rougailconfig['types'] = types
        tiramisu_tmp = TMP / "tiramisu.py"
        try:
            rougailconfig['tiramisu_cache'] = str(tiramisu_tmp)
        except:
            rougailconfig['cli.tiramisu_cache'] = str(tiramisu_tmp)
        #
        rougail = Rougail(rougailconfig)
        rougail.run()
        #
        if not tiramisu_file.is_file():
            shutil.copyfile(tiramisu_tmp, tiramisu_file)
        with open(tiramisu_tmp, 'r') as fh:
            tiramisu_objects = fh.read()
        with open(tiramisu_file, 'r') as fh:
            tiramisu_objects_ori = fh.read()
        assert tiramisu_objects == tiramisu_objects_ori, f'{exercice.name} -> {tiramisu_file}'
        tiramisu_tmp.unlink()
    shutil.rmtree(TMP)
