"""
模板渲染：支持加密 HTML 解密后渲染
"""
import os
from flask import render_template, render_template_string

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def render_html(template_name: str, **context):
    """读取 HTML 模板：若为加密文件则先解密，再渲染。未加密或解密失败时按明文渲染。"""
    path = os.path.join(BASE_DIR, "web_source", template_name)
    if not os.path.isfile(path):
        return render_template(template_name, **context)
    with open(path, "rb") as f:
        raw = f.read()
    try:
        from html_crypto import decrypt
        content = decrypt(raw).decode("utf-8")
    except Exception:
        content = raw.decode("utf-8", errors="replace")
    return render_template_string(content, **context)
