"""模板渲染分发器：按扩展名选择渲染器；文本类使用占位符替换。"""
from __future__ import annotations

from pathlib import Path

from app.core.response import AppError
from app.services.placeholder import render_text
from app.services.renderers import docx, pdf, xlsx

_TEXT_EXTS = {
    ".txt", ".md", ".html", ".htm", ".xml", ".json", ".csv",
    ".yaml", ".yml", ".properties", ".sql", ".ini", ".conf",
}


def render_template(template_path: str | Path, values: dict, output_path: str | Path) -> dict:
    template_path = Path(template_path)
    output_path = Path(output_path)
    ext = template_path.suffix.lower()

    if ext == ".docx":
        return docx.render_docx(template_path, values, output_path)
    if ext in (".xlsx", ".xlsm"):
        return xlsx.render_xlsx(template_path, values, output_path)
    if ext == ".pdf":
        return pdf.render_pdf(template_path, values, output_path)
    if ext in _TEXT_EXTS:
        return _render_text_file(template_path, values, output_path)

    raise AppError(f"暂不支持的模板类型: {ext}")


def _render_text_file(template_path: Path, values: dict, output_path: Path) -> dict:
    text = template_path.read_text(encoding="utf-8")
    res = render_text(text, values)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(res.rendered, encoding="utf-8")
    return {
        "type": "text",
        "output": str(output_path),
        "replacements": res.replacements,
        "unresolved": res.unresolved,
    }
