from __future__ import annotations

import fnmatch

import tree_sitter as ts
import tree_sitter_python as tspython

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


class PythonRule:
    @property
    def language_name(self) -> str:
        return "python"

    @property
    def file_extensions(self) -> list[str]:
        return [".py"]

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

    def is_test_file(self, file_path: str) -> bool:
        parts = file_path.replace("\\", "/").split("/")
        # Files inside a tests/ or test/ directory are test context, not public
        # API.  This lets the mini profile exclude their helper symbols even
        # when the file name does not match a test_* pattern.
        if any(p in ("tests", "test") for p in parts[:-1]):
            return True
        name = parts[-1] if parts 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(tspython.language())
        parser = ts.Parser(lang)
        tree = parser.parse(source)
        root = tree.root_node
        require_valid_tree(root, file_path, allow_recovery=True)

        result = ParseResult()
        self._walk_node(root, source, result, class_name=None)
        self._collect_symbols(root, result)
        # Explicit module-level ctypes/cffi handles are visible inside every
        # function unless shadowed. Propagate only FFI loader bindings; generic
        # constructor bindings remain local to avoid broad type assumptions.
        module_ffi_bindings = [
            binding
            for binding in self._extract_type_bindings(
                root, class_name=None, params=[],
            )
            if binding.source == "ffi_library"
        ]
        for function in result.functions:
            local_names = {binding.name for binding in function.type_bindings}
            function.type_bindings.extend(
                binding for binding in module_ffi_bindings
                if binding.name not in local_names
            )
        populate_tree_sitter_metadata(
            result,
            root,
            source_bytes=len(source),
            parser_name="tree-sitter-python",
            parser_version=installed_parser_version("tree-sitter-python"),
        )
        return result

    def _walk_node(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        class_name: str | None,
    ) -> None:
        for child in node.children:
            if child.type == "function_definition":
                fn = self._extract_function(child, source, class_name)
                result.functions.append(fn)
            elif child.type == "class_definition":
                cls = self._extract_class(child, source, result)
                result.classes.append(cls)
            elif child.type in (
                "import_statement",
                "import_from_statement",
            ):
                imp = self._extract_import(child, source)
                if imp:
                    result.imports.append(imp)
            elif child.type == "decorated_definition":
                self._handle_decorated(child, source, result, class_name)
            elif child.type == "block":
                self._walk_node(child, source, result, class_name)

    def _handle_decorated(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        class_name: str | None,
    ) -> None:
        for child in node.children:
            if child.type == "function_definition":
                fn = self._extract_function(child, source, class_name)
                for dec in node.children:
                    if dec.type == "decorator":
                        dec_name = dec.text.decode(errors="replace") if dec.text else ""
                        if "staticmethod" in dec_name:
                            fn.is_static = True
                        call_name = self._decorator_call_name(dec)
                        if call_name:
                            fn.calls.append(call_name)
                fn.calls = list(dict.fromkeys(fn.calls))
                result.functions.append(fn)
            elif child.type == "class_definition":
                cls = self._extract_class(child, source, result)
                result.classes.append(cls)

    def _extract_function(
        self, node: ts.Node, source: bytes, class_name: str | None
    ) -> FunctionInfo:
        name = ""
        params: list[dict] = []
        return_type: str | None = None
        is_async = any(
            c.type == "async" for c in node.children
        )

        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "parameters":
                params = self._extract_params(child, source)

        type_child = node.child_by_field_name("return_type")
        if type_child:
            return_type = (
                type_child.text.decode(errors="replace") if type_child.text else None
            )

        signature = self._build_signature(name, params, return_type, is_async)
        docstring = self._extract_docstring(node, source)

        is_test = name.startswith("test_") or name.startswith("_test_")
        visibility = detect_visibility(name)
        calls = self._extract_calls(node)
        references = self._extract_reference_facts(node)
        type_bindings = self._extract_type_bindings(
            node, class_name=class_name, params=params,
        )

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

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

        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "argument_list":
                bases = self._extract_bases(child, source)

        docstring = self._extract_docstring(node, source)

        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,
            docstring=docstring,
            is_exported=not name.startswith("_"),
            byte_start=node.start_byte,
            byte_end=node.end_byte,
        )

        for child in node.children:
            if child.type == "block":
                for sub in child.children:
                    if sub.type == "function_definition":
                        method = self._extract_function(
                            sub, source, class_name=name
                        )
                        cls.methods.append(method)
                        result.functions.append(method)
                    elif sub.type == "decorated_definition":
                        self._handle_decorated_in_class(
                            sub, source, result, cls
                        )

        return cls

    def _handle_decorated_in_class(
        self,
        node: ts.Node,
        source: bytes,
        result: ParseResult,
        cls: ClassInfo,
    ) -> None:
        for child in node.children:
            if child.type == "function_definition":
                method = self._extract_function(
                    child, source, class_name=cls.name
                )
                for dec in node.children:
                    if dec.type == "decorator":
                        dec_name = dec.text.decode(errors="replace") if dec.text else ""
                        if "staticmethod" in dec_name:
                            method.is_static = True
                        call_name = self._decorator_call_name(dec)
                        if call_name:
                            method.calls.append(call_name)
                method.calls = list(dict.fromkeys(method.calls))
                cls.methods.append(method)
                result.functions.append(method)

    @staticmethod
    def _decorator_call_name(node: ts.Node) -> str | None:
        """Return the callable tail of ``@decorator`` / ``@pkg.decorator(...)``."""
        text = node.text.decode(errors="replace") if node.text else ""
        text = text.lstrip("@").strip().split("(", 1)[0].strip()
        return text.rsplit(".", 1)[-1] if text else None

    def _collect_symbols(self, root: ts.Node, result: ParseResult) -> None:
        """Collect named Python values without turning every local into graph noise.

        Module assignments, class attributes and ``self``/``cls`` attributes are
        durable program symbols.  Ordinary function locals remain resolution
        facts for a later scope-IR phase and are deliberately not materialized
        as global graph symbols here.
        """

        def visit(
            node: ts.Node,
            *,
            scope: str,
            class_name: str | None,
        ) -> None:
            for child in node.children:
                if child.type == "ERROR":
                    visit(child, scope=scope, class_name=class_name)
                    continue
                if child.type == "decorated_definition":
                    # The contained definition owns its body; decorators are
                    # recorded as calls by _handle_decorated.
                    visit(child, scope=scope, class_name=class_name)
                    continue
                if child.type == "class_definition":
                    name_node = child.child_by_field_name("name")
                    nested_name = self._node_text(name_node)
                    body = child.child_by_field_name("body")
                    if body is not None:
                        visit(body, scope="class", class_name=nested_name)
                    continue
                if child.type == "function_definition":
                    body = child.child_by_field_name("body")
                    if body is not None:
                        visit(body, scope="function", class_name=class_name)
                    continue
                if child.type == "assignment":
                    self._append_assignment_symbols(
                        child,
                        result,
                        scope=scope,
                        class_name=class_name,
                    )
                    # Chained assignments nest another assignment on the RHS.
                    right = child.child_by_field_name("right")
                    if right is not None and right.type == "assignment":
                        self._append_assignment_symbols(
                            right,
                            result,
                            scope=scope,
                            class_name=class_name,
                        )
                        visit(right, scope=scope, class_name=class_name)
                    continue
                visit(child, scope=scope, class_name=class_name)

        visit(root, scope="module", class_name=None)

    def _append_assignment_symbols(
        self,
        node: ts.Node,
        result: ParseResult,
        *,
        scope: str,
        class_name: str | None,
    ) -> None:
        left = node.child_by_field_name("left")
        right = node.child_by_field_name("right")
        type_node = node.child_by_field_name("type")
        if left is None:
            return

        targets: list[tuple[str, str | None]] = []
        if left.type == "identifier":
            targets.append((self._node_text(left), None))
        elif left.type == "attribute":
            obj = left.child_by_field_name("object")
            attr = left.child_by_field_name("attribute")
            targets.append((self._node_text(attr), self._node_text(obj)))
        elif scope in {"module", "class"}:
            targets.extend(
                (self._node_text(item), None)
                for item in self._descendants_of_type(left, "identifier")
            )

        for name, receiver in targets:
            if not name:
                continue
            if scope == "function":
                if not class_name or receiver not in {"self", "cls"}:
                    continue
                kind = "class_attribute" if receiver == "cls" else "instance_attribute"
                owner_name = class_name
            elif scope == "class":
                kind = "class_attribute"
                owner_name = class_name
            else:
                kind = "module_variable"
                owner_name = None
            if right is not None and right.type == "lambda":
                kind = "lambda_binding"
            value = self._node_text(right) or None
            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=detect_visibility(name),
                signature=" ".join(self._node_text(node).split()),
                value=value,
                data_type=self._node_text(type_node) or None,
                owner_name=owner_name,
                is_exported=not name.startswith("_"),
            ))

    @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 _descendants_of_type(self, node: ts.Node, node_type: str) -> list[ts.Node]:
        found: list[ts.Node] = []
        for child in node.children:
            if child.type == node_type:
                found.append(child)
            else:
                found.extend(self._descendants_of_type(child, node_type))
        return found

    def _extract_bases(self, node: ts.Node, source: bytes) -> list[str]:
        bases = []
        for child in node.children:
            if child.type in ("identifier", "attribute"):
                bases.append(child.text.decode(errors="replace") if child.text else "")
        return bases

    def _extract_params(self, node: ts.Node, source: bytes) -> list[dict]:
        params: list[dict] = []
        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
                if name not in ("self", "cls"):
                    params.append({"name": name, "type": None})
            elif child.type == "typed_parameter":
                info = self._extract_typed_param(child, source)
                if info:
                    params.append(info)
            elif child.type == "default_parameter":
                info = self._extract_default_param(child, source)
                if info:
                    params.append(info)
            elif child.type == "typed_default_parameter":
                info = self._extract_typed_default_param(child, source)
                if info:
                    params.append(info)
            elif child.type == "list_splat_pattern":
                name = (
                    child.children[0].text.decode(errors="replace")
                    if child.children and child.children[0].text
                    else ""
                )
                params.append({"name": f"*{name}", "type": None})
            elif child.type == "dictionary_splat_pattern":
                name = (
                    child.children[0].text.decode(errors="replace")
                    if child.children and child.children[0].text
                    else ""
                )
                params.append({"name": f"**{name}", "type": None})
        return params

    def _extract_typed_param(
        self, node: ts.Node, source: bytes
    ) -> dict | None:
        name = None
        type_ann = None
        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "type":
                type_ann = child.text.decode(errors="replace") if child.text else None
        if name and name not in ("self", "cls"):
            return {"name": name, "type": type_ann}
        return None

    def _extract_default_param(
        self, node: ts.Node, source: bytes
    ) -> dict | None:
        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
                if name not in ("self", "cls"):
                    return {"name": name, "type": None}
        return None

    def _extract_typed_default_param(
        self, node: ts.Node, source: bytes
    ) -> dict | None:
        name = None
        type_ann = None
        for child in node.children:
            if child.type == "identifier":
                name = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "type":
                type_ann = child.text.decode(errors="replace") if child.text else None
        if name and name not in ("self", "cls"):
            return {"name": name, "type": type_ann}
        return None

    def _extract_docstring(self, node: ts.Node, source: bytes) -> str | None:
        body = node.child_by_field_name("body")
        if body and body.children:
            first = body.children[0]
            if first.type == "expression_statement" and first.children:
                expr = first.children[0]
                if expr.type == "string":
                    text = expr.text.decode(errors="replace") if expr.text else ""
                    if text.startswith('"""') or text.startswith("'''"):
                        return text[3:-3].strip()
                    elif text.startswith('"') or text.startswith("'"):
                        return text[1:-1].strip()
        return None

    def _extract_import(self, node: ts.Node, source: bytes) -> ImportInfo | None:
        if node.type == "import_statement":
            return self._extract_import_statement(node, source)
        elif node.type == "import_from_statement":
            return self._extract_import_from_statement(node, source)
        return None

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

    def _extract_import_from_statement(
        self, node: ts.Node, source: bytes
    ) -> ImportInfo | None:
        module = ""
        symbols: list[str] = []
        for child in node.children:
            if child.type == "relative_import":
                # 处理相对导入,如 from ..config import Config
                module = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "dotted_name" and not module:
                module = child.text.decode(errors="replace") if child.text else ""
            elif child.type == "dotted_name" and module:
                symbols.append(child.text.decode(errors="replace") if child.text else "")
            elif child.type == "aliased_import":
                for sub in child.children:
                    if sub.type == "dotted_name":
                        symbols.append(
                            sub.text.decode(errors="replace") if sub.text else ""
                        )
                        break
        if module:
            return ImportInfo(
                module=module,
                symbols=symbols,
                line=node.start_point[0] + 1,
            )
        return None

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

        def append(kind: str, node: ts.Node, name: str, receiver: str | None = None) -> None:
            if not name:
                return
            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,
            ))

        def visit(node: ts.Node, *, is_root: bool = False) -> None:
            if not is_root and node.type in {"function_definition", "class_definition"}:
                return
            if node.type == "call":
                function = node.child_by_field_name("function")
                if function is not None and function.type == "identifier":
                    append("call", node, self._node_text(function))
                elif function is not None and function.type == "attribute":
                    append(
                        "call",
                        node,
                        self._node_text(function.child_by_field_name("attribute")),
                        self._node_text(function.child_by_field_name("object")) or None,
                    )
                for child in node.children:
                    if child != function:
                        visit(child)
                return
            if node.type in {"assignment", "augmented_assignment"}:
                left = node.child_by_field_name("left")
                if left is not None and left.type == "attribute":
                    append(
                        "write",
                        left,
                        self._node_text(left.child_by_field_name("attribute")),
                        self._node_text(left.child_by_field_name("object")) or None,
                    )
                for child in node.children:
                    if child != left:
                        visit(child)
                return
            if node.type == "attribute":
                append(
                    "read",
                    node,
                    self._node_text(node.child_by_field_name("attribute")),
                    self._node_text(node.child_by_field_name("object")) 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,
        *,
        class_name: str | None,
        params: list[dict],
    ) -> list[TypeBindingInfo]:
        bindings: list[TypeBindingInfo] = []
        seen: set[tuple[str, str, str, str | None]] = set()

        def append(
            name: str,
            type_name: str | None,
            source_kind: str,
            node: ts.Node,
            foreign_library: str | None = None,
        ) -> None:
            if not name or not type_name:
                return
            key = (name, type_name, source_kind, foreign_library)
            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,
                foreign_library=foreign_library,
            ))

        for param in params:
            append(str(param.get("name") or ""), param.get("type"), "parameter", root)
        if class_name:
            parameter_names = {str(param.get("name") or "") for param in params}
            if "self" in parameter_names:
                append("self", class_name, "receiver", root)
            if "cls" in parameter_names:
                append("cls", class_name, "receiver", root)

        def visit(node: ts.Node, *, is_root: bool = False) -> None:
            if not is_root and node.type in {"function_definition", "class_definition"}:
                return
            if node.type == "assignment":
                left = node.child_by_field_name("left")
                right = node.child_by_field_name("right")
                type_node = node.child_by_field_name("type")
                if left is not None and left.type == "identifier":
                    name = self._node_text(left)
                    if type_node is not None:
                        append(name, self._node_text(type_node), "annotation", node)
                    if right is not None and right.type == "call":
                        constructor = right.child_by_field_name("function")
                        constructor_name = self._node_text(constructor)
                        if constructor_name:
                            append(name, constructor_name, "constructor", node)
                        if self._is_ffi_loader(constructor_name):
                            append(
                                name,
                                constructor_name or "ffi_library",
                                "ffi_library",
                                node,
                                foreign_library=self._first_string_literal(right),
                            )
                for child in node.children:
                    visit(child)
                return
            for child in node.children:
                visit(child)

        visit(root, is_root=True)
        return bindings

    @staticmethod
    def _is_ffi_loader(name: str) -> bool:
        normalized = name.replace(" ", "")
        return normalized in {
            "ctypes.CDLL", "ctypes.PyDLL", "ctypes.WinDLL", "ctypes.OleDLL",
            "ctypes.cdll.LoadLibrary", "ctypes.pydll.LoadLibrary",
        } or normalized.endswith(".dlopen")

    def _first_string_literal(self, node: ts.Node) -> str | None:
        stack = list(reversed(node.children))
        while stack:
            current = stack.pop()
            if current.type in {"string", "concatenated_string"}:
                value = self._node_text(current).strip()
                # Keep the library spelling as evidence, without claiming that
                # it maps uniquely to a repository module.
                return value.strip("'\"") or None
            stack.extend(reversed(current.children))
        return None

    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":
            func = node.child_by_field_name("function")
            if func:
                call_name = self._get_call_name(func)
                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 == "attribute":
            attr = node.child_by_field_name("attribute")
            if attr:
                return attr.text.decode(errors="replace") if attr.text else None
        return None

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