from collections.abc import Mapping
from typing import Any


def add_history_documents(
    entry: dict[str, Any],
    message: Mapping[str, Any],
    documents_map: Mapping[str, Mapping[str, Any]],
    *,
    documents_allowed: bool,
) -> None:
    document_entries = build_history_document_entries(message, documents_map)
    if document_entries and documents_allowed:
        entry["__documents__"] = document_entries


def build_history_document_entries(
    message: Mapping[str, Any],
    documents_map: Mapping[str, Mapping[str, Any]],
) -> list[dict[str, Any]]:
    document_entries = []
    for attachment in message.get("attachments") or []:
        if not isinstance(attachment, Mapping):
            continue

        document_path = attachment.get("document_path")
        if not document_path:
            continue

        document_info = documents_map.get(document_path)
        if not document_info:
            continue

        document_entries.append(
            {
                "name": document_info.get("name") or attachment.get("name") or document_path.rsplit("/", 1)[-1],
                "snapshots": document_info.get("snapshots") or [],
                "text": document_info.get("text") or "",
                "has_text_fallback": bool(document_info.get("has_text_fallback")),
            }
        )
    return document_entries
