"""Shared helpers for cyclomatic complexity calculation."""

from __future__ import annotations

from typing import TYPE_CHECKING, Callable

if TYPE_CHECKING:
    from tree_sitter import Node


def count_decisions_generic(
    node: Node,
    top_func: Node,
    skip_check: Callable[[Node, Node], bool],
    decision_types: set[str],
    logical_ops: set[str] | None = None,
) -> int:
    """Generic decision counting function with language-specific skip and type configuration."""
    count = 0

    for child in node.children:
        if skip_check(child, top_func):
            continue

        if child.type in decision_types:
            count += 1
        elif child.type == "binary_expression" and logical_ops:
            count += sum(1 for sub in child.children if sub.type in logical_ops)

        count += count_decisions_generic(
            child, top_func, skip_check, decision_types, logical_ops
        )

    return count


def compute_cyclomatic_generic(
    count_decisions_fn: Callable[[Node, Node], int],
) -> Callable[[Node], int]:
    """Creates a cyclomatic complexity function with the given decision counter."""

    def _compute(func_node: Node) -> int:
        return 1 + count_decisions_fn(func_node, top_func=func_node)

    _compute.__doc__ = "Compute McCabe cyclomatic complexity for a function node.\n\nCC = 1 + number of decision points.\n"
    return _compute
