from __future__ import annotations

import logging
from typing import Any

from .content_builders import MissingDocumentContentMixin

logger = logging.getLogger("dscons.missing_document.bundle")


class MissingDocumentBundleMixin(MissingDocumentContentMixin):
    """Core bundle assembly engine for missing document sets."""

    def build_generation_bundle(
        self,
        project_code: str,
        missing_document_types: list[str],
    ) -> dict[str, Any]:
        """Tạo bundle kế hoạch sinh hồ sơ an toàn cho bước ghi file về sau."""
        normalized_project_code = project_code.strip()
        normalized_document_types = self._normalize_document_types(
            missing_document_types
        )
        generated_at = self._utc_now()

        items: list[dict[str, Any]] = []
        stage_counts: dict[str, int] = {}

        for order, document_type in enumerate(normalized_document_types, start=1):
            document_meta = self._document_index.get(document_type, {})
            doc_stage = str(document_meta.get("doc_stage", "unknown"))
            stage_counts[doc_stage] = stage_counts.get(doc_stage, 0) + 1
            scaffold = self._get_document_scaffold(document_type, document_meta)
            file_name = self._build_output_filename(
                project_code=normalized_project_code,
                document_type=document_type,
                output_filename_suffix=scaffold["output_filename_suffix"],
                file_extension=scaffold["file_extension"],
            )
            output_path = f"generated/{normalized_project_code}/{file_name}"
            placeholder_payload = self._build_placeholder_payload(
                project_code=normalized_project_code,
                document_type=document_type,
                document_meta=document_meta,
                scaffold=scaffold,
                file_name=file_name,
                generated_at=generated_at,
            )
            placeholder_content = self._build_placeholder_content(
                project_code=normalized_project_code,
                document_type=document_type,
                document_meta=document_meta,
                scaffold=scaffold,
                file_name=file_name,
                generated_at=generated_at,
            )

            items.append(
                {
                    "document_type": document_type,
                    "label": document_meta.get("label")
                    or self._humanize_document_type(document_type),
                    "doc_stage": doc_stage,
                    "critical": bool(document_meta.get("critical", False)),
                    "generation_order": order,
                    "generator_type": scaffold["generator_type"],
                    "output_format": scaffold["file_extension"],
                    "mime_type": _TEXT_FORMATS[scaffold["file_extension"]],
                    "output_filename": file_name,
                    "output_path": output_path,
                    "template_key": scaffold.get("template_key"),
                    "required_inputs": list(scaffold["required_inputs"]),
                    "sections": list(scaffold["sections"]),
                    "notes": scaffold.get("notes"),
                    "placeholder_payload": placeholder_payload,
                    "placeholder_content": placeholder_content,
                }
            )

        return {
            "project_code": normalized_project_code,
            "generated_at": generated_at,
            "total_missing_documents": len(items),
            "stage_counts": stage_counts,
            "plan": self._build_generation_plan(items),
            "documents": items,
            "summary": self._build_summary(items),
        }
