"""McCabe cyclomatic complexity for TypeScript."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from tree_sitter import Node

import vibelexity.metrics.cyclomatic.shared as shared

_TS_SKIP_TYPES = {
    "function_declaration",
    "function_expression",
    "method_definition",
    "generator_function_declaration",
    "class_declaration",
    "class_expression",
    "arrow_function",
}

_TS_DECISION_TYPES = {
    "if_statement",
    "for_statement",
    "for_in_statement",
    "while_statement",
    "do_statement",
    "switch_case",
    "catch_clause",
    "ternary_expression",
}

_TS_LOGICAL_OPS = {"&&", "||", "??"}


def _ts_skip_check(child: Node, top_func: Node) -> bool:
    """Skip nested function declarations."""
    if child.type in _TS_SKIP_TYPES and child is not top_func:
        return True
    return False


def _count_decisions(node: Node, top_func: Node) -> int:
    return shared.count_decisions_generic(
        node, top_func, _ts_skip_check, _TS_DECISION_TYPES, _TS_LOGICAL_OPS
    )


compute_cyclomatic_ts = shared.compute_cyclomatic_generic(_count_decisions)
