"""Pattern detection utilities for code quality."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from tree_sitter import Language, Node, Query

from tree_sitter import Query, QueryCursor


def create_query(language: Language, source: str) -> Query:
    """Create a tree-sitter Query with error handling."""
    try:
        return Query(language, source)
    except Exception as e:
        raise ValueError(f"Invalid query: {e}") from e


def run_captures(query, root: Node) -> list[tuple[Node, str]]:
    """Query captures for a root node and return flat list of (node, capture_name)."""

    if root.child_count == 0:
        return []
    cursor = QueryCursor(query)
    result = []
    for capture_name, node in cursor.captures(root).items():
        for n in node:
            result.append((n, capture_name))
    return result
