//! Core render helper: resolves a template from the environment and renders it.

use minijinja::{Environment, Value};

use crate::error::RenderError;

/// Render `template_name` with `ctx`, returning HTML or a safe error string.
///
/// On error, logs via `tracing::error` and returns a minimal error paragraph
/// so the shell always has something to display rather than panicking.
pub fn render_safe(env: &Environment, template_name: &str, ctx: Value) -> String {
    match render(env, template_name, ctx) {
        Ok(html) => html,
        Err(e) => {
            tracing::error!(template = template_name, error = %e, "template render failed");
            format!(
                r#"<p class="ds-text-error p-4">Render error: {}</p>"#,
                html_escape::encode_text(&e.to_string())
            )
        }
    }
}

pub fn render(env: &Environment, template_name: &str, ctx: Value) -> Result<String, RenderError> {
    let tmpl = env
        .get_template(template_name)
        .map_err(|_| RenderError::TemplateNotFound(template_name.to_string()))?;
    Ok(tmpl.render(ctx)?)
}
