(in-package :opencortex)

(defun think (context)
  (let ((active-skill (find-triggered-skill context)))
    (if active-skill
        (progn
          (kernel-log "PROBABILISTIC ENGINE: Engaging skill '~a'~%" (skill-name active-skill))
          (let* ((prompt-generator (skill-neuro-prompt active-skill)) 
                 (prompt (when prompt-generator (funcall prompt-generator context))))
            (if prompt 
                (let* ((thought (ask-neuro prompt :context context))
                       ;; Improved cleaning: Extract content between ``` blocks if they exist
                       (cleaned-thought 
                        (let ((match (cl-ppcre:scan-to-strings "(?s)```(?:lisp)?\\n?(.*?)\\n?```" thought)))
                          (if match
                              (let ((regs (nth-value 1 (cl-ppcre:scan-to-strings "(?s)```(?:lisp)?\\n?(.*?)\\n?```" thought))))
                                (if (and regs (> (length regs) 0)) (elt regs 0) thought))
                              (string-trim '(#\Space #\Newline #\Tab) thought))))
                       (suggestion (ignore-errors (read-from-string cleaned-thought))))
                  (kernel-log "PROBABILISTIC ENGINE Suggestion: ~a~%" cleaned-thought)
                  (cond
                    ((and suggestion (listp suggestion)) suggestion)
                    ;; SALVAGE: If LLM returned plain text or a non-list symbol
                    ((and (let ((p (getf context :payload))) (eq (getf p :sensor) :chat-message))
                          (> (length cleaned-thought) 0))
                     (kernel-log "PROBABILISTIC ENGINE: SALVAGING plain-text response.~%")
                     (let* ((no-prefix (cl-ppcre:regex-replace "(?i)^(okay,? |sure,? |i will |i've |i have |here is |got it\\.? |understood\\.? |done\\.? |yes,? )+" cleaned-thought "")))
                       `(:target :emacs :payload (:action :insert-at-end :buffer "*opencortex-chat*" :text ,no-prefix))))
                    (t 
                     (kernel-log "PROBABILISTIC ENGINE ERROR: Could not parse response as Lisp plist.~%")
                     nil)))
                nil)))
        nil)))
