import logging

import tree_sitter_ruby
from tree_sitter import Language as TLanguage
from tree_sitter import Node, Parser, Query, QueryCursor

LOGGER = logging.getLogger(__name__)


def parse_ruby_with_tree_sitter(content: str) -> Node | None:
    try:
        parser_language = TLanguage(tree_sitter_ruby.language())
        parser = Parser(parser_language)
        result = parser.parse(content.encode("utf-8"))
    except Exception:
        LOGGER.exception("Failed to parse Ruby content with tree-sitter")
        return None
    else:
        return result.root_node if result.root_node else None


def find_method_calls(node: Node, method_name: str) -> list[Node]:
    try:
        language = TLanguage(tree_sitter_ruby.language())

        query_string = f"""
        (call
          method: (identifier) @method
          (#eq? @method "{method_name}")
        ) @call
        """

        query = Query(language, query_string)
        cursor = QueryCursor(query)

        captures = cursor.captures(node)

        return captures.get("call", [])
    except Exception:
        LOGGER.exception(
            "Failed to find method calls for method '%s'",
            method_name,
            extra={"method_name": method_name},
        )
        return []
