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:
        continue
    print_error("Template doesn't exists")
    exit()
  else:
    return cfg[template]["path"]

def copy_devenv(cfg_path: str, rel_path: str, force_copy: bool) -> 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)
  
  cwd_files = [file for file in os.listdir(os.getcwd())]
  template_files = [file for file in os.listdir(abs_path_str)]
  conflict_files = list(set(cwd_files) & set(template_files))

  if conflict_files:
    print_error(f"Conflicting file(s) found: {" ".join(conflict_files)}. Use --force to proceed anyway (this will overwrite conflicting files).")
  if not conflict_files or force_copy:
    if force_copy:
      print_warn("Force copying, this will overwrite conflicting files")
    for filename in template_files:
      src = f"{abs_path_str}/{filename}"
      dest = f"{os.getcwd()}/{filename}"
      if os.path.isdir(src):
        try:
          shutil.copytree(src, dest)
        except FileExistsError:
          shutil.rmtree(dest)
          shutil.copytree(src, dest)
      else:
        shutil.copyfile(src, dest)
