"""Bundle documents into XML payloads."""

from __future__ import annotations

from ragflow_sdk.modules.document import Document

from ims_mcp.clients.document import DocumentClient
from ims_mcp.constants import DEFAULT_SORT_ORDER, XML_FILE_CLOSE, XML_FILE_OPEN


class Bundler:
    def __init__(self, document_client: DocumentClient):
        self._documents = document_client

    @staticmethod
    def _meta(doc: Document) -> dict:
        meta = getattr(doc, "meta_fields", {}) or {}
        if isinstance(meta, dict):
            return meta
        return {
            "tags": getattr(meta, "tags", []),
            "sort_order": getattr(meta, "sort_order", None),
        }

    @staticmethod
    def _sort_key(doc: Document) -> tuple[int, str]:
        meta = Bundler._meta(doc)
        raw = meta.get("sort_order", DEFAULT_SORT_ORDER)
        try:
            sort_order = int(raw)
        except (TypeError, ValueError):
            sort_order = DEFAULT_SORT_ORDER
        return sort_order, (doc.name or "")

    def bundle(self, documents: list[Document], dataset_name: str) -> str:
        chunks: list[str] = []
        for doc in sorted(documents, key=self._sort_key):
            meta = self._meta(doc)
            tags = meta.get("tags", []) or []
            if isinstance(tags, str):
                tags = [tags]
            tags_attr = ",".join(str(tag) for tag in tags)
            body = self._documents.download_content(doc)
            chunks.append(
                XML_FILE_OPEN.format(
                    id=doc.id,
                    dataset=dataset_name,
                    name=doc.name,
                    tags=tags_attr,
                )
            )
            chunks.append(body)
            chunks.append(XML_FILE_CLOSE)
        return "\n".join(chunks)
