from __future__ import annotations

import hashlib
from dataclasses import asdict, dataclass, field, is_dataclass
from pathlib import Path
from typing import Any

from .scanner import FileScanner, decode_file_bytes
from .languages.base import FunctionInfo, LanguageRule
from .symbol_ids import (
    canonical_function_nodes,
    code_symbol_node_id,
    function_identity_key,
)
from .relation_resolver import RelationResolver, refresh_module_metadata
from .languages.python import PythonRule
from .languages.typescript import TypeScriptRule
from .languages.rust import RustRule
from .languages.c import CRule
from .languages.cpp import CppRule
from .languages.go import GoRule
from .languages.java import JavaRule
from ..graph.models import (
    FileNode, ModuleNode, FunctionNode, ClassNode, CodeChunkNode,
    CodeSymbolNode, Edge,
)
from ..query.index import KeywordIndex, SymbolIndex, FileIndex


LANGUAGE_RULES: dict[str, LanguageRule] = {
    "python": PythonRule(),
    "typescript": TypeScriptRule(),
    "rust": RustRule(),
    "c": CRule(),
    "cpp": CppRule(),
    "go": GoRule(),
    "java": JavaRule(),
}


@dataclass
class BuildResult:
    files_parsed: int = 0
    files_failed: int = 0
    functions_found: int = 0
    classes_found: int = 0
    symbols_found: int = 0
    modules_found: int = 0
    edges_created: int = 0
    errors: list[str] = field(default_factory=list)
    # rel_paths of files that failed to parse and got fallback FileNode +
    # CodeChunkNodes.  Used to link them to their parent module after all
    # directory modules have been created.
    fallback_files: list[str] = field(default_factory=list)


def parse_result_metadata(parse_result: Any, source_bytes: int) -> dict[str, Any]:
    """Serialize parser provenance while remaining compatible with old rules."""
    diagnostics = []
    for item in getattr(parse_result, "diagnostics", None) or []:
        if is_dataclass(item):
            diagnostics.append(asdict(item))
        elif isinstance(item, dict):
            diagnostics.append(dict(item))
    status = str(getattr(parse_result, "parse_status", "ok") or "ok")
    parsed_bytes = int(getattr(parse_result, "parsed_bytes", 0) or 0)
    if status == "ok" and not parsed_bytes:
        parsed_bytes = source_bytes
    coverage = float(getattr(parse_result, "parse_coverage", 1.0) or 0.0)
    return {
        "parse_status": status,
        "parse_coverage": max(0.0, min(1.0, coverage)),
        "parser_name": str(getattr(parse_result, "parser_name", "") or ""),
        "parser_version": str(
            getattr(parse_result, "parser_version", "") or ""
        ),
        "source_bytes": source_bytes,
        "parsed_bytes": max(0, min(source_bytes, parsed_bytes)),
        "parse_diagnostics": diagnostics,
        "semantic_backend": str(
            getattr(parse_result, "semantic_backend", "") or ""
        ),
        "semantic_facts": int(
            getattr(parse_result, "semantic_facts", 0) or 0
        ),
    }


def serialize_relation_facts(items: Any) -> list[dict[str, Any]]:
    """Serialize parser relation facts without coupling persistence to a rule."""
    serialized: list[dict[str, Any]] = []
    for item in items or []:
        if is_dataclass(item):
            serialized.append(asdict(item))
        elif isinstance(item, dict):
            serialized.append(dict(item))
    return serialized


class CodeParser:
    def __init__(
        self,
        project_path: Path,
        exclude_patterns: list[str] | None = None,
        languages: list[str] | None = None,
        index_body: bool = False,
        semantic_backend: Any = None,
        include_patterns: list[str] | None = None,
    ):
        self.project_path = Path(project_path)
        self.scanner = FileScanner(
            project_path, exclude_patterns, languages, include_patterns,
        )
        self.rules = LANGUAGE_RULES
        self.index_body = index_body
        self.semantic_backend = semantic_backend

    def parse_all(
        self,
        store: Any,
        keyword_index: KeywordIndex,
        symbol_index: SymbolIndex,
        file_index: FileIndex,
    ) -> BuildResult:
        result = BuildResult()
        modules_seen: dict[str, str] = {}
        
        # 第一遍:解析所有文件并建立模块路径映射。跨文件关系要等全部
        # 节点安装后由 RelationResolver 统一解析。
        module_path_to_id: dict[str, str] = {}
        module_metadata: dict[str, tuple[str, str]] = {}
        # Set of directory module paths that are declared ``pub mod`` in their
        # parent file.  Modules NOT in this set default to is_exported=True for
        # non-Rust languages; for Rust, only pub-mod-declared modules are public.
        pub_mod_dirs: set[str] = set()
        # ALL mod declarations (both pub mod and private mod).  A directory that
        # appears here but NOT in pub_mod_dirs was explicitly declared private.
        all_mod_dirs: set[str] = set()
        # Paths of Rust files that are private mod declarations (``mod foo;``
        # without ``pub``).  Symbols in these files are not public API unless
        # re-exported via ``pub use``.
        private_file_paths: set[str] = set()
        rust_module_dirs: set[str] = set()
        # Directories that contain lib.rs or main.rs — these are Rust crate
        # roots and are always publicly accessible regardless of pub mod.
        rust_crate_root_dirs: set[str] = set()
        file_parse_results: list[tuple[Path, str, str, Any, str, bytes]] = []

        for file_path, language in self.scanner.scan_code_files():
            rule = self.rules.get(language)
            if not rule:
                continue

            # Compute rel_path/crate/source before the parse try-block so the
            # fallback handler can use them when rule.parse() raises.
            # Use os.path.relpath for Windows 8.3 short-path resilience.
            import os as _os
            rel_path = _os.path.relpath(str(file_path), str(self.project_path)).replace("\\", "/")
            crate = self.scanner.detect_crate(file_path)
            try:
                source = file_path.read_bytes()
            except Exception as e:
                result.files_failed += 1
                result.errors.append(f"{file_path}: {e}")
                continue

            try:
                parse_result = rule.parse(source, rel_path)
                if self.semantic_backend is not None and language in {"c", "cpp"}:
                    self.semantic_backend.enrich(file_path, parse_result)

                # 记录模块路径
                dir_path = str(file_path.parent.relative_to(self.project_path)).replace("\\", "/")
                if dir_path == ".":
                    dir_path = ""
                if language == "rust":
                    fname = file_path.name
                    if fname in ("lib.rs", "main.rs") and dir_path:
                        rust_crate_root_dirs.add(dir_path)
                if dir_path:
                    parts = dir_path.split("/")
                    for depth in range(1, len(parts) + 1):
                        module_path = "/".join(parts[:depth])
                        module_path_to_id.setdefault(
                            module_path, f"mod_{self._hash(module_path)}",
                        )
                        module_metadata.setdefault(module_path, (language, crate))
                        if language == "rust":
                            rust_module_dirs.add(module_path)

                # Record pub mod declarations so directory modules can be marked
                # as exported or not.  ``pub mod util;`` in src/lib.rs means the
                # directory module ``src/util`` is publicly accessible.
                pub_mods = getattr(parse_result, "pub_mod_names", None) or []
                all_mods = getattr(parse_result, "all_mod_names", None) or []
                if all_mods or pub_mods:
                    file_dir = dir_path
                    for mod_name in (all_mods or pub_mods):
                        child_mod_path = (
                            f"{file_dir}/{mod_name}" if file_dir else mod_name
                        )
                        all_mod_dirs.add(child_mod_path)
                    for mod_name in (pub_mods or []):
                        child_mod_path = (
                            f"{file_dir}/{mod_name}" if file_dir else mod_name
                        )
                        pub_mod_dirs.add(child_mod_path)

                # Track private file-level mod declarations.  ``mod read_task;``
                # (without pub) means read_task.rs / read_task/mod.rs is a
                # private submodule.  Symbols in that file should not appear in
                # the public API unless explicitly re-exported.
                private_mods_set = set(all_mods or []) - set(pub_mods or [])
                if private_mods_set:
                    file_dir_for_mods = dir_path
                    for mod_name in private_mods_set:
                        # File modules can be foo.rs or foo/mod.rs
                        mod_file = f"{file_dir_for_mods}/{mod_name}.rs" if file_dir_for_mods else f"{mod_name}.rs"
                        private_file_paths.add(mod_file)
                        mod_dir = f"{file_dir_for_mods}/{mod_name}" if file_dir_for_mods else mod_name
                        private_file_paths.add(f"{mod_dir}/mod.rs")

                file_parse_results.append(
                    (file_path, rel_path, language, parse_result, crate, source)
                )
            except Exception as e:
                result.files_failed += 1
                result.errors.append(f"{file_path}: {e}")
                # Fallback: install a minimal FileNode + CodeChunkNodes so the
                # file is still discoverable despite the parse failure.
                # module_id is resolved after directory modules are created
                # (below), so we pass None here and let _link_fallback_modules
                # wire the CONTAIN edge later.
                self._create_fallback_file_nodes(
                    store, file_index, rel_path, language, source,
                    module_id=None, crate=crate,
                    parse_error=str(e),
                )
                result.fallback_files.append(rel_path)

        # Create all directory ancestors before installing files.  This avoids
        # dangling parent references for a file added directly in a deep tree.
        for dir_path in sorted(
            module_path_to_id,
            key=lambda path: (path.count("/"), path),
        ):
            mod_id = module_path_to_id[dir_path]
            parent_dir = dir_path.rsplit("/", 1)[0] if "/" in dir_path else ""
            parent_mod_id = module_path_to_id.get(parent_dir)
            language, crate = module_metadata[dir_path]
            mod_node = ModuleNode(
                id=mod_id,
                name=dir_path.rsplit("/", 1)[-1],
                path=dir_path,
                parent=parent_mod_id,
                line_count=0,
                file_count=0,
                language=language,
                crate=crate,
                is_exported=self._module_is_exported(dir_path, language, pub_mod_dirs, all_mod_dirs, rust_module_dirs, rust_crate_root_dirs),
            )
            store.add_node(mod_node.to_dict())
            modules_seen[dir_path] = mod_id
            result.modules_found += 1
            if parent_mod_id:
                store.add_edge(Edge(
                    id=f"{parent_mod_id}->{mod_id}:CONTAIN",
                    type="CONTAIN",
                    source=parent_mod_id,
                    target=mod_id,
                ))
                result.edges_created += 1

        # Link fallback files (created during Phase 1 parse failures) to their
        # parent directory module now that all module nodes exist.
        for fb_rel_path in result.fallback_files:
            fb_dir = fb_rel_path.rsplit("/", 1)[0] if "/" in fb_rel_path else ""
            fb_module_id = modules_seen.get(fb_dir) if fb_dir else None
            if fb_module_id:
                fb_file_id = f"file_{self._hash(fb_rel_path)}"
                # Avoid duplicate edges if the fallback already added one.
                edge_id = f"{fb_module_id}->{fb_file_id}:CONTAIN"
                if not store.get_edge(edge_id):
                    store.add_edge(Edge(
                        id=edge_id, type="CONTAIN",
                        source=fb_module_id, target=fb_file_id,
                    ))
                    result.edges_created += 1

        # 第二遍:构建图谱
        for (
            file_path, rel_path, language, parse_result, crate, raw,
        ) in file_parse_results:
            try:
                rule = self.rules.get(language)
                if not rule:
                    continue
                file_text = decode_file_bytes(raw)
                md5 = hashlib.md5(raw).hexdigest()
                source_lines = file_text.splitlines() if self.index_body else None

                file_id = f"file_{self._hash(rel_path)}"
                file_node = FileNode(
                    id=file_id,
                    path=rel_path,
                    language=language,
                    line_count=len(file_text.splitlines()),
                    is_test=rule.is_test_file(rel_path),
                    is_generated=False,
                    md5=md5,
                    crate=crate,
                    imports=[
                        {
                            "module": imp.module,
                            "symbols": list(imp.symbols),
                            "line": imp.line,
                            "cfg_conditions": list(imp.cfg_conditions),
                        }
                        for imp in parse_result.imports
                    ],
                    reexports=getattr(parse_result, "reexported_names", None) or [],
                    is_exported=rel_path not in private_file_paths,
                    **parse_result_metadata(parse_result, len(raw)),
                )
                store.add_node(file_node.to_dict())
                
                node_ids: list[str] = []
                
                dir_path = str(file_path.parent.relative_to(self.project_path)).replace("\\", "/")
                if dir_path == ".":
                    dir_path = ""
                module_id = modules_seen.get(dir_path)
                
                # 建立模块到文件的 CONTAIN 边
                if module_id:
                    store.add_edge(Edge(
                        id=f"{module_id}->{file_id}:CONTAIN",
                        type="CONTAIN",
                        source=module_id,
                        target=file_id,
                    ))
                    result.edges_created += 1
                
                parsed_functions = canonical_function_nodes(
                    rel_path, parse_result.functions,
                )
                for fn_info, fn_id in parsed_functions:
                    body = None
                    if self.index_body and source_lines and fn_info.line_end >= fn_info.line_start:
                        body = "\n".join(source_lines[fn_info.line_start - 1 : fn_info.line_end])
                    fn_node = FunctionNode(
                        id=fn_id,
                        name=fn_info.name,
                        signature=fn_info.signature,
                        file_id=file_id,
                        module_id=module_id or "",
                        class_id=self._class_id(rel_path, fn_info.class_name, fn_info.module_path),
                        class_name=fn_info.class_name,
                        line_start=fn_info.line_start,
                        line_end=fn_info.line_end,
                        visibility=fn_info.visibility,
                        is_async=fn_info.is_async,
                        is_static=fn_info.is_static,
                        is_test=fn_info.is_test,
                        params=fn_info.params,
                        return_type=fn_info.return_type,
                        docstring=fn_info.docstring,
                        body=body,
                        is_exported=fn_info.is_exported,
                        cfg_conditions=fn_info.cfg_conditions,
                        calls=list(fn_info.calls),
                        references=serialize_relation_facts(fn_info.references),
                        type_bindings=serialize_relation_facts(fn_info.type_bindings),
                        linkage=fn_info.linkage or ("C" if language == "c" else None),
                        module_path=fn_info.module_path,
                        is_definition=fn_info.is_definition,
                        byte_start=fn_info.byte_start,
                        byte_end=fn_info.byte_end,
                        kind=fn_info.kind,
                    )
                    store.add_node(fn_node.to_dict())
                    node_ids.append(fn_id)
                    
                    symbol_index.add(fn_info.name, fn_id)
                    keyword_index.add(
                        fn_id,
                        f"{fn_info.name} {fn_info.signature} {fn_info.docstring or ''}",
                    )
                    
                    if module_id:
                        store.add_edge(Edge(
                            id=f"{module_id}->{fn_id}:CONTAIN",
                            type="CONTAIN",
                            source=module_id,
                            target=fn_id,
                        ))
                        result.edges_created += 1
                    
                    store.add_edge(Edge(
                        id=f"{file_id}->{fn_id}:CONTAIN",
                        type="CONTAIN",
                        source=file_id,
                        target=fn_id,
                    ))
                    result.edges_created += 1
                    
                    result.functions_found += 1
                
                for cls_info in parse_result.classes:
                    cls_id = self._class_id(rel_path, cls_info.name, cls_info.module_path)
                    # Match methods by class_name.  When both the class and the
                    # method have a module_path, they must match — this prevents
                    # sync_impl::Body from picking up async_impl::Body's methods.
                    # When either has no module_path (e.g. an impl block written
                    # outside the inline module), fall back to class_name only.
                    cls_mod_path = cls_info.module_path
                    method_ids = [
                        fn_id
                        for fn, fn_id in parsed_functions
                        if fn.class_name == cls_info.name
                        and (
                            not cls_mod_path
                            or not fn.module_path
                            or fn.module_path == cls_mod_path
                        )
                    ]
                    cls_node = ClassNode(
                        id=cls_id,
                        name=cls_info.name,
                        kind=cls_info.kind,
                        file_id=file_id,
                        module_id=module_id or "",
                        line_start=cls_info.line_start,
                        line_end=cls_info.line_end,
                        visibility=cls_info.visibility,
                        bases=cls_info.bases,
                        docstring=cls_info.docstring,
                        methods=method_ids,
                        is_exported=cls_info.is_exported,
                        cfg_conditions=cls_info.cfg_conditions,
                        module_path=cls_info.module_path,
                        is_definition=cls_info.is_definition,
                        byte_start=cls_info.byte_start,
                        byte_end=cls_info.byte_end,
                    )
                    store.add_node(cls_node.to_dict())
                    node_ids.append(cls_id)
                    
                    symbol_index.add(cls_info.name, cls_id)
                    keyword_index.add(
                        cls_id, f"{cls_info.name} {cls_info.docstring or ''}"
                    )
                    
                    if module_id:
                        store.add_edge(Edge(
                            id=f"{module_id}->{cls_id}:CONTAIN",
                            type="CONTAIN",
                            source=module_id,
                            target=cls_id,
                        ))
                        result.edges_created += 1
                    
                    store.add_edge(Edge(
                        id=f"{file_id}->{cls_id}:CONTAIN",
                        type="CONTAIN",
                        source=file_id,
                        target=cls_id,
                    ))
                    result.edges_created += 1
                    
                    result.classes_found += 1

                for symbol_info in getattr(parse_result, "symbols", None) or []:
                    symbol_id = code_symbol_node_id(rel_path, symbol_info)
                    owner_id = self._class_id(
                        rel_path, symbol_info.owner_name,
                    )
                    symbol_node = CodeSymbolNode(
                        id=symbol_id,
                        name=symbol_info.name,
                        kind=symbol_info.kind,
                        file_id=file_id,
                        module_id=module_id or "",
                        line_start=symbol_info.line_start,
                        line_end=symbol_info.line_end,
                        byte_start=symbol_info.byte_start,
                        byte_end=symbol_info.byte_end,
                        visibility=symbol_info.visibility,
                        signature=symbol_info.signature,
                        value=symbol_info.value,
                        data_type=symbol_info.data_type,
                        owner_name=symbol_info.owner_name,
                        owner_id=owner_id,
                        is_definition=symbol_info.is_definition,
                        is_exported=symbol_info.is_exported,
                        cfg_conditions=list(symbol_info.cfg_conditions),
                        references=serialize_relation_facts(symbol_info.references),
                    )
                    node_data = symbol_node.to_dict()
                    store.add_node(node_data)
                    node_ids.append(symbol_id)
                    symbol_index.add(symbol_info.name, symbol_id)
                    keyword_index.add(
                        symbol_id,
                        " ".join(part for part in (
                            symbol_info.name,
                            symbol_info.kind,
                            symbol_info.signature or "",
                            symbol_info.value or "",
                            symbol_info.data_type or "",
                            symbol_info.owner_name or "",
                        ) if part),
                    )
                    if module_id:
                        store.add_edge(Edge(
                            id=f"{module_id}->{symbol_id}:CONTAIN",
                            type="CONTAIN",
                            source=module_id,
                            target=symbol_id,
                        ))
                        result.edges_created += 1
                    store.add_edge(Edge(
                        id=f"{file_id}->{symbol_id}:CONTAIN",
                        type="CONTAIN",
                        source=file_id,
                        target=symbol_id,
                    ))
                    result.edges_created += 1
                    if owner_id and store.get_node(owner_id):
                        store.add_edge(Edge(
                            id=f"{owner_id}->{symbol_id}:CONTAIN",
                            type="CONTAIN",
                            source=owner_id,
                            target=symbol_id,
                        ))
                        result.edges_created += 1
                    result.symbols_found += 1
                
                file_index.add(rel_path, {
                    "file_id": file_id,
                    "language": language,
                    "nodes": node_ids,
                })
                
                result.files_parsed += 1

            except Exception as e:
                result.files_failed += 1
                result.errors.append(f"{file_path}: {e}")
                # Fallback: the file parsed but node installation failed
                # mid-way.  Install a minimal FileNode + CodeChunkNodes so the
                # file is still discoverable.
                import logging as _logging
                _logging.getLogger(__name__).debug(
                    "Phase 2 install failed for %s; creating fallback nodes", rel_path,
                    exc_info=True,
                )
                try:
                    fb_dir = (
                        str(file_path.parent.relative_to(self.project_path)).replace("\\", "/")
                        if str(file_path.parent) != str(self.project_path) else ""
                    )
                    self._create_fallback_file_nodes(
                        store, file_index, rel_path, language, raw,
                        module_id=modules_seen.get(fb_dir) if fb_dir else None,
                        crate=crate,
                        parse_error=str(e),
                    )
                except Exception:
                    pass

        # Resolve every derived relation from facts persisted on the completed
        # node set.  Incremental builds use the same resolver after installing
        # their whole debounce batch, so the two paths cannot drift.
        refresh_module_metadata(store)
        relation_edges = RelationResolver(store).replace_all()
        result.edges_created += len(relation_edges)

        return result

    # ---- Fallback for files that fail to tree-sitter parse --------------
    # Instead of dropping a parse-failed file entirely, create a minimal
    # FileNode plus line-windowed CodeChunkNodes so the file is still
    # discoverable (keyword_search / get_content / get_file_symbols).

    def _create_fallback_file_nodes(
        self,
        store: Any,
        file_index: FileIndex,
        rel_path: str,
        language: str,
        source: bytes,
        module_id: str | None,
        crate: str = "",
        parse_error: str | None = None,
    ) -> str | None:
        """Install a minimal FileNode + CodeChunkNodes for a parse-failed file.

        Thin wrapper around the module-level :func:`create_fallback_file_nodes`
        so both the full-build path (CodeParser) and the incremental updater
        can share one implementation.
        """
        return create_fallback_file_nodes(
            store, file_index, rel_path, language, source,
            module_id=module_id, crate=crate, parse_error=parse_error,
        )

    def _hash(self, text: str) -> str:
        return hashlib.md5(text.encode()).hexdigest()[:12]

    def _fn_id(self, rel_path: str, fn_info: FunctionInfo) -> str:
        """Signature-aware ID for callers that resolve one function at a time."""
        return f"fn_{self._hash(function_identity_key(rel_path, fn_info))}"

    @staticmethod
    def _module_is_exported(
        dir_path: str,
        language: str,
        pub_mod_dirs: set[str],
        all_mod_dirs: set[str],
        rust_module_dirs: set[str],
        rust_crate_root_dirs: set[str] | None = None,
    ) -> bool:
        """Determine whether a directory module is publicly accessible.

        For non-Rust languages, directory modules default to exported.  For
        Rust, the logic is:

        * Crate roots (containing ``lib.rs``/``main.rs``) are always accessible.
        * Directories declared ``pub mod foo;`` are exported.
        * Directories declared ``mod foo;`` (private, no ``pub``) are NOT exported.
        * Directories NOT declared via any ``mod`` statement default to True —
          they are just directory structure (e.g. workspace subdirectories) and
          their accessibility is determined by ancestor reachability at query
          time, not by their own is_exported flag.
        """
        if language != "rust":
            return True
        if not dir_path:
            return True
        if rust_crate_root_dirs and dir_path in rust_crate_root_dirs:
            return True
        if dir_path in pub_mod_dirs:
            return True
        # Only mark as private if EXPLICITLY declared as non-pub ``mod foo;``.
        # A directory that no file declared at all is just structural — default
        # to True so workspace directories don't get wrongly hidden.
        if dir_path in all_mod_dirs and dir_path not in pub_mod_dirs:
            return False
        return True

    def _class_id(
        self, rel_path: str, class_name: str | None, module_path: str | None = None
    ) -> str | None:
        """Resolve a struct/trait name to its ClassNode id within the same file.

        *module_path* is the language-specific semantic module path (e.g. a
        Rust inline ``mod sync_impl``).  When present it is folded into the ID
        so two types with the same name in different inline modules produce
        distinct node IDs instead of overwriting each other.
        """
        if not class_name:
            return None
        key = rel_path + ':' + class_name
        if module_path:
            key = f"{rel_path}:{module_path}::{class_name}"
        return f"cls_{self._hash(key)}"


# ---------------------------------------------------------------------------
# Module-level fallback: shared by CodeParser (full build) and
# IncrementalUpdater (watcher).  When tree-sitter cannot parse a code file,
# install a minimal FileNode + line-windowed CodeChunkNodes so the file is
# still discoverable via keyword_search / get_content / get_file_symbols.
# ---------------------------------------------------------------------------

import re as _re

_FALLBACK_CHUNK_LINES = 120
_FALLBACK_CHUNK_OVERLAP = 20
_FALLBACK_MAX_CHUNKS = 4096


def _fallback_hash(text: str) -> str:
    return hashlib.md5(text.encode()).hexdigest()[:12]


def create_fallback_file_nodes(
    store: Any,
    file_index: FileIndex,
    rel_path: str,
    language: str,
    source: bytes,
    module_id: str | None = None,
    crate: str = "",
    parse_error: str | None = None,
) -> str | None:
    """Install a minimal FileNode + CodeChunkNodes for a parse-failed file.

    Returns the file_id (or ``None`` on failure).  The file is split into
    ~120-line chunks with ~20-line overlap, snapped to blank-line boundaries,
    so ``keyword_search`` and ``get_content`` can still surface its code even
    though tree-sitter could not parse it.
    """
    try:
        file_text = decode_file_bytes(source)
    except Exception:
        return None
    source_lines = file_text.splitlines()
    line_count = len(source_lines)
    file_id = f"file_{_fallback_hash(rel_path)}"
    md5 = hashlib.md5(source).hexdigest()

    file_node = FileNode(
        id=file_id,
        path=rel_path,
        language=language,
        line_count=line_count,
        is_test=False,
        is_generated=False,
        md5=md5,
        crate=crate,
        imports=[],
        reexports=[],
        is_exported=True,
        parse_status="fallback",
        parse_coverage=0.0,
        source_bytes=len(source),
        parsed_bytes=0,
        parse_diagnostics=[{
            "kind": "parser_error",
            "message": parse_error or "tree-sitter parse failed",
            "line_start": 1,
            "line_end": max(1, line_count),
            "byte_start": 0,
            "byte_end": len(source),
            "recovered": False,
        }],
    )
    store.add_node(file_node.to_dict())

    if module_id:
        store.add_edge(Edge(
            id=f"{module_id}->{file_id}:CONTAIN",
            type="CONTAIN",
            source=module_id,
            target=file_id,
        ))

    node_ids: list[str] = []
    start = 0  # 0-based line index
    total = line_count
    while start < total and len(node_ids) < _FALLBACK_MAX_CHUNKS:
        ideal_end = start + _FALLBACK_CHUNK_LINES
        if ideal_end >= total:
            end = total
        else:
            # Snap the end forward to the next blank line (up to +20 lines)
            # so chunks don't split a block mid-statement.
            snap_end = ideal_end
            for i in range(ideal_end, min(ideal_end + 20, total)):
                if source_lines[i].strip() == "":
                    snap_end = i
                    break
            end = snap_end
        chunk_lines = source_lines[start:end]
        content = "\n".join(chunk_lines)
        line_start = start + 1  # 1-based
        line_end = end
        chunk_id = f"cchunk_{_fallback_hash(f'{file_id}:{line_start}:{line_end}')}"
        # Extract simple keywords: identifiers 3+ chars, deduped, capped.
        identifiers = _re.findall(r"[A-Za-z_][A-Za-z0-9_]{2,}", content)
        seen: set[str] = set()
        keywords_list: list[str] = []
        for ident in identifiers:
            if ident not in seen:
                seen.add(ident)
                keywords_list.append(ident)
                if len(keywords_list) >= 30:
                    break
        keywords = " ".join(keywords_list)
        chunk = CodeChunkNode(
            id=chunk_id,
            content=content,
            kind="fallback",
            source_id=file_id,
            line_start=line_start,
            line_end=line_end,
            token_count=len(chunk_lines) * 4,
            keywords=keywords,
        )
        store.add_node(chunk.to_dict())
        store.add_edge(Edge(
            id=f"{file_id}->{chunk_id}:CONTAIN",
            type="CONTAIN",
            source=file_id,
            target=chunk_id,
        ))
        node_ids.append(chunk_id)
        # Advance with overlap; ensure forward progress.
        next_start = end - _FALLBACK_CHUNK_OVERLAP
        if next_start <= start:
            next_start = end
        start = next_start

    file_index.add(rel_path, {
        "file_id": file_id,
        "language": language,
        "nodes": node_ids,
    })
    return file_id