import os
from typing import Optional
from ..core.config import settings


def _read_template_bytes(template_path: str) -> Optional[bytes]:
    """读取模板文件（明文 .docx）"""
    full_path = os.path.join(settings.TEMPLATE_BASE_DIR, template_path)
    if os.path.exists(full_path):
        with open(full_path, "rb") as f:
            return f.read()
    return None


async def render_template(template_path: str, context: dict) -> Optional[bytes]:
    try:
        from docxtpl import DocxTemplate
        import io

        content = _read_template_bytes(template_path)
        if not content:
            return None

        doc = DocxTemplate(io.BytesIO(content))
        doc.render(context)

        buffer = io.BytesIO()
        doc.save(buffer)
        buffer.seek(0)
        return buffer.read()
    except ImportError:
        return None
    except Exception:
        return None
