(in-package :opencortex)

(defun execute-openrouter-request (prompt system-prompt &key model)
  (let ((api-key (uiop:getenv "OPENROUTER_API_KEY"))
        (endpoint "https://openrouter.ai/api/v1/chat/completions")
        (model-id (or model "google/gemini-2.0-flash-001")))
    (unless api-key (return-from execute-openrouter-request "(:type :LOG :payload (:text \"OpenRouter API Key missing\"))"))
    (kernel-log "OPENROUTER DEBUG - Using Model: ~a" model-id)
    (let* ((headers `(("Content-Type" . "application/json")
                      ("Authorization" . ,(format nil "Bearer ~a" api-key))
                      ("HTTP-Referer" . "https://github.com/amr/opencortex")))
           (body (cl-json:encode-json-to-string
                  `((model . ,model-id)
                    (messages . (( (role . "system") (content . ,system-prompt) )
                                 ( (role . "user") (content . ,prompt) )))))))
      (handler-case (let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30)))
                      (let ((json (cl-json:decode-json-from-string response)))
                        (cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json)))))))))
        (error (c) (format nil "(:type :LOG :payload (:text \"OpenRouter Failure: ~a\"))" c))))))
