from __future__ import annotations

import logging
from typing import Any

from .helpers import MissingDocumentHelpersMixin

logger = logging.getLogger("dscons.missing_document.content")


class MissingDocumentContentMixin(MissingDocumentHelpersMixin):
    """Content, payload, and planning builders for generated missing document packages."""

    def _build_placeholder_payload(
        self,
        project_code: str,
        document_type: str,
        document_meta: dict[str, Any],
        scaffold: dict[str, Any],
        file_name: str,
        generated_at: str,
    ) -> dict[str, Any]:
        """Tạo payload structured để parent agent có thể render hoặc ghi file sau này."""
        return {
            "project_code": project_code,
            "document_type": document_type,
            "document_label": document_meta.get("label")
            or self._humanize_document_type(document_type),
            "doc_stage": document_meta.get("doc_stage", "unknown"),
            "critical": bool(document_meta.get("critical", False)),
            "output": {
                "file_name": file_name,
                "file_extension": scaffold["file_extension"],
                "mime_type": _TEXT_FORMATS[scaffold["file_extension"]],
            },
            "template": {
                "generator_type": scaffold["generator_type"],
                "template_key": scaffold.get("template_key"),
                "sections": list(scaffold["sections"]),
            },
            "required_inputs": [
                {
                    "field_name": field_name,
                    "status": "pending_input",
                    "label": self._humanize_field_name(field_name),
                    "example_value": f"[[{field_name}]]",
                }
                for field_name in scaffold["required_inputs"]
            ],
            "placeholders": {
                field_name: f"[[{field_name}]]"
                for field_name in scaffold["required_inputs"]
            },
            "metadata": {
                "generated_at": generated_at,
                "generation_mode": "safe_placeholder_only",
                "source": "missing_document_generation_service",
            },
        }

    def _build_placeholder_content(
        self,
        project_code: str,
        document_type: str,
        document_meta: dict[str, Any],
        scaffold: dict[str, Any],
        file_name: str,
        generated_at: str,
    ) -> str:
        """Sinh nội dung markdown placeholder an toàn, không phải văn bản phát hành thật."""
        lines = [
            f"# {document_meta.get('label') or self._humanize_document_type(document_type)}",
            "",
            "> Bản nháp placeholder do hệ thống tạo tự động để bổ sung hồ sơ còn thiếu.",
            "> Chỉ dùng cho bước rà soát / chuẩn bị dữ liệu, chưa phải văn bản phát hành.",
            "",
            f"- Mã dự án: {project_code}",
            f"- Loại tài liệu: {document_type}",
            f"- Giai đoạn hồ sơ: {document_meta.get('doc_stage', 'unknown')}",
            f"- Mức độ ưu tiên: {'critical' if document_meta.get('critical') else 'normal'}",
            f"- Tên file dự kiến: {file_name}",
            f"- Thời điểm tạo scaffold: {generated_at}",
            "",
            "## Dữ liệu đầu vào cần bổ sung",
            "",
        ]

        for field_name in scaffold["required_inputs"]:
            lines.append(
                f"- **{self._humanize_field_name(field_name)}**: `[[{field_name}]]`"
            )

        lines.extend(["", "## Khung nội dung đề xuất", ""])

        for section in scaffold["sections"]:
            lines.extend(
                [f"### {section}", "", f"[[noi_dung_{self._slugify(section)}]]", ""]
            )

        lines.extend(
            [
                "## Ghi chú vận hành",
                "",
                "- Reviewer cần xác minh đầy đủ thông tin pháp lý, số liệu và chủ thể ký.",
                "- Có thể dùng payload structured đi kèm để render sang định dạng file text/markdown ở bước sau.",
                "- Không tự động phát hành văn bản này nếu chưa có người phụ trách kiểm tra.",
            ]
        )

        if scaffold.get("notes"):
            lines.extend(["", f"- Ghi chú template: {scaffold['notes']}"])

        return "\n".join(lines)

    def _build_generation_plan(
        self, items: list[dict[str, Any]]
    ) -> list[dict[str, Any]]:
        """Tạo checklist thao tác ngắn gọn cho toàn bộ bundle."""
        plan: list[dict[str, Any]] = []
        for item in items:
            plan.append(
                {
                    "document_type": item["document_type"],
                    "doc_stage": item["doc_stage"],
                    "priority": "high" if item["critical"] else "normal",
                    "next_action": "Bổ sung required_inputs rồi ghi placeholder_content ra file.",
                    "output_path": item["output_path"],
                }
            )
        return plan

    def _build_summary(self, items: list[dict[str, Any]]) -> dict[str, Any]:
        """Tóm tắt nhanh phục vụ API/UI."""
        critical_count = sum(1 for item in items if item["critical"])
        return {
            "critical_documents": critical_count,
            "normal_documents": len(items) - critical_count,
            "message": (
                "Đã tạo scaffold an toàn cho các hồ sơ còn thiếu. "
                "Cần bổ sung dữ liệu bắt buộc trước khi ghi file chính thức."
            ),
        }

    def _build_document_index(self) -> dict[str, dict[str, Any]]:
        """Lập chỉ mục metadata tài liệu từ bộ quy tắc readiness hiện có."""
        document_index: dict[str, dict[str, Any]] = {}
        for doc_stage, requirements in self._stage_requirements.items():
            for requirement in requirements:
                document_type = str(requirement.get("document_type", "")).strip()
                if not document_type:
                    continue
                document_index[document_type] = {
                    "document_type": document_type,
                    "label": requirement.get("label")
                    or self._humanize_document_type(document_type),
                    "critical": bool(requirement.get("critical", False)),
                    "doc_stage": doc_stage,
                }
        return document_index
