import { runPython } from './python'

let initialization: Promise<void> | undefined

async function initialize() {
  const response = await fetch('/pyodide/jinja.py')
  if (!response.ok) {
    throw new Error('Failed to fetch python code for jinja expressions')
  }
  const code = await response.text()
  await runPython(`
    import micropip
    await micropip.install('jinja2')
    await micropip.install('jinja2_strcase')
  `, { global: true })
  await runPython(code, { global: true })
}

export async function runJinja(expression: string, context: Record<string, any> = {}) {
  if (!initialization) initialization = initialize()
  await initialization
  return runPython(`
    jinja_template = jinja_env.from_string(expression)
    jinja_template.render(context)
  `, { context: { context, expression } })
}
