"""Shared helpers for parsers."""

from __future__ import annotations

from typing import TYPE_CHECKING, Callable

if TYPE_CHECKING:
    from tree_sitter import Language, Node


def parse_with_language(language: Language, code: str) -> Node:
    """Parse source code with a given language and return the tree root node."""
    from tree_sitter import Parser

    parser = Parser(language)
    tree = parser.parse(code.encode())
    return tree.root_node


def collect_functions_wrapper(
    recursive_fn: Callable[[Node, list[Node]], None],
) -> Callable[[Node], list[Node]]:
    """Create a collect_functions function from language-specific recursive collection."""

    def collect_functions(root: Node) -> list[Node]:
        functions = []
        recursive_fn(root, functions)
        return functions

    collect_functions.__doc__ = "Collect all function nodes at all depths."
    return collect_functions


def func_param_count_wrapper(
    func_param_count_fn: Callable[[Node], int],
) -> Callable[[Node], int]:
    """Create wrapper function for parameter count."""

    def func_param_count(node: Node) -> int:
        return func_param_count_fn(node)

    func_param_count.__doc__ = "Extract parameter count from a function node."
    return func_param_count
