"""Word(.docx) 文档生成服务：关键内容替换 + 可选分类勾选 + 可选转 PDF。"""
from __future__ import annotations

from pathlib import Path

from app.core.response import AppError
from app.services.converter import convert_to_pdf
from app.services.renderers.docx import render_docx
from app.services.renderers.weee import apply_weee_categories


def render_word(
    template_path: str | Path,
    values: dict,
    output_path: str | Path,
    *,
    to_pdf: bool = False,
    categories: dict | None = None,
) -> dict:
    """渲染 Word 模板：替换占位符，可选勾选 WEEE 分类，可选转换为 PDF。

    返回 dict 包含：type / output / replacements / unresolved / pdf_path / pdf_name
    """
    template_path = Path(template_path)
    output_path = Path(output_path)

    if template_path.suffix.lower() != ".docx":
        raise AppError(f"render_word 仅支持 .docx，收到: {template_path.suffix}")

    result = render_docx(template_path, values, output_path)

    if categories:
        apply_weee_categories(output_path, output_path, categories)

    if to_pdf:
        pdf_path = convert_to_pdf(output_path, output_path.with_suffix(".pdf"))
        result["pdf_path"] = str(pdf_path)
        result["pdf_name"] = pdf_path.name
    else:
        result["pdf_path"] = None
        result["pdf_name"] = None

    return result
