from pathlib import Path
import ast
import re


def get_entry_point(filename: Path, prefix: str, import_path: str) -> list[str]:
    """Returns the entry point string for a given path.

    This looks for LIBTBX_SET_DISPATCHER_NAME, and a root function
    named 'run'. It can return multiple results for each file, if more
    than one dispatcher name is bound.

    Args:
        filename:
            The python file to parse. Will look for a run() function
            and any number of LIBTBX_SET_DISPATCHER_NAME.
        prefix: The prefix to output the entry point console script with
        import_path: The import path to get to the package the file is in

    Returns:
        A list of entry_point specifications
    """
    contents = filename.read_text(encoding="utf-8")
    tree = ast.parse(contents)
    # Find root functions named "run"
    has_run = any(
        x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == "run"
    )
    if not has_run:
        return []
    # Find if we need an alternate name via LIBTBX_SET_DISPATCHER_NAME
    alternate_names = re.findall(
        r"^#\s*LIBTBX_SET_DISPATCHER_NAME\s+(.*)$", contents, re.M
    )
    if alternate_names:
        return [f"{name}={import_path}.{filename.stem}:run" for name in alternate_names]

    return [f"{prefix}.{filename.stem}={import_path}.{filename.stem}:run"]