"""This file provides all the toplevel functionality"""

import glob
import os
from typing import Any, Dict, List

PROJECTEER_FOLDER = ".projecteer"
PROJECT_CONFIG_FILE = "project.config"
PROJECT_SCRIPT_FILE = "project.scripts"
# these special variables are generated by projecteer
# SPECIAL = ["PROJECTEER_GENERATED_FILES"]

_allowDotFolders = ".**/**"
def findFilesToBeConfigured() -> List[str]:
    """Returns a List with the path of all Files that are going to be configured"""
    paths = []


    # configured sandwiched
    paths += glob.glob('**/*.configured.*', recursive=True)  # any sub dir
    paths += glob.glob(f'{_allowDotFolders}/*.configured.*', recursive=True)  # any .sub dir

    # configured in the beginning
    paths += glob.glob('**/configured.*', recursive=True)
    paths += glob.glob('**/.configured.*', recursive=True)
    paths += glob.glob(f'{_allowDotFolders}/configured.*', recursive=True)
    paths += glob.glob(f'{_allowDotFolders}/.configured.*', recursive=True)

    # configured in the end
    paths += glob.glob('**/*.configured', recursive=True)
    paths += glob.glob(f'{_allowDotFolders}/*.configured', recursive=True)
    return sorted(list(set(paths)))


def tryLoadAlreadyGeneratedFilePaths():
    os.makedirs(PROJECTEER_FOLDER, exist_ok=True)
    with open(PROJECTEER_FOLDER+"/generatedFiles", 'a') as f:
        pass
    with open(PROJECTEER_FOLDER+"/generatedFiles", "r") as f:
        return f.read().splitlines()

def generateSpecialVariables(projectConfig: Dict[str, Any]):
    # all filePaths that got generated
    allGeneratedFilePaths = tryLoadAlreadyGeneratedFilePaths()
    filePaths = findFilesToBeConfigured()

    # pregenerate all file paths to setup the GENERATED_FILES variable
    allGeneratedFilePaths = list(set(
        allGeneratedFilePaths +
        # replace os.sep with linux slash, because of gitignore working better with linux slash
        [path.replace(".configured", "").replace(os.sep, "/")
         for path in filePaths]
    ))
    allGeneratedFilePaths.sort()

    projectConfig["PROJECTEER_GENERATED_FILES"] = "\n".join(
        allGeneratedFilePaths)

    def updateGeneratedFilePaths():
        with open(PROJECTEER_FOLDER+"/generatedFiles", 'w') as f:
            f.writelines("\n".join(allGeneratedFilePaths))

    return updateGeneratedFilePaths