from pathlib import PurePosixPath

_INDEX_STEMS: frozenset[str] = frozenset({"__init__", "index"})


def compute_module_path_segments(file_path: str, root: str | None = None) -> list[str]:
    posix = PurePosixPath(file_path)

    if root is not None:
        try:
            posix = posix.relative_to(PurePosixPath(root))
        except ValueError:
            pass
        else:
            stem = posix.stem
            if stem in _INDEX_STEMS:
                return list(posix.parts[:-1])
            return [*posix.parts[:-1], stem]

    stem = posix.stem
    if stem in _INDEX_STEMS:
        parent_name = posix.parent.name
        return [parent_name] if parent_name else []
    return [stem]
