(in-package :opencortex)

(defun ask-neuro (prompt &key (system-prompt "You are the Probabilistic Engine engine of a Neurosymbolic Lisp Machine.") (cascade nil) (context nil))
  (let ((backends (cond
                    ((listp cascade) cascade)
                    ((functionp cascade) (funcall cascade context))
                    ((functionp *provider-cascade*) (funcall *provider-cascade* context))
                    (t *provider-cascade*))))
    (dolist (backend backends)
      (let ((backend-fn (gethash backend *neuro-backends*)))
        (when backend-fn
          (kernel-log "PROBABILISTIC ENGINE: Attempting backend ~a..." backend)
          (let* ((model (ignore-errors 
                         (uiop:symbol-call :opencortex.skills.org-skill-economist :economist-get-model-for-provider backend)))
                 (result (if model 
                             (funcall backend-fn prompt system-prompt :model model)
                             (funcall backend-fn prompt system-prompt))))
            (kernel-log "PROBABILISTIC ENGINE: Backend ~a returned: ~a" backend (if (stringp result) (subseq result 0 (min 50 (length result))) result))
            (if (and (stringp result) (search ":LOG" result) (or (search "Failure" result) (search "missing" result)))
                (kernel-log "PROBABILISTIC ENGINE: Backend ~a failed. Falling back..." backend)
                (return-from ask-neuro result))))))
    "(:type :LOG :payload (:text \"Neural Cascade Failure\"))"))
