;;; gptel-org-tools.el --- LLM Tools for org-mode interaction.  -*- lexical-binding: t; -*-

;; Copyright (C) 2025  Phil Bajsicki

;; Author: Phil Bajsicki <phil@bajsicki.com>
;; Keywords: extensions, comm, tools, matching, convenience,
;;
;; Author: Phil Bajsicki <phil@bajsicki.com>
;; Version: 0.0.1
;; Package-Requires: ((emacs "30.1") (gptel 0.9.8) (org-ql 0.9))
;; URL: https://github.com/phil/gptel-org-tools
;; SPDX-License-Identifier: GPL-3.0

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, version 3 of the License.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;; This file is NOT part of GNU Emacs.

;; This file is not part of GNU Emacs.

;;; Commentary:

;;  All documentation regarding these functions is in the README.org file.
;;  Repository: https://git.bajsicki.com/phil/gptel-org-tools

;;; Code:)

(defvar gptel-org-tools '())

(defvar gptel-org-tools-skip-heading-extraction '())

(defun gptel-org-tools--heading ()
  (concat
   (buffer-substring-no-properties
    (line-beginning-position)
    (line-end-position))
   '"\n---\n"))

(defun gptel-org-tools--heading-body ()
    (concat
     (buffer-substring-no-properties
      (line-beginning-position)
      (progn
	(outline-next-heading)
	(line-beginning-position)))
     "---\n"))

(defun gptel-org-tools--heading-subtree ()
    (concat
     (buffer-substring-no-properties
      (line-beginning-position)
      (org-end-of-subtree))
     "---\n"))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function (lambda (arg)
			    (list-buffers-noselect)
			    (with-current-buffer "*Buffer List*"
			     (buffer-string)))
	      :name "list-buffers"
	      :description "Access the list of buffers open in Emacs, including file names and full paths."
	      :args (list '(:name "arg"
			    :type string
			    :description "Does nothing."
			    :optional t))
	      :category "emacs"))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function (lambda (dir)
			  (with-temp-buffer
			    (dired (or dir "~"))
			    (let ((content (buffer-string)))
			      (kill-buffer (current-buffer))
			      content)))
	      :name "dired"
	      :description "List directory contents"
	      :args (list '(:name "dir"
			    :type string
			    :description "Directory path"
			    :optional t))
	      :category "filesystem"))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function (lambda (filename)
			  (concat
			   (bufferp (find-buffer-visiting (expand-file-name filename)))
			   "\n---\nTool execution complete. Proceed with next step."))
	      :name "find-buffer-visiting"
	      :description "Check if the file is open in a buffer. Usage (find-buffer-visiting filename)"
	      :args (list '(:name "filename"
			    :type string
			    :description "The filename to compare to open buffers."))
	      :category "org-mode"))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function (lambda (file)
			   (with-current-buffer (get-buffer-create file)
			     (insert-file-contents file)
			     (concat
			      (current-buffer)
			      "\n---\nTool execution complete. Proceed with next step.")))
	      :name "open-file-inactive"
	      :description "Open the file in a background buffer. This doesn't interfere with the user."
	      :args (list '(:name "file"
			    :type string
			    :description "Path to file.."))
	      :category "filesystem"))

(add-to-list 'gptel-org-tools
             (gptel-make-tool
              :function (lambda (var)
                          (let ((symbol (intern var)))
                            (if (boundp symbol)
				(prin1-to-string (symbol-value symbol))
                              (format "Variable %s is not bound." var))))
              :name "describe-variable"
              :description "See variable contents"
              :args (list '(:name "var"
                            :type string
                            :description "Variable name"))
              :category "emacs"))

(add-to-list 'gptel-org-tools
             (gptel-make-tool
              :function (lambda (fun)
                          (let ((symbol (intern fun)))
                            (if (fboundp symbol)
				(prin1-to-string (documentation symbol 'function))
                              (format "Function %s is not defined." fun))))
              :name "describe-function"
              :description "See function description"
              :args (list '(:name "fun"
                            :type string
                            :description "Function name"
                            :optional t))
              :category "emacs"))

(defun gptel-org-tools--org-extract-tags (buffer)
  (with-current-buffer buffer
    (let ((tags '()))
      (org-map-entries
       (lambda ()
         (let* ((components (org-heading-components))
                (tag-string (car (last components))))
           (when tag-string
             (dolist (tag (split-string tag-string ":" t))
               (push tag tags))))))
      (sort (-uniq tags) #'string<))))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-extract-tags
	      :name "org-extract-tags"
	      :description "Extract all unique tags from an org-mode buffer"
	      :args (list '(:name "buffer"
			    :type string
			    :description "The Org buffer to extract tags from."))
	      :category "org-mode"))

(defun gptel-org-tools--org-extract-headings (buffer)
  (if (member buffer gptel-org-tools-skip-heading-extraction)
      (user-error "Buffer %s has too many headings, use org-extract-tags or org-ql-select-rifle." buffer)
  (with-current-buffer buffer
    (org-map-entries
     #'gptel-org-tools--heading
     t
     'file))))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-extract-headings
	      :name "org-extract-headings"
	      :description "Extract all headings from an org-mode buffer"
	      :args (list '(:name "buffer"
			    :type string
			    :description "The Org buffer to extract headings from."))
	      :category "org-mode"))

(defun gptel-org-tools--org-ql-select-by-date (buf date)
  (org-ql-select
    (get-buffer buf)
    `(heading ,date)
    :action #'gptel-org-tools--heading-subtree))


(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-by-date
	      :name "org-ql-select-by-date"
	      :description "Returns all timestamped headings matching query. Query may be: YYYY, YYYY-MM, YYYY-MM-DD. Prefer using this first when request specifies any time periods. Example: get all headings matching March 2025: \"2025-03\""
	      :args (list '(:name "buffer"
			    :type string
			    :description "Buffer name.")
			  '(:name "date"
			    :type string
			    :description "Date in YYYY or YYYY-MM format."))
	      :category "org"))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function (lambda (days)
			  (with-temp-buffer
			    (org-agenda-list (or days 14))
			    (let ((content (buffer-string)))
			      (kill-buffer (current-buffer))
			      content)))
	      :name "org-agenda-seek"
	      :description "Get user's agenda/ tasking from now to X days in the past or future"
	      :args (list '(:name "days"
			    :type integer
			    :description "Days. Positive = future. Negative = past. Default: 14"))
	      :category "org"))

(defun gptel-org-tools--org-ql-select-headings (buf query)
    (org-ql-select
    (get-buffer buf)
    `(heading ,query)
    :action #''gptel-org-tools--heading))


(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-headings
	      :name "org-ql-select-headings"
	      :description "Retreive matching headings from buffer. Matches only a single string. Using filename fails."
	      :args (list '(:name "buffer"
			    :type string
			    :description "The name of the buffer. See the NAME column in ~emacs-list-buffers~.")
			  '(:name "query"
			    :type string
			    :description "The keyword to match entry headings against."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-headings-rifle (buf query)
    (org-ql-select
      (get-buffer buf)
      `(rifle ,query)
      :action #'gptel-org-tools--heading))


(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-headings-rifle
	      :name "org-ql-select-headings-rifle"
	      :description "Retreive headings from buffer using org-ql-select. Matches against both heading and content. Using filename fails."
	      :args (list '(:name "buffer"
			    :type string
			    :description "The name of the buffer. See the NAME column in ~emacs-list-buffers~.")
			  '(:name "query"
			    :type string
			    :description "The keyword to match entry headings against."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-tags-local (buf query)
    (org-ql-select
    (get-buffer buf)
    `(tags-local ,query)
    :action #'gptel-org-tools-heading-body))


(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-tags-local
	      :name "org-ql-select-tags-local"
	      :description "Run org-ql-select-tags-local against buffer with query. No tag inheritance."
	      :args (list '(:name "buffer"
			    :type string
			    :description "The name of the buffer. See the NAME column in `emacs-list-buffers`. Using filename fails.")
			  '(:name "query"
			    :type string
			    :description "The string match entry tags against."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-tags (buf query)
    (org-ql-select
    (get-buffer buf)
    `(tags ,query)
    :action #'gptel-org-tools--heading-body))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-tags
	      :name "org-ql-select-tags"
	      :description "Run org-ql-select-tags against buffer with query. Supports tag inheritance."
	      :args (list '(:name "buffer"
			    :type string
			    :description "The name of the buffer. See the NAME column in `emacs-list-buffers`. Using filename fails.")
			  '(:name "query"
			    :type string
			    :description "The keyword to match entry headings against."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-rifle (buf query)
    (let ((buffer (get-buffer buf)))
    (if buffer
        (org-ql-select
          buffer
          `(rifle ,query)
          :action #'gptel-org-tools--heading-body)
      (message "Buffer '%s' does not exist." buf))))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-rifle
	      :name "org-ql-select-rifle"
	      :description "Run org-ql-select-rifle against buffer with query."
	      :args (list '(:name "buffer"
			    :type string
			    :description "The name of the buffer. See the NAME column in `emacs-list-buffers`. Using filename fails.")
			  '(:name "query"
			    :type string
			    :description "A single keyword to search for."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-all-tags-local (query)
  (org-ql-select
    (org-agenda-files)
    `(tags-local ,query)
    :action #'gptel-org-tools--heading-body))


(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-all-tags-local
	      :name "org-ql-select-all-tags-local"
	      :description "Run single word query  against all files in (org-agenda-files). WITHOUT tag inheritance, only directly tagged headings."
	      :args (list '(:name "query"
			    :type string
			    :description "A single word to scan for."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-all-tags (query)
  (org-ql-select
    (org-agenda-files)
    `(tags ,query)
    :action #'gptel-org-tools--heading-body))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-all-tags
	      :name "org-ql-select-all-tags"
	      :description "Run single word query  against all files in (org-agenda-files). WITH tag inheritance."
	      :args (list '(:name "query"
			    :type string
			    :description "A single word to scan for."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-all-rifle (query)
  (org-ql-select
    (org-agenda-files)
    `(rifle ,query)
    :action #'gptel-org-tools--heading-body))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-all-rifle
	      :name "org-ql-select-all-rifle"
	      :description "Run single word query against ALL org-mode files (notes)."
	      :args (list '(:name "query"
			    :type string
			    :description "The keyword to match entry headings and content against."))
	      :category "org-ql"))

(defun gptel-org-tools--org-ql-select-all-regexp (query)
  (org-ql-select
    (org-agenda-files)
    `(regexp ,query)
    :action #'gptel-org-tools--heading-body))

(add-to-list 'gptel-org-tools
	     (gptel-make-tool
	      :function #'gptel-org-tools--org-ql-select-all-regexp
	      :name "org-ql-select-all-regexp"
	      :description "Run regexp on ALL files at once."
	      :args (list '(:name "query"
			    :type string
			    :description "Regexp, Emacs Lisp format."))
	      :category "org-ql"))

(provide 'gptel-org-tools)
;;; gptel-org-tools.el ends here