from __future__ import annotations
import hashlib
import logging
import os
import re
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

try:
    import yaml
except ImportError:
    yaml = None

from ..graph.models import (
    ConceptNode,
    DocumentChunkNode,
    DocumentNode,
    Edge,
    SectionNode,
)
from .document_content import (
    DocumentContentError,
    DocumentContentPolicy,
    _relative_posix,
    utf8_size,
)

logger = logging.getLogger(__name__)


def _safe_relative_posix(file_path: Path, project_path: Path) -> str:
    """Compute a project-relative POSIX path, resilient to Windows 8.3 short paths.

    ``pathlib.relative_to`` can fail on Python 3.14/Windows when one path is
    resolved to an 8.3 short name and the other is not.  Fall back to
    ``os.path.relpath`` which does not depend on resolve consistency.
    """
    import os as _os
    try:
        return file_path.resolve().relative_to(project_path.resolve()).as_posix()
    except (OSError, ValueError):
        rel = _os.path.relpath(str(file_path), str(project_path))
        return rel.replace("\\", "/")


# Format label per file extension (stored in DocumentNode.format).
_FORMAT_MAP = {
    ".md": "markdown", ".markdown": "markdown",
    ".txt": "text", ".text": "text",
    ".rst": "rst",
    ".html": "html", ".htm": "html",
    ".csv": "csv",
    ".json": "json",
    ".adoc": "asciidoc", ".asciidoc": "asciidoc",
    ".org": "org",
    # Office formats (converted to Markdown via MarkItDown)
    ".docx": "docx", ".doc": "docx",
    ".xlsx": "xlsx", ".xls": "xlsx",
    ".pptx": "pptx", ".ppt": "pptx",
    ".pdf": "pdf",
}

# Lazily-initialized MarkItDown converter (heavy import).
_markitdown = None


def _get_markitdown():
    """Return a cached MarkItDown instance, or None if unavailable."""
    global _markitdown
    if _markitdown is None:
        try:
            from markitdown import MarkItDown
            _markitdown = MarkItDown()
        except ImportError:
            logger.warning("markitdown not installed; non-.md documents will be parsed as plain text")
        except MemoryError:
            raise
        except Exception as e:
            logger.warning("markitdown init failed: %s", e)
    return _markitdown


@dataclass
class DocParseResult:
    document: DocumentNode
    sections: list[SectionNode] = field(default_factory=list)
    chunks: list[DocumentChunkNode] = field(default_factory=list)
    concepts: list[ConceptNode] = field(default_factory=list)
    references: list[Edge] = field(default_factory=list)


class DocumentParser:
    # Chunk sizing targets token counts (350-450 tokens, ~12% overlap) so the
    # same setting works for both Latin text (~4 chars/token) and CJK text
    # (~1 char/token).  ``_chunk_target_chars`` converts to a character budget
    # per document based on its CJK ratio.
    CHUNK_TARGET_TOKENS = 400
    CHUNK_OVERLAP_TOKENS = 50
    CHUNK_TARGET_CHARS = 1500
    CHUNK_OVERLAP_CHARS = 150
    MAX_SECTION_NODES = 4096
    MAX_SECTION_TITLES = 4096
    MAX_CHUNKS = 4096
    MAX_CONCEPT_NODES = 4096
    MAX_TITLE_CHARS = 240
    MAX_CONCEPT_NAME_CHARS = 240
    MAX_METADATA_FILE_BYTES = 16 * 1024 * 1024
    HASH_CHUNK_BYTES = 1024 * 1024
    MAX_STRUCTURE_LINES = 100_000
    MAX_STRUCTURE_CHARS = 4 * 1024 * 1024
    MAX_FRONT_MATTER_BYTES = 64 * 1024
    MAX_SUMMARY_SCAN_CHARS = 64 * 1024

    def __init__(self, policy: DocumentContentPolicy | None = None):
        self.policy = policy

    def parse_file(
        self,
        file_path: Path,
        project_path: Path,
        *,
        rel_path: str | None = None,
        display_path: Path | None = None,
    ) -> DocParseResult:
        # Paths are part of the stable document identity.  Always use the
        # project-relative POSIX spelling so a graph built on Windows has the
        # same IDs (and can be incrementally updated by slash-normalized
        # watcher events) as one built on POSIX.
        rel_path = (
            _relative_posix(rel_path, "rel_path")
            if rel_path is not None
            else _safe_relative_posix(file_path, project_path)
        )
        display_path = display_path or file_path
        selected = self.policy is not None and self.policy.should_store(rel_path)
        ext = display_path.suffix.lower()
        fmt = _FORMAT_MAP.get(ext, "unknown")
        raw_limit = (
            self.policy.max_file_bytes
            if selected
            else self.MAX_METADATA_FILE_BYTES
        )
        raw, input_md5, raw_line_count, raw_size = self._read_source_snapshot(
            file_path,
            raw_limit,
            stop_after_limit=bool(
                selected and self.policy is not None
                and self.policy.on_limit == "error"
            ),
        )
        if selected:
            file_within_limit = self.policy.validate_file_size(raw_size, rel_path)
            if not file_within_limit:
                return self._omitted_file_result(
                    display_path, rel_path, fmt,
                    input_md5=input_md5, line_count=raw_line_count,
                )
        elif raw_size > self.MAX_METADATA_FILE_BYTES:
            return self._metadata_only_file_result(
                display_path, rel_path, fmt,
                input_md5=input_md5, line_count=raw_line_count,
            )
        if raw is None:  # pragma: no cover - guarded by the size branches above
            raise DocumentContentError(
                f"document snapshot exceeded its read limit: {rel_path}"
            )

        # .md files are parsed natively; everything else is converted to
        # Markdown from the bounded, stable raw snapshot. MarkItDown must never
        # reopen the live project path after the size check because an atomic
        # replacement there could otherwise bypass the raw-file budget.
        if ext in (".md", ".markdown"):
            content = self._decode_snapshot_text(raw)
            converted = False
        else:
            content, converted = self._convert_snapshot_to_markdown(
                raw, display_path,
            )
            fmt = fmt  # keep original format label even after conversion
        # Do not keep the raw bytes and decoded/converted text alive together.
        del raw

        # Detect base64/hex binary noise (e.g. tokenizer.json model weights).
        # Such content carries no semantic value but would pollute BM25 indexes
        # and consume the stored-content budget.  Preserve metadata only.
        if self._is_binary_noise_content(content):
            return self._binary_noise_result(
                display_path, rel_path, fmt, content,
                input_md5=input_md5, converted=converted,
            )

        content_within_limit = True
        if selected:
            content_within_limit = self.policy.validate_content(content, rel_path)
        md5 = self.text_digest(content)
        if selected and not content_within_limit:
            return self._omitted_content_result(
                file_path=display_path,
                rel_path=rel_path,
                fmt=fmt,
                input_md5=input_md5,
                canonical_md5=md5,
                content=content,
                converted=converted,
            )
        if not selected and utf8_size(content) > self.MAX_METADATA_FILE_BYTES:
            return self._omitted_content_result(
                file_path=display_path,
                rel_path=rel_path,
                fmt=fmt,
                input_md5=input_md5,
                canonical_md5=md5,
                content=content,
                converted=converted,
                content_state="not_selected",
            )

        line_count = self._text_line_count(content)
        structure_degraded = (
            line_count > self.MAX_STRUCTURE_LINES
            or len(content) > self.MAX_STRUCTURE_CHARS
        )
        if structure_degraded:
            # A bounded prefix is enough for title/TOC metadata.  In
            # particular, never split a multi-million-line snapshot into a
            # multi-million-element list merely to derive graph structure.
            structure_lines = content[:self.MAX_SUMMARY_SCAN_CHARS].splitlines()
        else:
            structure_lines = content.splitlines()
        title = self._extract_title(structure_lines, display_path.stem)
        summary = self._extract_summary(content, structure_lines)
        section_titles = self._extract_section_titles(structure_lines)

        store_content = selected and content_within_limit
        if store_content:
            content_state = "full"
        elif selected:
            # This state is only reachable with the explicit on_limit=omit
            # policy. on_limit=error raises before a partial graph is built.
            content_state = "omitted_oversize"
        else:
            content_state = "not_selected"

        doc_id = f"doc_{hashlib.md5(rel_path.encode()).hexdigest()[:12]}"
        document = DocumentNode(
            id=doc_id,
            title=title,
            path=rel_path,
            format=fmt,
            line_count=line_count,
            md5=md5,
            input_md5=input_md5,
            summary=summary,
            section_titles=section_titles,
            content=content if store_content else None,
            content_state=content_state,
            content_complete=store_content,
            content_bytes=utf8_size(content) if store_content else 0,
            content_encoding="utf-8",
            content_representation=(
                "converted_markdown" if converted else "source_text"
            ),
        )

        if structure_degraded:
            sections = self._degraded_sections(
                content,
                doc_id,
                title,
                line_count,
                include_preview=not store_content,
            )
        else:
            sections = self._parse_sections(
                structure_lines, doc_id, title, include_preview=not store_content,
            )
        chunks = (
            self._build_chunks(content, document, sections)
            if store_content
            else []
        )
        concepts = self._extract_concepts(content, doc_id)
        references: list[Edge] = []

        return DocParseResult(
            document=document,
            sections=sections,
            chunks=chunks,
            concepts=concepts,
            references=references,
        )

    @classmethod
    def file_digest(cls, path: Path) -> str:
        """Hash one stable opened file generation with bounded memory."""
        digest = hashlib.md5()
        try:
            with path.open("rb") as stream:
                before = os.fstat(stream.fileno())
                while True:
                    chunk = stream.read(cls.HASH_CHUNK_BYTES)
                    if not chunk:
                        break
                    digest.update(chunk)
                after = os.fstat(stream.fileno())
            current = path.stat()
        except OSError as exc:
            raise DocumentContentError(
                f"cannot hash document {path}: {exc}"
            ) from exc
        signature = cls._stat_signature(before)
        if (
            cls._stat_signature(after) != signature
            or cls._stat_signature(current) != signature
        ):
            raise DocumentContentError(
                f"document changed while it was being hashed: {path}"
            )
        return digest.hexdigest()

    @staticmethod
    def _stat_signature(value: os.stat_result) -> tuple[int, int, int, int]:
        """Return identity and mutation fields for one opened file generation.

        ``st_ctime_ns`` is deliberately excluded: on Windows NTFS it reports
        creation time and its value can diverge between ``os.fstat`` on an open
        handle and ``path.stat`` on the path right after a write, which produces
        spurious "changed while being read" false positives (100% repro on a
        write-then-read sequence). ``st_mtime_ns`` + ``st_size`` detect content
        mutation and ``st_dev``/``st_ino`` detect atomic replacement, which is
        sufficient for the open-generation stability check.
        """
        return (
            int(value.st_dev),
            int(value.st_ino),
            int(value.st_size),
            int(value.st_mtime_ns),
        )

    @classmethod
    def _read_source_snapshot(
        cls,
        path: Path,
        max_bytes: int,
        *,
        stop_after_limit: bool = False,
    ) -> tuple[bytes | None, str, int, int]:
        """Read one stable raw snapshot with a hard materialisation bound.

        The digest, size, line count, and returned bytes all come from the same
        opened handle. Files larger than ``max_bytes`` are streamed for
        metadata without retaining their body. Under the fail-fast error
        policy, reading stops as soon as the limit is known to be exceeded.
        """
        if max_bytes <= 0:
            raise DocumentContentError("document read limit must be positive")

        digest = hashlib.md5()
        captured: bytearray | None = bytearray()
        size = 0
        newline_count = 0
        last_byte: int | None = None
        try:
            with path.open("rb") as stream:
                before = os.fstat(stream.fileno())
                if stop_after_limit and before.st_size > max_bytes:
                    return None, digest.hexdigest(), 0, int(before.st_size)
                while True:
                    chunk = stream.read(cls.HASH_CHUNK_BYTES)
                    if not chunk:
                        break
                    digest.update(chunk)
                    size += len(chunk)
                    newline_count += chunk.count(b"\n")
                    last_byte = chunk[-1]
                    if captured is not None:
                        if size <= max_bytes:
                            captured.extend(chunk)
                        else:
                            captured = None
                    if stop_after_limit and size > max_bytes:
                        return None, digest.hexdigest(), 0, size
                after = os.fstat(stream.fileno())
        except OSError as exc:
            raise DocumentContentError(
                f"cannot read document {path}: {exc}"
            ) from exc

        try:
            current = path.stat()
        except OSError as exc:
            raise DocumentContentError(
                f"document changed while it was being parsed: {path} ({exc})"
            ) from exc
        signature = cls._stat_signature(before)
        if (
            cls._stat_signature(after) != signature
            or cls._stat_signature(current) != signature
        ):
            raise DocumentContentError(
                f"document changed while it was being parsed: {path}"
            )

        line_count = 0 if size == 0 else newline_count + (last_byte != 0x0A)
        return (
            bytes(captured) if captured is not None else None,
            digest.hexdigest(),
            int(line_count),
            size,
        )

    @classmethod
    def _raw_file_stats(cls, path: Path) -> tuple[str, int]:
        """Return a streaming digest and raw logical-line count."""
        digest = hashlib.md5()
        size = 0
        newline_count = 0
        last_byte: int | None = None
        with path.open("rb") as stream:
            while True:
                chunk = stream.read(cls.HASH_CHUNK_BYTES)
                if not chunk:
                    break
                digest.update(chunk)
                size += len(chunk)
                newline_count += chunk.count(b"\n")
                last_byte = chunk[-1]
        line_count = 0 if size == 0 else newline_count + (last_byte != 0x0A)
        return digest.hexdigest(), int(line_count)

    @classmethod
    def text_digest(cls, content: str) -> str:
        """Hash canonical text without one full-size encoded temporary."""
        digest = hashlib.md5()
        step = 64 * 1024
        for offset in range(0, len(content), step):
            digest.update(content[offset:offset + step].encode("utf-8"))
        return digest.hexdigest()

    def _omitted_file_result(
        self, file_path: Path, rel_path: str, fmt: str,
        *, input_md5: str | None = None, line_count: int | None = None,
    ) -> DocParseResult:
        """Create metadata for a raw oversize file without loading its body."""
        if input_md5 is None or line_count is None:
            input_md5, line_count = self._raw_file_stats(file_path)
        return self._make_omitted_result(
            file_path=file_path,
            rel_path=rel_path,
            fmt=fmt,
            input_md5=input_md5,
            canonical_md5=input_md5,
            line_count=line_count,
            title=self._bounded_label(
                file_path.stem.replace("_", " ").replace("-", " ").title(),
                self.MAX_TITLE_CHARS,
            ),
            representation="omitted_source",
            content_state="omitted_oversize",
        )

    def _metadata_only_file_result(
        self, file_path: Path, rel_path: str, fmt: str,
        *, input_md5: str | None = None, line_count: int | None = None,
    ) -> DocParseResult:
        """Bound legacy metadata parsing for an unselected giant document."""
        if input_md5 is None or line_count is None:
            input_md5, line_count = self._raw_file_stats(file_path)
        return self._make_omitted_result(
            file_path=file_path,
            rel_path=rel_path,
            fmt=fmt,
            input_md5=input_md5,
            canonical_md5=input_md5,
            line_count=line_count,
            title=self._bounded_label(
                file_path.stem.replace("_", " ").replace("-", " ").title(),
                self.MAX_TITLE_CHARS,
            ),
            representation="omitted_source",
            content_state="not_selected",
        )

    def _omitted_content_result(
        self,
        *,
        file_path: Path,
        rel_path: str,
        fmt: str,
        input_md5: str,
        canonical_md5: str,
        content: str,
        converted: bool,
        content_state: str = "omitted_oversize",
    ) -> DocParseResult:
        """Drop an inflated canonical representation before structural parsing."""
        prefix_lines = content[:64 * 1024].splitlines()
        title = self._extract_title(prefix_lines, file_path.stem)
        line_count = content.count("\n")
        if content and not content.endswith(("\n", "\r")):
            line_count += 1
        return self._make_omitted_result(
            file_path=file_path,
            rel_path=rel_path,
            fmt=fmt,
            input_md5=input_md5,
            canonical_md5=canonical_md5,
            line_count=line_count,
            title=title,
            representation=(
                "converted_markdown" if converted else "source_text"
            ),
            content_state=content_state,
        )

    def _binary_noise_result(
        self,
        file_path: Path,
        rel_path: str,
        fmt: str,
        content: str,
        *,
        input_md5: str,
        converted: bool,
    ) -> DocParseResult:
        """Preserve metadata only for base64/hex binary-noise documents.

        The body (base64 model weights, hex dumps, etc.) is excluded from
        sections, chunks, and stored content so it cannot pollute BM25 indexes
        or consume the stored-content budget.  An implicit root section with
        an empty body keeps the line range addressable for ``get_content``.
        """
        prefix_lines = content[:64 * 1024].splitlines()
        title = self._extract_title(prefix_lines, file_path.stem)
        line_count = self._text_line_count(content)
        md5 = self.text_digest(content)
        doc_id = f"doc_{hashlib.md5(rel_path.encode()).hexdigest()[:12]}"
        document = DocumentNode(
            id=doc_id,
            title=title,
            path=rel_path,
            format=fmt,
            line_count=line_count,
            md5=md5,
            input_md5=input_md5,
            summary=None,
            section_titles=[],
            content=None,
            content_state="omitted_binary",
            content_complete=False,
            content_bytes=0,
            content_encoding="utf-8",
            content_representation=(
                "converted_markdown" if converted else "source_text"
            ),
        )
        # Implicit root section with empty content — preserves line range
        # without letting binary noise into BM25.
        section = SectionNode(
            id=f"sec_{doc_id}_implicit",
            title=title,
            level=1,
            doc_id=doc_id,
            line_start=1,
            line_end=max(1, line_count),
            content="",
        )
        return DocParseResult(
            document=document,
            sections=[section],
            chunks=[],
            concepts=[],
            references=[],
        )

    @staticmethod
    def _make_omitted_result(
        *,
        file_path: Path,
        rel_path: str,
        fmt: str,
        input_md5: str,
        canonical_md5: str,
        line_count: int,
        title: str,
        representation: str,
        content_state: str,
    ) -> DocParseResult:
        doc_id = f"doc_{hashlib.md5(rel_path.encode()).hexdigest()[:12]}"
        document = DocumentNode(
            id=doc_id,
            title=title,
            path=rel_path,
            format=fmt,
            line_count=max(0, int(line_count)),
            md5=canonical_md5,
            input_md5=input_md5,
            summary=None,
            section_titles=[],
            content=None,
            content_state=content_state,
            content_complete=False,
            content_bytes=0,
            content_encoding="utf-8",
            content_representation=representation,
        )
        return DocParseResult(document=document)

    def _read_text(self, path: Path) -> str:
        """Read a file as text with the unified encoding strategy.

        ``MemoryError`` from the underlying read propagates so a genuinely
        exhausted process is not masked by a fallback.
        """
        return self._decode_document_bytes(path.read_bytes())

    @staticmethod
    def _decode_document_bytes(raw: bytes) -> str:
        """Decode document bytes with a multi-layer encoding strategy.

        Order matters for correctness:

        1. **BOM detection** — UTF-8/UTF-16 BOM unambiguously identifies the
           encoding.
        2. **UTF-8 strict** — succeeds for the vast majority of modern files
           (including emoji and accented Latin).  Trying UTF-8 *first* prevents
           GBK from silently mis-decoding UTF-8 content (e.g. ``é`` → ``茅``).
        3. **GBK strict** — only reached when the file is genuinely not UTF-8.
           GBK covers Simplified Chinese Windows files, the most common non-
           UTF-8 case.  Strict mode rejects Shift-JIS/Big5 so they fall through
           to layer 4 instead of producing silent garbage.
        4. **charset_normalizer** — best-effort detection for Shift-JIS, Big5,
           Latin-1, and other encodings that GBK strict rejects.
        5. **UTF-8 replace** — last resort; invalid bytes become ``□`` rather
           than silent corruption.
        """
        # 1. BOM detection
        if raw.startswith(b"\xef\xbb\xbf"):
            text = raw[3:].decode("utf-8", errors="replace")
        elif raw.startswith(b"\xff\xfe") or raw.startswith(b"\xfe\xff"):
            text = raw.decode("utf-16", errors="replace")
        else:
            # 2. UTF-8 strict
            try:
                text = raw.decode("utf-8")
            except UnicodeDecodeError:
                # 3. GBK strict
                try:
                    text = raw.decode("gbk")
                except UnicodeDecodeError:
                    # 4. charset_normalizer best-effort
                    try:
                        from charset_normalizer import from_bytes
                        detected = from_bytes(raw).best()
                        text = str(detected) if detected else raw.decode(
                            "utf-8", errors="replace"
                        )
                    except Exception:
                        # 5. Last resort
                        text = raw.decode("utf-8", errors="replace")
        return text.replace("\r\n", "\n").replace("\r", "\n")

    @staticmethod
    def _decode_snapshot_text(raw: bytes) -> str:
        """Decode bounded snapshot bytes using the unified encoding strategy."""
        return DocumentParser._decode_document_bytes(raw)

    # Thresholds for detecting base64/hex binary noise in document content.
    # A tokenizer.json or model-weights file is dominated by very long
    # tokens whose characters all fall in the base64 or hex alphabet.
    _BINARY_NOISE_MIN_TOKEN_LEN = 80
    _BINARY_NOISE_MIN_RATIO = 0.60
    _BASE64_CHARS = frozenset(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
    )
    _HEX_CHARS = frozenset("0123456789abcdefABCDEF")

    @classmethod
    def _is_binary_noise_content(cls, content: str) -> bool:
        """Detect whether content is dominated by base64/hex binary noise.

        Files like ``tokenizer.json`` or model-weight dumps contain very long
        base64 or hex strings that carry no semantic value but would pollute
        BM25 indexes.  This heuristic flags them so their body is excluded
        from sections, chunks, and stored content while preserving metadata
        (title, path, md5, line count).

        To avoid false positives on repetitive-but-meaningful text (e.g. a
        document full of ``=====`` dividers), a long token must have **both**
        a base64/hex-only charset **and** enough character diversity (>= 10
        unique characters) to look like encoded binary rather than repeated
        punctuation.
        """
        if not content or len(content) < 200:
            return False
        # Sample up to 64 KiB to keep the check constant-time for huge files.
        sample = content[:65536]
        long_token_total = 0
        for token in sample.split():
            if len(token) < cls._BINARY_NOISE_MIN_TOKEN_LEN:
                continue
            # Strip JSON/text wrapper characters (quotes, braces, colons) so a
            # base64 blob inside ``{"weights": "..."}`` is still detected.
            stripped = token.strip('"\'{}[]():,')
            if len(stripped) < cls._BINARY_NOISE_MIN_TOKEN_LEN:
                continue
            charset = set(stripped)
            is_b64 = charset <= cls._BASE64_CHARS
            is_hex = charset <= cls._HEX_CHARS
            if not (is_b64 or is_hex):
                continue
            # Require character diversity so repeated punctuation like "====="
            # or "AAAAAA" is not flagged.  Real base64/hex has many distinct
            # characters; repeated single-character tokens do not.
            if len(charset) < 10:
                continue
            long_token_total += len(stripped)
        if not long_token_total:
            return False
        ratio = long_token_total / len(sample)
        return ratio >= cls._BINARY_NOISE_MIN_RATIO

    # Formats where MarkItDown acts as a plain-text passthrough.  For these we
    # decode with our own encoding strategy (UTF-8 → GBK → charset_normalizer)
    # instead of letting MarkItDown's charset_normalizer mis-detect GBK as
    # cp949 (Korean), which produces silent garbage for Simplified Chinese.
    _PLAINTEXT_FORMATS = frozenset({
        ".txt", ".text", ".json", ".org", ".rst", ".adoc", ".asciidoc",
    })

    # Binary Office/PDF formats: must be written as raw bytes (not decoded to
    # text) so MarkItDown can parse their binary structure (zip/xml for
    # docx/xlsx/pptx, binary for pdf).  Decoding these as text corrupts them.
    _BINARY_FORMATS = frozenset({
        ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt", ".pdf",
    })

    def _convert_snapshot_to_markdown(
        self, raw: bytes, original_path: Path,
    ) -> tuple[str, bool]:
        """Convert immutable bounded bytes instead of reopening a live path.

        For plain-text formats (txt/json/org/rst/adoc) MarkItDown is just a
        passthrough, so we decode ourselves to avoid its unreliable
        charset_normalizer.  For structured text formats (html/csv) we
        pre-decode to UTF-8 text and write that to the staging file so
        MarkItDown's converter receives correctly-decoded content.  For binary
        Office/PDF formats (docx/xlsx/pptx/pdf) we write the raw bytes directly
        — decoding them as text would corrupt the binary structure.
        """
        ext = original_path.suffix.lower()
        # Plain-text passthrough formats: decode and return directly.
        if ext in self._PLAINTEXT_FORMATS:
            return self._decode_document_bytes(raw), False
        try:
            with tempfile.TemporaryDirectory(prefix="bot-brain-doc-") as root:
                snapshot_path = Path(root) / original_path.name
                if ext in self._BINARY_FORMATS:
                    # Binary formats: write raw bytes so MarkItDown can parse
                    # the binary structure (zip/xml/pdf).
                    snapshot_path.write_bytes(raw)
                else:
                    # Structured text formats (html/csv): pre-decode to UTF-8.
                    decoded = self._decode_document_bytes(raw)
                    snapshot_path.write_text(decoded, encoding="utf-8")
                return self._convert_to_markdown(snapshot_path)
        except OSError as exc:
            raise DocumentContentError(
                f"cannot stage document conversion for {original_path}: {exc}"
            ) from exc

    def _convert_to_markdown(self, path: Path) -> tuple[str, bool]:
        """Convert a non-.md file to Markdown via MarkItDown.

        Returns (markdown_content, converted). If MarkItDown is unavailable
        or conversion fails, falls back to reading as plain text.
        """
        md = _get_markitdown()
        if md is None:
            return self._read_text(path), False
        try:
            result = md.convert(str(path))
            return result.markdown, True
        except MemoryError:
            raise
        except Exception as e:
            logger.warning("MarkItDown conversion failed for %s: %s; falling back to text", path, e)
            return self._read_text(path), False

    def _extract_title(self, lines: list[str], fallback: str) -> str:
        for line in lines:
            stripped = line.strip()
            if stripped.startswith("# "):
                return self._bounded_label(
                    stripped[2:].strip(), self.MAX_TITLE_CHARS,
                )
        return self._bounded_label(
            fallback.replace("_", " ").replace("-", " ").title(),
            self.MAX_TITLE_CHARS,
        )

    @staticmethod
    def _bounded_label(value: str, limit: int) -> str:
        """Bound repeated graph labels so one heading cannot amplify storage."""
        text = str(value or "").strip()
        if len(text) <= limit:
            return text
        return text[:max(0, limit - 1)].rstrip() + "…"

    @staticmethod
    def _text_line_count(content: str) -> int:
        """Count ordinary text lines without constructing ``splitlines()``."""
        if not content:
            return 0
        # Canonical parser text normalises CRLF/CR to LF before this point.
        return content.count("\n") + (not content.endswith("\n"))

    def _extract_summary(
        self, content: str, lines: list[str] | None = None,
    ) -> str | None:
        """提取文档摘要,优先级:front matter > 首段 > 前3行"""
        # 1. YAML front matter.  Find and parse only a small, complete block;
        # never hand a multi-megabyte unterminated header to the YAML parser.
        body_start = 0
        front_matter = self._bounded_front_matter(content)
        if front_matter is not None:
            payload, body_start = front_matter
            if yaml is not None:
                try:
                    fm = yaml.safe_load(payload)
                    description = (
                        fm.get("description") if isinstance(fm, dict) else None
                    )
                    if isinstance(description, str) and description:
                        return description[:200]
                except MemoryError:
                    raise
                except Exception:
                    pass

        # Both fallback strategies inspect only a bounded prefix.  ``lines``
        # is intentionally ignored here because callers may have a full list
        # for small files but must not need one for giant snapshots.
        summary_text = content[
            body_start:body_start + self.MAX_SUMMARY_SCAN_CHARS
        ]
        summary_lines = summary_text.splitlines()

        # 2. 开头到第一个 # 之间的正文
        body_lines: list[str] = []
        body_chars = 0
        for line in summary_lines:
            if line.startswith("#"):
                break
            stripped = line.strip()
            if stripped and not stripped.startswith("---"):
                body_lines.append(stripped)
                body_chars += len(stripped) + (1 if len(body_lines) > 1 else 0)
                if body_chars >= 200:
                    break
        if body_lines:
            return " ".join(body_lines)[:200]

        # 3. 前 3 行非空非标题文本
        text_lines: list[str] = []
        for line in summary_lines:
            if line.strip() and not line.startswith("#"):
                text_lines.append(line.strip())
                if len(text_lines) >= 3:
                    break
        if text_lines:
            return " ".join(text_lines)[:200]

        return None

    def _bounded_front_matter(self, content: str) -> tuple[str, int] | None:
        """Return a complete <=64 KiB YAML header and following body offset."""
        if not content.startswith("---"):
            return None
        first_end = content.find("\n", 0, self.MAX_FRONT_MATTER_BYTES + 1)
        if first_end < 0 or content[:first_end].rstrip("\r") != "---":
            return None

        payload_start = first_end + 1
        cursor = payload_start
        while cursor <= min(len(content), self.MAX_FRONT_MATTER_BYTES):
            line_end = content.find(
                "\n", cursor, self.MAX_FRONT_MATTER_BYTES + 1,
            )
            if line_end < 0:
                line_end = min(len(content), self.MAX_FRONT_MATTER_BYTES + 1)
            if content[cursor:line_end].rstrip("\r") == "---":
                closing_end = line_end + (line_end < len(content))
                header = content[:closing_end]
                if utf8_size(header) > self.MAX_FRONT_MATTER_BYTES:
                    return None
                return content[payload_start:cursor], closing_end
            if line_end >= len(content) or line_end > self.MAX_FRONT_MATTER_BYTES:
                break
            cursor = line_end + 1
        return None

    def _extract_section_titles(self, lines: list[str]) -> list[str]:
        """提取所有标题,供 LLM 浏览目录"""
        titles: list[str] = []
        for line in lines:
            if line.startswith("#"):
                titles.append(self._bounded_label(
                    line.strip("# ").strip(), self.MAX_TITLE_CHARS,
                ))
                if len(titles) >= self.MAX_SECTION_TITLES:
                    break
        return titles

    def _parse_sections(
        self,
        lines: list[str],
        doc_id: str,
        default_title: str = "Document",
        *,
        include_preview: bool = True,
    ) -> list[SectionNode]:
        sections = []
        current_title = ""
        current_level = 0
        current_start = 0
        current_content_lines: list[str] = []
        current_content_chars = 0

        for i, line in enumerate(lines):
            match = re.match(r'^(#{1,6})\s+(.+)', line)
            if match:
                if current_title:
                    if len(sections) < self.MAX_SECTION_NODES:
                        content = (
                            "\n".join(current_content_lines).strip()[:500]
                            if include_preview
                            else ""
                        )
                        sec_id = f"sec_{doc_id}_{current_level}_{len(sections)}"
                        sections.append(SectionNode(
                            id=sec_id,
                            title=current_title,
                            level=current_level,
                            doc_id=doc_id,
                            line_start=current_start + 1,
                            line_end=i,
                            content=content,
                        ))
                current_level = len(match.group(1))
                current_title = self._bounded_label(
                    match.group(2), self.MAX_TITLE_CHARS,
                )
                current_start = i
                current_content_lines = []
                current_content_chars = 0
            elif include_preview and len(sections) < self.MAX_SECTION_NODES:
                if not current_content_lines and not line.strip():
                    continue
                separator_chars = 1 if current_content_lines else 0
                remaining = 501 - current_content_chars - separator_chars
                if remaining > 0:
                    current_content_lines.append(line[:remaining])
                    current_content_chars += (
                        separator_chars + min(len(line), remaining)
                    )

        if current_title and len(sections) < self.MAX_SECTION_NODES:
            content = (
                "\n".join(current_content_lines).strip()[:500]
                if include_preview
                else ""
            )
            sec_id = f"sec_{doc_id}_{current_level}_{len(sections)}"
            sections.append(SectionNode(
                id=sec_id,
                title=current_title,
                level=current_level,
                doc_id=doc_id,
                line_start=current_start + 1,
                line_end=len(lines),
                content=content,
            ))

        if not sections and any(line.strip() for line in lines):
            # Plain-text documents and Markdown without headings previously
            # had no addressable section at all. The implicit root preserves
            # the original line range while keeping the short section preview.
            content = self._bounded_line_preview(lines) if include_preview else ""
            sections.append(SectionNode(
                id=f"sec_{doc_id}_implicit",
                title=default_title,
                level=1,
                doc_id=doc_id,
                line_start=1,
                line_end=len(lines),
                content=content,
            ))

        return sections

    def _degraded_sections(
        self,
        content: str,
        doc_id: str,
        title: str,
        line_count: int,
        *,
        include_preview: bool,
    ) -> list[SectionNode]:
        """Represent an unusually large/line-dense document with one node."""
        if not content:
            return []
        preview = (
            content[:500].strip()
            if include_preview
            else ""
        )
        return [SectionNode(
            id=f"sec_{doc_id}_implicit",
            title=title,
            level=1,
            doc_id=doc_id,
            line_start=1,
            line_end=max(1, line_count),
            content=preview,
        )]

    @staticmethod
    def _bounded_line_preview(lines: list[str], limit: int = 500) -> str:
        """Build a short preview without joining an arbitrarily large body."""
        pieces: list[str] = []
        used = 0
        for line in lines:
            if not pieces and not line.strip():
                continue
            separator = 1 if pieces else 0
            remaining = limit + 1 - used - separator
            if remaining <= 0:
                break
            pieces.append(line[:remaining])
            used += separator + min(len(line), remaining)
            if used > limit:
                break
        return "\n".join(pieces).strip()[:limit]

    def _chunk_target_chars(self, content: str) -> int:
        """Convert the token target to a character budget for this content."""
        sample = content[:8192] if len(content) > 8192 else content
        if not sample:
            return self.CHUNK_TARGET_CHARS
        cjk = 0
        for ch in sample:
            code = ord(ch)
            if (
                0x3400 <= code <= 0x4DBF
                or 0x4E00 <= code <= 0x9FFF
                or 0xF900 <= code <= 0xFAFF
                or 0x3040 <= code <= 0x30FF
                or 0xAC00 <= code <= 0xD7AF
            ):
                cjk += 1
        ratio = cjk / len(sample)
        # Pure CJK (~1 char/token) -> target_tokens chars.
        # Pure Latin (~4 chars/token) -> target_tokens * 4 chars.
        chars_per_token = 1.0 + (1.0 - ratio) * 3.0
        return max(200, int(self.CHUNK_TARGET_TOKENS * chars_per_token))

    def _chunk_overlap_chars(self, target_chars: int) -> int:
        """Overlap is ~12% of the target character budget."""
        return max(20, int(target_chars * self.CHUNK_OVERLAP_TOKENS / self.CHUNK_TARGET_TOKENS))

    def _build_chunks(
        self,
        content: str,
        document: DocumentNode,
        sections: list[SectionNode],
    ) -> list[DocumentChunkNode]:
        """Build deterministic retrieval metadata without duplicating text.

        Character ranges are half-open offsets into ``document.content``.
        Short sections deliberately share chunks so heading-heavy documents
        cannot create one graph node per heading. Long documents keep a small
        overlap and are hard-capped at ``MAX_CHUNKS`` metadata nodes.
        """
        if not content or not content.strip():
            return []

        base_target = self._chunk_target_chars(content)
        overlap = self._chunk_overlap_chars(base_target)
        # Account for overlap when sizing windows so normal splitting stays
        # below the hard cap. The final slot absorbs any remainder when a
        # paragraph boundary causes unusually short windows.
        target_chars = max(
            base_target,
            2 * (
                (len(content) + self.MAX_CHUNKS - 1) // self.MAX_CHUNKS
                + overlap
                + 50  # word-boundary backtracking below
            ),
        )
        ordered_sections = sorted(sections, key=lambda item: item.line_start)
        section_index = -1
        line_scan = 0
        line_number = 1
        chunks: list[DocumentChunkNode] = []
        start = 0
        while start < len(content) and len(chunks) < self.MAX_CHUNKS:
            if len(chunks) == self.MAX_CHUNKS - 1:
                end = len(content)
            else:
                end = self._chunk_end(
                    content, start, len(content), target_chars=target_chars,
                )
            if end <= start:
                end = min(len(content), start + target_chars)

            line_number += content.count("\n", line_scan, start)
            line_scan = start
            while (
                section_index + 1 < len(ordered_sections)
                and ordered_sections[section_index + 1].line_start <= line_number
            ):
                section_index += 1
            chunk_text = content[start:end]
            if chunk_text.strip():
                identity = f"{document.id}:{start}:{end}"
                chunk_id = (
                    "dchunk_"
                    + hashlib.md5(identity.encode("utf-8")).hexdigest()[:16]
                )
                last_char = max(start, end - 1)
                chunk_line_end = (
                    line_number + content.count("\n", start, last_char)
                )
                section = (
                    ordered_sections[section_index]
                    if section_index >= 0
                    and line_number >= ordered_sections[section_index].line_start
                    and chunk_line_end <= ordered_sections[section_index].line_end
                    else None
                )
                chunks.append(DocumentChunkNode(
                    id=chunk_id,
                    doc_id=document.id,
                    section_id=section.id if section is not None else None,
                    title=section.title if section is not None else document.title,
                    line_start=line_number,
                    line_end=chunk_line_end,
                    char_start=start,
                    char_end=end,
                ))

            if end >= len(content):
                break
            next_start = max(start + 1, end - overlap)
            # Avoid beginning in the middle of a word while preserving a
            # bounded overlap. If a very long token has no nearby boundary,
            # retain the exact overlap instead of dropping it altogether.
            boundary = next_start
            lower_bound = max(start + 1, next_start - 50)
            while boundary > lower_bound and not content[boundary - 1].isspace():
                boundary -= 1
            if boundary > lower_bound:
                next_start = boundary
            while next_start < end and content[next_start].isspace():
                next_start += 1
            start = min(next_start, end - 1)

        return chunks

    def _chunk_end(
        self,
        content: str,
        start: int,
        range_end: int,
        *,
        target_chars: int | None = None,
    ) -> int:
        chunk_target = target_chars or self.CHUNK_TARGET_CHARS
        target = min(range_end, start + chunk_target)
        if target >= range_end:
            return range_end

        minimum = start + chunk_target // 2
        window = content[minimum:target]
        paragraph_breaks = [
            minimum + match.end()
            for match in re.finditer(r"\n[ \t]*\n", window)
        ]
        if paragraph_breaks:
            return paragraph_breaks[-1]

        # A long paragraph still gets a hard bound, preferably at whitespace.
        end = target
        while end > minimum and not content[end - 1].isspace():
            end -= 1
        return end if end > minimum else target

    def _extract_concepts(self, content: str, doc_id: str) -> list[ConceptNode]:
        concepts = []
        seen: set[str] = set()
        for match in re.finditer(r'`([A-Z][A-Za-z0-9_]{2,})`', content):
            term = self._bounded_label(
                match.group(1), self.MAX_CONCEPT_NAME_CHARS,
            )
            if term not in seen:
                seen.add(term)
                # Concepts are document-owned artifacts.  A global term-only
                # ID made two documents mentioning the same term overwrite
                # each other, and deleting either document then removed the
                # shared node.  Include the owning document in the identity.
                identity = f"{doc_id}:{term}"
                concept_id = f"concept_{hashlib.md5(identity.encode()).hexdigest()[:12]}"
                concepts.append(ConceptNode(
                    id=concept_id,
                    name=term,
                    source=doc_id,
                ))
                if len(concepts) >= self.MAX_CONCEPT_NODES:
                    break
        return concepts