from __future__ import annotations

import fnmatch
import re

import tree_sitter as ts
import tree_sitter_cpp as tscpp

from .base import (
    ClassInfo,
    FunctionInfo,
    ImportInfo,
    installed_parser_version,
    mask_inactive_preprocessor_code,
    ParseResult,
    ReferenceInfo,
    SymbolInfo,
    TypeBindingInfo,
    populate_tree_sitter_metadata,
    detect_visibility,
    require_valid_tree,
    extract_macro_reference_facts,
)


class CppRule:
    @property
    def language_name(self) -> str:
        return "cpp"

    @property
    def file_extensions(self) -> list[str]:
        return [".cpp", ".cc", ".cxx", ".hpp", ".hxx"]

    @property
    def test_patterns(self) -> list[str]:
        return [
            "test_*.cpp", "*_test.cpp",
            "test_*.cc", "*_test.cc",
            "test_*.cxx", "*_test.cxx",
        ]

    def is_test_file(self, file_path: str) -> bool:
        name = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path
        return any(fnmatch.fnmatch(name, p) for p in self.test_patterns)

    def parse(self, source: bytes, file_path: str) -> ParseResult:
        lang = ts.Language(tscpp.language())
        parser = ts.Parser(lang)
        parse_source = source if not source or source.endswith(b"\n") else source + b"\n"
        parse_source = mask_inactive_preprocessor_code(parse_source)
        parse_source = self._mask_module_syntax(parse_source)
        tree = parser.parse(parse_source)
        root = tree.root_node
        require_valid_tree(
            root,
            file_path,
            allow_recovery=True,
        )

        result = ParseResult()
        self._walk_node(root, parse_source, result)
        self._collect_symbols(
            root,
            result,
            parse_source,
            guard_macros=self._include_guard_macros(parse_source),
        )
        populate_tree_sitter_metadata(
            result,
            root,
            source_bytes=len(source),
            parser_name="tree-sitter-cpp",
            parser_version=installed_parser_version("tree-sitter-cpp"),
        )
        return result

    @staticmethod
    def _mask_module_syntax(source: bytes) -> bytes:
        """Mask standard C++ module markers unsupported by tree-sitter-cpp."""
        output: list[bytes] = []
        for line in source.splitlines(keepends=True):
            stripped = line.lstrip()
            if re.match(
                rb"(?:(?:export\s+)?module|(?:export\s+)?import)\b",
                stripped,
            ):
                output.append(bytes(
                    byte if byte in (10, 13) else 32
                    for byte in line
                ))
                continue
            export_match = re.match(rb"(\s*)export\s+", line)
            if export_match:
                start = len(export_match.group(1))
                mutable = bytearray(line)
                mutable[start:start + len(b"export")] = b" " * len(b"export")
                line = bytes(mutable)
            output.append(line)
        return b"".join(output)

    @staticmethod
    def _include_guard_macros(source: bytes) -> set[str]:
        """Detect a conventional leading C/C++ header guard."""
        significant: list[str] = []
        in_block_comment = False
        for raw_line in source[:8192].decode(errors="replace").splitlines():
            line = raw_line.strip()
            while line:
                if in_block_comment:
                    end = line.find("*/")
                    if end < 0:
                        line = ""
                        break
                    line = line[end + 2:].lstrip()
                    in_block_comment = False
                    continue
                if line.startswith("/*"):
                    end = line.find("*/", 2)
                    if end < 0:
                        in_block_comment = True
                        line = ""
                        break
                    line = line[end + 2:].lstrip()
                    continue
                if line.startswith("//"):
                    line = ""
                break
            if not line:
                continue
            significant.append(line)
            if len(significant) == 2:
                break
        if len(significant) != 2:
            return set()
        opening = re.fullmatch(r"#\s*ifndef\s+([A-Za-z_]\w*)", significant[0])
        if not opening:
            return set()
        name = opening.group(1)
        return (
            {name}
            if re.match(rf"#\s*define\s+{re.escape(name)}\b", significant[1])
            else set()
        )

    def _collect_symbols(
        self,
        root: ts.Node,
        result: ParseResult,
        source: bytes,
        *,
        guard_macros: set[str],
    ) -> None:
        """Collect C++ values/types not represented by FunctionNode/ClassNode."""

        def visit(
            node: ts.Node,
            *,
            conds: list[str],
            else_conds: list[str] | None = None,
            owner_name: str | None = None,
            visibility: str = "public",
            namespace_path: str = "",
        ) -> None:
            current_visibility = visibility
            for child in node.children:
                if child.type in {"preproc_ifdef", "preproc_if"}:
                    guard = [
                        item for item in self._extract_preproc_cond(child)
                        if item.lstrip("!") not in guard_macros
                    ]
                    visit(
                        child,
                        conds=conds + guard,
                        else_conds=self._negated_branch_conditions(conds, guard),
                        owner_name=owner_name,
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type == "preproc_elif":
                    outer = else_conds if else_conds is not None else conds
                    guard = self._extract_preproc_cond(child)
                    visit(
                        child,
                        conds=outer + guard,
                        else_conds=self._negated_branch_conditions(outer, guard),
                        owner_name=owner_name,
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type == "preproc_else":
                    visit(
                        child,
                        conds=else_conds if else_conds is not None else conds,
                        owner_name=owner_name,
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type == "ERROR":
                    visit(
                        child,
                        conds=conds,
                        else_conds=else_conds,
                        owner_name=owner_name,
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type == "access_specifier":
                    current_visibility = self._node_text(child).rstrip(":") or current_visibility
                    continue
                if child.type in {"preproc_def", "preproc_function_def"}:
                    name_node = child.child_by_field_name("name")
                    name = self._node_text(name_node)
                    if name and name not in guard_macros:
                        value_node = child.child_by_field_name("value")
                        self._append_cpp_symbol(
                            child,
                            result,
                            name=name,
                            kind=(
                                "function_macro"
                                if child.type == "preproc_function_def"
                                else "macro"
                            ),
                            owner_name=owner_name,
                            visibility=current_visibility,
                            is_exported=current_visibility == "public",
                            conds=conds,
                            value=self._node_text(value_node) or None,
                            references=extract_macro_reference_facts(value_node, source),
                        )
                    continue
                if child.type == "namespace_definition":
                    name = self._node_text(child.child_by_field_name("name"))
                    qualified = "::".join(part for part in (namespace_path, name) if part)
                    if name:
                        self._append_cpp_symbol(
                            child,
                            result,
                            name=qualified or name,
                            kind="namespace",
                            owner_name=None,
                            visibility="public",
                            is_exported=True,
                            conds=conds,
                        )
                    visit(
                        child,
                        conds=conds,
                        owner_name=None,
                        visibility="public",
                        namespace_path=qualified,
                    )
                    continue
                if child.type in {"class_specifier", "struct_specifier", "union_specifier"}:
                    name = self._cpp_type_name(child)
                    body = child.child_by_field_name("body")
                    if body is not None:
                        visit(
                            body,
                            conds=conds,
                            owner_name=name or owner_name,
                            visibility=("private" if child.type == "class_specifier" else "public"),
                            namespace_path=namespace_path,
                        )
                    continue
                if child.type == "enum_specifier":
                    name = self._cpp_type_name(child)
                    visit(
                        child,
                        conds=conds,
                        owner_name=name or owner_name,
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type == "enumerator":
                    name = self._node_text(child.child_by_field_name("name"))
                    value_node = child.child_by_field_name("value")
                    self._append_cpp_symbol(
                        child,
                        result,
                        name=name,
                        kind="enum_constant",
                        owner_name=owner_name,
                        visibility=current_visibility,
                        is_exported=current_visibility == "public",
                        conds=conds,
                        value=self._node_text(value_node) or None,
                    )
                    continue
                if child.type in {"type_definition", "alias_declaration"}:
                    aliases = self._cpp_declaration_names(child)
                    if child.type == "alias_declaration" and not aliases:
                        aliases = [self._node_text(child.child_by_field_name("name"))]
                    for name in dict.fromkeys(item for item in aliases if item):
                        function_declarator = self._find_function_declarator(child)
                        self._append_cpp_symbol(
                            child,
                            result,
                            name=name,
                            kind=(
                                "type_alias"
                                if child.type == "alias_declaration"
                                else "typedef_function_pointer"
                                if function_declarator is not None
                                and self._is_function_pointer_declarator(function_declarator)
                                else "typedef"
                            ),
                            owner_name=owner_name,
                            visibility=current_visibility,
                            is_exported=current_visibility == "public",
                            conds=conds,
                            data_type=self._cpp_declaration_type(child),
                        )
                    # Continue into an inline record/enum to retain fields and
                    # enumerators owned by the alias.
                    visit(
                        child,
                        conds=conds,
                        owner_name=(aliases[0] if aliases else owner_name),
                        visibility=current_visibility,
                        namespace_path=namespace_path,
                    )
                    continue
                if child.type in {"declaration", "field_declaration"}:
                    function_declarator = self._find_function_declarator(child)
                    is_function_pointer = (
                        function_declarator is not None
                        and self._is_function_pointer_declarator(function_declarator)
                    )
                    if function_declarator is None or is_function_pointer:
                        kind = "field" if child.type == "field_declaration" and owner_name else "variable"
                        if is_function_pointer:
                            kind = f"function_pointer_{kind}"
                        is_static = any(
                            item.type == "storage_class_specifier"
                            and "static" in self._node_text(item)
                            for item in child.children
                        )
                        for name in self._cpp_declaration_names(child):
                            self._append_cpp_symbol(
                                child,
                                result,
                                name=name,
                                kind=("static_field" if kind == "field" and is_static else kind),
                                owner_name=owner_name,
                                visibility=("private" if is_static and not owner_name else current_visibility),
                                is_exported=(
                                    current_visibility == "public"
                                    and not (is_static and not owner_name)
                                ),
                                conds=conds,
                                data_type=self._cpp_declaration_type(child),
                            )
                    continue
                visit(
                    child,
                    conds=conds,
                    else_conds=else_conds,
                    owner_name=owner_name,
                    visibility=current_visibility,
                    namespace_path=namespace_path,
                )

        visit(root, conds=[])

    def _append_cpp_symbol(
        self,
        node: ts.Node,
        result: ParseResult,
        *,
        name: str,
        kind: str,
        owner_name: str | None,
        visibility: str,
        is_exported: bool,
        conds: list[str],
        value: str | None = None,
        data_type: str | None = None,
        references: list[ReferenceInfo] | None = None,
    ) -> None:
        if not name:
            return
        result.symbols.append(SymbolInfo(
            name=name,
            kind=kind,
            line_start=node.start_point[0] + 1,
            line_end=self._line_end(node),
            byte_start=node.start_byte,
            byte_end=node.end_byte,
            visibility=visibility,
            signature=" ".join(self._node_text(node).split()),
            value=value,
            data_type=data_type,
            owner_name=owner_name,
            is_exported=is_exported,
            cfg_conditions=list(conds),
            references=list(references or []),
        ))

    def _cpp_declaration_names(self, node: ts.Node) -> list[str]:
        declarators = list(node.children_by_field_name("declarator"))
        if not declarators:
            declarators = [
                child
                for child in node.children
                if child.type in {
                    "identifier", "field_identifier", "type_identifier",
                    "init_declarator", "pointer_declarator", "reference_declarator",
                    "array_declarator", "structured_binding_declarator",
                }
            ]
        names = [self._cpp_declarator_name(item) for item in declarators]
        return list(dict.fromkeys(name for name in names if name))

    def _cpp_declarator_name(self, node: ts.Node | None) -> str:
        if node is None:
            return ""
        if node.type in {"identifier", "field_identifier", "type_identifier"}:
            return self._node_text(node)
        named = node.child_by_field_name("declarator") or node.child_by_field_name("name")
        if named is not None:
            value = self._cpp_declarator_name(named)
            if value:
                return value
        for child in node.children:
            value = self._cpp_declarator_name(child)
            if value:
                return value
        return ""

    @staticmethod
    def _is_function_pointer_declarator(node: ts.Node) -> bool:
        declarator = node.child_by_field_name("declarator")
        return declarator is not None and declarator.type in {
            "parenthesized_declarator", "pointer_declarator",
        }

    def _cpp_declaration_type(self, node: ts.Node) -> str | None:
        type_node = node.child_by_field_name("type")
        if type_node is not None:
            return self._node_text(type_node) or None
        parts = [
            self._node_text(child)
            for child in node.children
            if child.type in {
                "primitive_type", "type_identifier", "sized_type_specifier",
                "scoped_type_identifier", "qualified_identifier", "template_type",
                "type_qualifier", "auto",
            }
        ]
        return " ".join(part for part in parts if part) or None

    def _cpp_type_name(self, node: ts.Node) -> str:
        name_node = node.child_by_field_name("name")
        if name_node is not None:
            return self._node_text(name_node)
        return next(
            (
                self._node_text(child)
                for child in node.children
                if child.type in {"type_identifier", "qualified_identifier"}
            ),
            "",
        )

    @staticmethod
    def _node_text(node: ts.Node | None) -> str:
        return node.text.decode(errors="replace") if node is not None and node.text else ""

    @staticmethod
    def _line_end(node: ts.Node) -> int:
        return max(
            node.start_point[0] + 1,
            node.end_point[0] + (1 if node.end_point[1] else 0),
        )

    def _walk_node(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        conds: list[str] | None = None,
        else_conds: list[str] | None = None,
    ) -> None:
        """Walk the AST. ``conds`` tracks the #ifdef/#if guard stack so symbols
        inside conditional blocks get annotated with their guard macros."""
        conds = conds or []
        for child in node.children:
            if child.type in ("preproc_ifdef", "preproc_if"):
                guard = self._extract_preproc_cond(child)
                inner_conds = conds + guard
                self._walk_node(
                    child,
                    source,
                    result,
                    inner_conds,
                    self._negated_branch_conditions(conds, guard),
                )
                continue
            if child.type == "ERROR":
                self._walk_node(child, source, result, conds, else_conds)
                continue
            if child.type == "preproc_elif":
                branch_outer = (
                    else_conds if else_conds is not None else conds
                )
                guard = self._extract_preproc_cond(child)
                self._walk_node(
                    child,
                    source,
                    result,
                    branch_outer + guard,
                    self._negated_branch_conditions(branch_outer, guard),
                )
                continue
            if child.type == "preproc_else":
                self._walk_node(
                    child,
                    source,
                    result,
                    else_conds if else_conds is not None else conds,
                )
                continue
            if child.type == "function_definition":
                fn = self._extract_function(child, source)
                if conds:
                    fn.cfg_conditions = list(conds)
                if fn.name:
                    result.functions.append(fn)
            elif child.type == "template_declaration":
                self._handle_template(child, source, result, conds)
            elif child.type == "class_specifier":
                cls = self._extract_class(child, source, result)
                if conds:
                    cls.cfg_conditions = list(conds)
                result.classes.append(cls)
            elif child.type == "struct_specifier":
                cls = self._extract_struct(child, source, result)
                if conds:
                    cls.cfg_conditions = list(conds)
                result.classes.append(cls)
            elif child.type == "enum_specifier":
                cls = self._extract_enum(child, source)
                if conds:
                    cls.cfg_conditions = list(conds)
                result.classes.append(cls)
            elif child.type == "namespace_definition":
                self._handle_namespace(child, source, result, conds)
            elif child.type == "preproc_include":
                imp = self._extract_include(child, source)
                if imp:
                    result.imports.append(imp)
            elif child.type == "declaration":
                self._handle_declaration(child, source, result, conds)
            elif child.type == "linkage_specification":
                # ``extern "C"`` / ``extern "C++"`` linkage. The common
                # multi-line form is pre-masked by
                # ``mask_inactive_preprocessor_code``, but the single
                # declaration form (``extern "C" int f(int);``) and the
                # one-line block form (``extern "C" { int a(void); ... }``)
                # still reach the parser as this node type. Descend into the
                # enclosed declarations so their functions are not silently
                # dropped from the graph.
                for sub in child.children:
                    if sub.type == "declaration_list":
                        self._walk_node(sub, source, result, conds)
                    elif sub.type == "declaration":
                        self._handle_declaration(sub, source, result, conds)
                    elif sub.type == "function_definition":
                        fn = self._extract_function(sub, source)
                        if conds:
                            fn.cfg_conditions = list(conds)
                        if fn.name:
                            result.functions.append(fn)

    @staticmethod
    def _extract_preproc_cond(node: ts.Node) -> list[str]:
        """Extract guard macro names from a #ifdef/#if node."""
        text = node.text.decode(errors="replace") if node.text else ""
        first_line = text.split("\n", 1)[0]
        conds: list[str] = []
        if first_line.startswith("#ifdef"):
            macro = first_line[len("#ifdef"):].strip()
            if macro:
                conds.append(macro)
        elif first_line.startswith("#ifndef"):
            macro = first_line[len("#ifndef"):].strip()
            if macro:
                conds.append("!" + macro)
        elif first_line.startswith(("#if", "#elif")):
            marker = "#elif" if first_line.startswith("#elif") else "#if"
            expression = first_line[len(marker):].strip()
            expression = re.sub(
                r"defined\s*(?:\(\s*(\w+)\s*\)|(\w+))",
                lambda match: match.group(1) or match.group(2),
                expression,
            )
            expression = re.sub(r"\s+", " ", expression).strip()
            if expression not in ("", "0", "1"):
                conds.append(expression)
        return conds

    @staticmethod
    def _negated_branch_conditions(
        outer: list[str], guard: list[str],
    ) -> list[str]:
        """Preserve outer guards and describe the current ``#else`` branch."""
        if not guard:
            return list(outer)
        if len(guard) == 1:
            condition = guard[0]
            if re.fullmatch(r"!\w+", condition):
                negated = condition[1:]
            elif re.fullmatch(r"\w+", condition):
                negated = f"!{condition}"
            else:
                negated = f"!({condition})"
        else:
            negated = "!(" + " && ".join(guard) + ")"
        return [*outer, negated]

    def _handle_template(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        conds: list[str] | None = None,
    ) -> None:
        conds = conds or []
        for child in node.children:
            if child.type == "function_definition":
                fn = self._extract_function(child, source)
                fn.kind = "function_template"
                fn.line_start = node.start_point[0] + 1
                fn.byte_start = node.start_byte
                if conds:
                    fn.cfg_conditions = list(conds)
                if fn.name:
                    result.functions.append(fn)
            elif child.type == "class_specifier":
                cls = self._extract_class(child, source, result)
                cls.kind = "class_template"
                cls.line_start = node.start_point[0] + 1
                cls.byte_start = node.start_byte
                if conds:
                    cls.cfg_conditions = list(conds)
                result.classes.append(cls)
            elif child.type == "declaration":
                functions_before = len(result.functions)
                self._handle_declaration(child, source, result, conds)
                for function in result.functions[functions_before:]:
                    function.kind = "function_template"
                    function.line_start = node.start_point[0] + 1
                    function.byte_start = node.start_byte

    def _handle_declaration(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        conds: list[str] | None = None,
    ) -> None:
        conds = conds or []
        for child in node.children:
            if child.type == "function_declarator":
                name, params = self._extract_declarator(child, source)
                if name:
                    return_type = self._get_decl_return_type(node)
                    signature = self._build_signature(name, params, return_type)
                    visibility = detect_visibility(name)
                    fn = FunctionInfo(
                        name=name,
                        signature=signature,
                        line_start=node.start_point[0] + 1,
                        line_end=node.end_point[0] + 1,
                        visibility=visibility,
                        params=params,
                        return_type=return_type,
                        is_definition=False,
                        byte_start=node.start_byte,
                        byte_end=node.end_byte,
                    )
                    if conds:
                        fn.cfg_conditions = list(conds)
                    result.functions.append(fn)

    def _get_decl_return_type(self, node: ts.Node) -> str | None:
        for child in node.children:
            if child.type in (
                "primitive_type",
                "type_identifier",
                "sized_type_specifier",
                "struct_specifier",
                "enum_specifier",
                "auto",
            ):
                return child.text.decode(errors="replace") if child.text else None
        return None

    def _handle_namespace(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        conds: list[str] | None = None,
    ) -> None:
        for child in node.children:
            if child.type == "declaration_list":
                self._walk_node(child, source, result, conds)

    def _extract_function(
        self, node: ts.Node, source: bytes
    ) -> FunctionInfo:
        name = ""
        params: list[dict] = []
        return_type: str | None = None
        is_static = False
        return_indirection = ""

        declarator = node.child_by_field_name("declarator")
        function_declarator = (
            self._find_function_declarator(declarator)
            if declarator is not None
            else None
        )
        if function_declarator is not None:
            name, params = self._extract_declarator(
                function_declarator, source,
            )
            return_indirection = self._return_indirection_before(
                declarator, function_declarator,
            )

        for child in node.children:
            if child.type == "storage_class_specifier":
                text = child.text.decode(errors="replace") if child.text else ""
                if "static" in text:
                    is_static = True
            elif child.type in (
                "primitive_type",
                "type_identifier",
                "sized_type_specifier",
                "struct_specifier",
                "enum_specifier",
                "auto",
                "scoped_type_identifier",
            ):
                return_type = child.text.decode(errors="replace") if child.text else None

        if not return_type:
            for child in node.children:
                if child.type not in (
                    "function_declarator",
                    "compound_statement",
                    "storage_class_specifier",
                    "type_qualifier",
                    "noexcept",
                ):
                    txt = child.text.decode(errors="replace") if child.text else ""
                    if txt and txt not in ("static", "inline", "extern", "virtual", "explicit"):
                        return_type = txt
                        break

        if return_indirection:
            return_type = (
                f"{return_type} {return_indirection}"
                if return_type
                else return_indirection
            )

        visibility = detect_visibility(name)
        if is_static:
            visibility = "private"

        is_test = name.startswith("test_") or name.endswith("_test")
        calls = self._extract_calls(node)
        references = self._extract_reference_facts(node)
        type_bindings = self._extract_type_bindings(node, params=params)
        signature = self._build_signature(name, params, return_type)

        return FunctionInfo(
            name=name,
            signature=signature,
            line_start=node.start_point[0] + 1,
            line_end=node.end_point[0] + 1,
            visibility=visibility,
            is_static=is_static,
            is_test=is_test,
            params=params,
            return_type=return_type,
            calls=calls,
            is_exported=not is_static,
            byte_start=node.start_byte,
            byte_end=node.end_byte,
            references=references,
            type_bindings=type_bindings,
        )

    def _extract_declarator(
        self, node: ts.Node, source: bytes
    ) -> tuple[str, list[dict]]:
        name = ""
        params: list[dict] = []
        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "field_identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "qualified_identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "destructor_name":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "parenthesized_declarator":
                for sub in child.children:
                    if sub.type in ("pointer_declarator", "reference_declarator"):
                        inner = self._find_function_declarator(sub)
                        if inner:
                            n, p = self._extract_declarator(inner, source)
                            if n:
                                name = n
                            params = p
                    elif sub.type == "function_declarator":
                        n, p = self._extract_declarator(sub, source)
                        if n:
                            name = n
                        params = p
            elif child.type in ("pointer_declarator", "reference_declarator"):
                inner = self._find_function_declarator(child)
                if inner:
                    n, p = self._extract_declarator(inner, source)
                    if n:
                        name = n
                    params = p
            elif child.type == "parameter_list":
                params = self._extract_params(child, source)
        return name, params

    def _find_function_declarator(self, node: ts.Node) -> ts.Node | None:
        if node.type == "function_declarator":
            return node
        for child in node.children:
            if child.type == "function_declarator":
                return child
            result = self._find_function_declarator(child)
            if result:
                return result
        return None

    def _return_indirection_before(
        self,
        node: ts.Node,
        target: ts.Node,
    ) -> str:
        """Return pointer/reference markers wrapping a function declarator."""
        if node == target:
            return ""
        for child in node.children:
            if self._contains_node(child, target):
                marker = ""
                if node.type == "pointer_declarator":
                    marker = "*"
                elif node.type == "reference_declarator":
                    marker = next(
                        (
                            child.type
                            for child in node.children
                            if child.type in {"&", "&&"}
                        ),
                        "&",
                    )
                return marker + self._return_indirection_before(child, target)
        return ""

    def _contains_node(self, node: ts.Node, target: ts.Node) -> bool:
        if node == target:
            return True
        return any(self._contains_node(child, target) for child in node.children)

    def _extract_params(
        self, node: ts.Node, source: bytes
    ) -> list[dict]:
        params: list[dict] = []
        for child in node.children:
            if child.type == "parameter_declaration":
                info = self._extract_param(child, source)
                if info:
                    params.append(info)
            elif child.type == "variadic_parameter":
                params.append({"name": "...", "type": None})
            elif child.type == "optional_parameter_declaration":
                info = self._extract_param(child, source)
                if info:
                    params.append(info)
        return params

    def _extract_param(
        self, node: ts.Node, source: bytes
    ) -> dict | None:
        name = None
        type_ann = None
        type_parts: list[str] = []

        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "primitive_type":
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type == "type_identifier":
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type == "sized_type_specifier":
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type == "type_qualifier":
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type == "scoped_type_identifier":
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type in {
                "struct_specifier", "class_specifier", "union_specifier",
                "enum_specifier", "template_type",
            }:
                type_parts.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type in ("pointer_declarator", "reference_declarator"):
                for sub in child.children:
                    if sub.type == "identifier":
                        name = sub.text.decode(errors="replace") if sub.text else ""
                if type_parts:
                    decl_text = child.text.decode(errors="replace") if child.text else ""
                    type_ann = " ".join(type_parts) + " " + decl_text
            elif child.type == "array_declarator":
                for sub in child.children:
                    if sub.type in ("identifier", "field_identifier"):
                        name = sub.text.decode(errors="replace") if sub.text else ""
            elif child.type == "function_declarator":
                for sub in child.children:
                    if sub.type == "identifier":
                        name = sub.text.decode(errors="replace") if sub.text else ""
            elif child.type == "false" or child.type == "true":
                pass
            elif child.type == "number_literal":
                pass
            elif child.type == "string_literal":
                pass

        if type_ann is None and type_parts:
            type_ann = " ".join(type_parts)

        if name:
            return {"name": name, "type": type_ann}
        elif type_parts:
            return {"name": "", "type": " ".join(type_parts)}
        return None

    def _extract_class(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
    ) -> ClassInfo:
        name = ""
        bases: list[str] = []

        for child in node.children:
            if child.type == "type_identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "base_class_clause":
                for base in child.children:
                    if base.type in {
                        "type_identifier",
                        "qualified_identifier",
                        "scoped_type_identifier",
                        "template_type",
                    } and base.text:
                        bases.append(base.text.decode(errors="replace"))

        cls = ClassInfo(
            name=name,
            line_start=node.start_point[0] + 1,
            line_end=node.end_point[0] + 1,
            kind="class",
            visibility=detect_visibility(name),
            bases=bases,
            byte_start=node.start_byte,
            byte_end=node.end_byte,
        )

        current_visibility = "private"
        for child in node.children:
            if child.type == "field_declaration_list":
                self._walk_class_body(child, source, result, cls, current_visibility)

        return cls

    def _walk_class_body(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        cls: ClassInfo,
        current_visibility: str,
    ) -> None:
        vis = current_visibility
        for child in node.children:
            if child.type == "access_specifier":
                vis = child.text.decode(errors="replace") if child.text else "private"
            elif child.type == "field_declaration":
                method = self._extract_method_from_field(child, source, cls.name, vis)
                if method:
                    method.type_bindings.append(TypeBindingInfo(
                        name="this",
                        type_name=cls.name,
                        source="receiver",
                        line=child.start_point[0] + 1,
                        byte_start=child.start_byte,
                        byte_end=child.end_byte,
                    ))
                    cls.methods.append(method)
                    result.functions.append(method)
            elif child.type == "function_definition":
                fn = self._extract_function(child, source)
                fn.class_name = cls.name
                fn.visibility = vis
                fn.type_bindings.append(TypeBindingInfo(
                    name="this",
                    type_name=cls.name,
                    source="receiver",
                    line=child.start_point[0] + 1,
                    byte_start=child.start_byte,
                    byte_end=child.end_byte,
                ))
                if fn.name:
                    cls.methods.append(fn)
                    result.functions.append(fn)

    def _extract_method_from_field(
        self,
        node: ts.Node,
        source: bytes,
        class_name: str,
        visibility: str,
    ) -> FunctionInfo | None:
        name = ""
        params: list[dict] = []
        return_type: str | None = None

        for child in node.children:
            if child.type == "function_declarator":
                name, params = self._extract_declarator(child, source)
            elif child.type in (
                "primitive_type",
                "type_identifier",
                "sized_type_specifier",
                "auto",
                "scoped_type_identifier",
            ):
                return_type = child.text.decode(errors="replace") if child.text else None

        if not name:
            return None

        signature = self._build_signature(name, params, return_type)

        return FunctionInfo(
            name=name,
            signature=signature,
            line_start=node.start_point[0] + 1,
            line_end=node.end_point[0] + 1,
            visibility=visibility,
            params=params,
            return_type=return_type,
            class_name=class_name,
            is_definition=False,
            byte_start=node.start_byte,
            byte_end=node.end_byte,
        )

    def _extract_struct(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
    ) -> ClassInfo:
        name = ""
        for child in node.children:
            if child.type == "type_identifier":
                name = child.text.decode(errors="replace") if child.text else ""
                break

        cls = ClassInfo(
            name=name,
            line_start=node.start_point[0] + 1,
            line_end=node.end_point[0] + 1,
            kind="struct",
            visibility=detect_visibility(name),
            byte_start=node.start_byte,
            byte_end=node.end_byte,
        )

        current_visibility = "public"
        for child in node.children:
            if child.type == "field_declaration_list":
                self._walk_class_body(child, source, result, cls, current_visibility)

        return cls

    def _extract_enum(self, node: ts.Node, source: bytes) -> ClassInfo:
        name = ""
        for child in node.children:
            if child.type == "type_identifier":
                name = child.text.decode(errors="replace") if child.text else ""
                break

        return ClassInfo(
            name=name,
            line_start=node.start_point[0] + 1,
            line_end=node.end_point[0] + 1,
            kind="enum",
            visibility=detect_visibility(name),
            byte_start=node.start_byte,
            byte_end=node.end_byte,
        )

    def _extract_include(
        self, node: ts.Node, source: bytes
    ) -> ImportInfo | None:
        for child in node.children:
            if child.type == "system_lib_string":
                module = child.text.decode(errors="replace") if child.text else ""
                module = module.strip("<>")
                return ImportInfo(
                    module=module,
                    symbols=[],
                    line=node.start_point[0] + 1,
                )
            elif child.type == "string_literal":
                module = child.text.decode(errors="replace") if child.text else ""
                module = module.strip('"')
                return ImportInfo(
                    module=module,
                    symbols=[],
                    line=node.start_point[0] + 1,
                )
        return None

    def _extract_reference_facts(self, root: ts.Node) -> list[ReferenceInfo]:
        facts: list[ReferenceInfo] = []

        def receiver_node(node: ts.Node) -> ts.Node | None:
            return (
                node.child_by_field_name("argument")
                or node.child_by_field_name("object")
                or node.child_by_field_name("value")
            )

        def append(
            kind: str,
            node: ts.Node,
            name: str,
            receiver: str | None = None,
            arguments: list[str] | None = None,
        ) -> None:
            if name:
                facts.append(ReferenceInfo(
                    kind=kind,
                    name=name,
                    receiver=receiver,
                    qualified_name=(f"{receiver}.{name}" if receiver else name),
                    line_start=node.start_point[0] + 1,
                    line_end=self._line_end(node),
                    byte_start=node.start_byte,
                    byte_end=node.end_byte,
                    arguments=list(arguments or []),
                ))

        def call_arguments(node: ts.Node) -> list[str]:
            arguments = node.child_by_field_name("arguments")
            if arguments is None:
                return []
            return [
                self._node_text(child)
                if child.type in {
                    "identifier", "qualified_identifier", "field_identifier",
                }
                or (
                    child.type == "unary_expression"
                    and self._node_text(child).lstrip().startswith("&")
                )
                else ""
                for child in arguments.named_children
            ]

        def call_parts(node: ts.Node | None) -> tuple[str, str | None]:
            if node is None:
                return "", None
            if node.type in {"identifier", "field_identifier", "operator_name"}:
                return self._node_text(node), None
            if node.type == "field_expression":
                return (
                    self._node_text(node.child_by_field_name("field")),
                    self._node_text(receiver_node(node)) or None,
                )
            if node.type == "qualified_identifier":
                name_node = node.child_by_field_name("name")
                name = self._node_text(name_node) or self._node_text(node).rsplit("::", 1)[-1]
                text = self._node_text(node)
                return name, text.rsplit("::", 1)[0] if "::" in text else None
            if node.type == "template_function":
                name_node = node.child_by_field_name("name")
                if name_node is None:
                    name_node = next(
                        (
                            child for child in node.named_children
                            if child.type in {
                                "identifier", "field_identifier",
                                "qualified_identifier",
                            }
                        ),
                        None,
                    )
                return call_parts(name_node)
            return "", None

        def visit(node: ts.Node, *, is_root: bool = False) -> None:
            if not is_root and node.type in {"function_definition", "lambda_expression"}:
                return
            if node.type == "call_expression":
                function = node.child_by_field_name("function")
                name, receiver = call_parts(function)
                append(
                    "template_call"
                    if function is not None and function.type == "template_function"
                    else "call",
                    node,
                    name,
                    receiver,
                    call_arguments(node),
                )
                for child in node.children:
                    if child != function:
                        visit(child)
                return
            if node.type == "assignment_expression":
                left = node.child_by_field_name("left")
                if left is not None and left.type == "field_expression":
                    append(
                        "write",
                        left,
                        self._node_text(left.child_by_field_name("field")),
                        self._node_text(receiver_node(left)) or None,
                    )
                for child in node.children:
                    if child != left:
                        visit(child)
                return
            if node.type == "field_expression":
                append(
                    "read",
                    node,
                    self._node_text(node.child_by_field_name("field")),
                    self._node_text(receiver_node(node)) or None,
                )
                return
            for child in node.children:
                visit(child)

        visit(root, is_root=True)
        return facts

    def _extract_type_bindings(
        self,
        root: ts.Node,
        *,
        params: list[dict],
    ) -> list[TypeBindingInfo]:
        bindings: list[TypeBindingInfo] = []
        seen: set[tuple[str, str]] = set()

        def append(name: str, type_name: str | None, source_kind: str, node: ts.Node) -> None:
            if not name or not type_name:
                return
            key = (name, type_name)
            if key in seen:
                return
            seen.add(key)
            bindings.append(TypeBindingInfo(
                name=name,
                type_name=type_name,
                source=source_kind,
                line=node.start_point[0] + 1,
                byte_start=node.start_byte,
                byte_end=node.end_byte,
            ))

        for param in params:
            append(str(param.get("name") or ""), param.get("type"), "parameter", root)

        def visit(node: ts.Node, *, is_root: bool = False) -> None:
            if not is_root and node.type in {"function_definition", "lambda_expression"}:
                return
            if node.type == "declaration" and self._find_function_declarator(node) is None:
                data_type = self._cpp_declaration_type(node)
                for name in self._cpp_declaration_names(node):
                    append(name, data_type, "declaration", node)
            for child in node.children:
                visit(child)

        visit(root, is_root=True)
        return bindings

    def _extract_calls(self, node: ts.Node) -> list[str]:
        calls: list[str] = []
        self._find_calls_recursive(node, calls)
        return list(set(calls))

    def _find_calls_recursive(
        self, node: ts.Node, calls: list[str]
    ) -> None:
        if node.type == "call_expression":
            fn_node = node.child_by_field_name("function")
            if fn_node:
                call_name = self._get_call_name(fn_node)
                if call_name:
                    calls.append(call_name)
        for child in node.children:
            self._find_calls_recursive(child, calls)

    def _get_call_name(self, node: ts.Node) -> str | None:
        if node.type == "identifier":
            return node.text.decode(errors="replace") if node.text else None
        elif node.type == "qualified_identifier":
            return node.text.decode(errors="replace") if node.text else None
        elif node.type == "field_expression":
            field = node.child_by_field_name("field")
            if field and field.text:
                return field.text.decode(errors="replace")
        elif node.type == "template_function":
            name = node.child_by_field_name("name")
            if name is None:
                name = next(
                    (
                        child for child in node.named_children
                        if child.type in {"identifier", "qualified_identifier"}
                    ),
                    None,
                )
            return self._get_call_name(name) if name is not None else None
        return None

    def _build_signature(
        self,
        name: str,
        params: list[dict],
        return_type: str | None,
    ) -> str:
        param_strs = []
        for p in params:
            if p.get("type"):
                param_strs.append(f"{p['type']} {p['name']}".strip())
            else:
                param_strs.append(p["name"])
        params_str = ", ".join(param_strs)
        ret = f"{return_type} " if return_type else ""
        return f"{ret}{name}({params_str})"