import os
import shutil
import tomllib as toml
import colorama as clr

def print_error(msg): print(clr.Fore.RED +":: ERROR: " + clr.Fore.RESET + msg)
def print_warn(msg): print(clr.Fore.YELLOW + ":: WARN:" + clr.Fore.RESET + msg)

def parse(cfg_path, template) -> str:
  """
  Parses the config
  cfg_path: str = path to the dir containing the config (not the path to the config)
  template: str = selected template
  Returns the relative path in the config
  """
  try:
    with open(f"{cfg_path}/devenvcp.toml", "rb") as c:
      cfg = toml.load(c)
  except FileNotFoundError:
    raise configFileNotFound(f"No config.toml found at {cfg_path}")

  if template not in cfg:
    for t in cfg:
      try:
        if template in cfg[t]["aliases"]:
          return cfg[t]["path"]
      except KeyError as e:
        print_error("Template doesn't exists")
        exit()
  else:
    return cfg[template]["path"]


def copy_devenv(cfg_path, rel_path) -> None:
  """
  Copies the template's file in the cwd
  cfg_path:str = same config pathas parse()
  rel_path:str = relative path returned by parse()
  """
  abs_path_str = os.path.abspath(os.path.join(cfg_path, rel_path))
  path = os.fsencode(abs_path_str)
  for filename in os.listdir(path):
    shutil.copyfile(f"{abs_path_str}/{filename.decode('utf-8')}", f"{os.getcwd()}/{filename.decode("utf-8")}")
