import { ConditionalObject } from '../form/types'
import { runPython } from './python'

let initialization: Promise<void> | undefined

async function initialize() {
  const response = await fetch('/pyodide/condition.py')
  if (!response.ok) {
    throw new Error('Failed to fetch python code for conditions')
  }
  const code = await response.text()
  await runPython(code, { global: true })
}

export async function runCondition(operator: ConditionalObject['operator'], left: any, right: any) {
  if (!initialization) initialization = initialize()
  await initialization
  return runPython(`
    op = OPERATIONS.get(operator)
    op(right, left)
  `, { context: { operator, left, right } }) as Promise<boolean>
}
