"""Routines to handles paths to dirs and files"""
from pathlib import Path
from typing import List
from typing import Tuple
from typing import Union


StrPath = Union[str, Path]


def file_paths(dirs: Tuple[StrPath, ...], filename: StrPath) -> List[Path]:
    """A list of all existing files with that name in those dirs

    >>> pythons = file_paths(('/bin', '/usr/bin', '/usr/local/bin'), 'python')
    >>> assert pythons[0].name == 'python'
    """
    result = []
    for dir_path in dir_paths(dirs):
        file_path = dir_path / filename
        if file_path.is_file():
            result.append(file_path)
    return result


def dir_paths(strings: Tuple[StrPath, ...]) -> List[Path]:
    """Convert all strings which are real directories to Path()

    Result does not have duplicates

    >>> bins = dir_paths(['/bin', '/jhkjhkj', '/usr/bin', '/bin'])
    >>> assert bins == [Path('/bin'), Path('/usr/bin')]
    """
    result = []
    for string in strings:
        p = Path(string)
        if p in result:
            continue
        if not p.is_dir():
            continue
        result.append(p)
    return result


def yamlise(path: StrPath) -> Path:
    """Replace the extension of that path with '.yaml'

    >>> assert yamlise("/path/to/fred.py") == Path("/path/to/fred.yaml")
    """
    try:
        path_ = Path(path)
    except TypeError:
        raise TypeError(f"{path!r} is not a path")
    return path_.parent / f"{path_.stem}.yaml"
