from pathlib import Path


def get_csl_or_template(key: str, val: str, dir: Path):
    """Get CSL or template file according to the value :code:`val`

    Args:
        key: One of "csl" or "template"
        val: The file path or file stem to search for, essentially
             the CSL or template name.
        dir: The directory in which to search

    The CSL or template file can be searched in a given directory with the file
    name or file name without suffix with some rules according to naming
    conventions.

    E.g., :code:`get_csl_or_template("csl", "ieee", "some_dir")` will search for
    "ieee" and "ieee.csl" in "some_dir".
    While, :code:`get_csl_or_template("template", "ieee", "some_dir")` will search for
    "default.ieee" and "ieee.template" in those directories

    """
    v = val
    if dir.joinpath(v).exists():
        v = str(dir.joinpath(v))
    else:
        candidates = [x.name for x in dir.iterdir()
                      if v in str(x)]
        if key == "template":
            if f"default.{v}" in candidates:
                v = str(dir.joinpath(f"default.{v}"))
            elif f"{v}.template" in candidates:
                v = str(dir.joinpath(f"{v}.template"))
        elif key == "csl":
            if f"{v}" in candidates:
                v = str(dir.joinpath(f"{v}"))
            elif f"{v}.csl" in candidates:
                v = str(dir.joinpath(f"{v}.csl"))
    return v