import pathlib
from typing import Optional
from typing import List


def is_python_file(
    file_path: pathlib.Path, python_bins: Optional[List[str]] = None
) -> bool:
    """Check if a file is a Python file.

    This function will do it's best to determine Whether a file is a Python file.

    It will:
      - Check if the extension is .py
      - Check if the first line is a #! line and Whether any of the python_bin names are in the line.

    :param file_path: The path to check.
    :param python_bins: Optional list of python executable names.
    :return: Whether this is a Python file.

    """
    ext = file_path.suffix

    if ext == ".py":
        return True

    if ext == ".pyc":
        return False

    # Try to peak at the first line.
    with file_path.open() as handle:
        try:
            first_line = handle.readline()

        except UnicodeDecodeError:
            return False

    python_bins = ["python"] if python_bins is None else python_bins

    # If the file is a script check if any of the python bin names are in the command.
    if first_line.startswith("#!"):
        for python_bin in python_bins:
            if python_bin in first_line:
                return True

    return False