;;; $DOOMDIR/config.el -*- lexical-binding: t; -*-

;; Place your private configuration here! Remember, you do not need to run 'doom
;; sync' after modifying this file!


;; Some functionality uses this to identify you, e.g. GPG configuration, email
;; clients, file templates and snippets. It is optional.
;; (setq user-full-name "John Doe"
;;       user-mail-address "john@doe.com")

;; Doom exposes five (optional) variables for controlling fonts in Doom:
;;
;; - `doom-font' -- the primary font to use
;; - `doom-variable-pitch-font' -- a non-monospace font (where applicable)
;; - `doom-big-font' -- used for `doom-big-font-mode'; use this for
;;   presentations or streaming.
;; - `doom-symbol-font' -- for symbols
;; - `doom-serif-font' -- for the `fixed-pitch-serif' face
;;
;; See 'C-h v doom-font' for documentation and more examples of what they
;; accept. For example:
;;
;;(setq doom-font (font-spec :family "Fira Code" :size 12 :weight 'semi-light)
;;      doom-variable-pitch-font (font-spec :family "Fira Sans" :size 13))
;;
;; If you or Emacs can't find your font, use 'M-x describe-font' to look them
;; up, `M-x eval-region' to execute elisp code, and 'M-x doom/reload-font' to
;; refresh your font settings. If Emacs still can't find your font, it likely
;; wasn't installed correctly. Font issues are rarely Doom issues!
(setq doom-font (font-spec :family "Fira Code" :size 16))

;; Auto-install nerd-icons fonts if they're missing
(defun my/ensure-nerd-icons-fonts ()
  "Check if nerd-icons fonts are installed and install them if missing."
  (when (display-graphic-p)
    (unless (find-font (font-spec :name "Symbols Nerd Font Mono"))
      (when (fboundp 'nerd-icons-install-fonts)
        (nerd-icons-install-fonts t)))))

(add-hook 'doom-init-ui-hook #'my/ensure-nerd-icons-fonts)

;; There are two ways to load a theme. Both assume the theme is installed and
;; available. You can either set `doom-theme' or manually load a theme with the
;; `load-theme' function. This is the default:
(setq doom-theme 'doom-tokyo-night)

;; This determines the style of line numbers in effect. If set to `nil', line
;; numbers are disabled. For relative line numbers, set this to `relative'.
(setq display-line-numbers-type t)

;; If you use `org' and don't want your org files in the default location below,
;; change `org-directory'. It must be set before org loads!
(setq org-directory "~/org/")
(after! org
  (setq org-agenda-span 'week
        org-agenda-start-with-log-mode t
        my-agenda-dirs '("projects" "roam")
        org-agenda-files (cons org-directory (mapcan (lambda (x) (directory-files-recursively
                                                                  (expand-file-name x org-directory)
                                                                  "\.org$"))
                                                     my-agenda-dirs))
        org-log-done 'time
        org-agenda-custom-commands '(("n" "Agenda"
                                      ((agenda "")
                                       (tags-todo "-someday-recurring")))
                                     ("s" "Someday Items"
                                      ((tags-todo "+someday"))))
        org-todo-keywords '((sequence "TODO(t)" "IN-PROGRESS(p)" "WAIT(w)" "|" "DONE(d)" "KILL(k)"))
        org-journal-file-type 'weekly
        org-journal-file-format "%Y-%m-%d.org"
        org-capture-templates
          '(("t" "Todo" entry (file+headline "~/org/todo.org" "Inbox")
             "* TODO %? \n %i \n%a" :prepend t)))
  ;; Make blocked tasks more visible in agenda (they have subtasks to do!)
  (custom-set-faces!
    '(org-agenda-dimmed-todo-face :foreground "#bb9af7" :weight normal)))

(map! :after org-agenda
      :map org-agenda-mode-map
      :localleader
      (:prefix ("v" . "view")
       "d" #'org-agenda-day-view
       "w" #'org-agenda-week-view))

;; (use-package! org-caldav
;;   :defer t
;;   :config
;;   (setq org-caldav-url "https://nextcloud.johnogle.info/remote.php/dav/calendars/johno"
;;         org-caldav-calendar-id "personal"
;;         org-icalendar-timezone "America/Los_Angeles"
;;         org-caldav-inbox "~/org/calendar.org"
;;         org-caldav-files nil
;;         org-caldav-sync-direction 'cal->org))

(defun my/get-rbw-password (alias)
  "Return the password for ALIAS via rbw, unlocking the vault only if needed."
  (let* ((cmd     (format "rbw get %s 2>&1" alias))
         (output  (shell-command-to-string cmd)))
    (string-trim output)))

(after! gptel
  :config
  (setq! gptel-api-key (my/get-rbw-password "openai-api-key-chatgpt-el")
         gptel-default-mode 'org-mode
         gptel-use-tools t
         gptel-confirm-tool-calls 'always
         gptel-include-reasoning 'ignore
         gptel-model "qwen3:30b")

  ;; Set default backend to be Ollama-Local
  (setq! gptel-backend
         (gptel-make-ollama "Ollama-Local"
           :host "localhost:11434"
           :stream t
           :models '(deepseek-r1 deepseek-r1-fullctx qwen3:30b qwen3:4b llama3.1 qwen2.5-coder mistral-nemo gpt-oss)))

  ;; Define custom tools
  (gptel-make-tool
   :name "run_shell_command"
   :description "Execute shell commands and return output. Use this to run system commands, check file contents, or perform system operations."
   :function (lambda (command)
               (condition-case err
                   (shell-command-to-string command)
                 (error (format "Error running command: %s" (error-message-string err)))))
   :args (list '(:name "command" :type "string" :description "Shell command to execute")))

  (gptel-make-tool
   :name "read_file"
   :description "Read the contents of a file and return as text"
   :function (lambda (filepath)
               (condition-case err
                   (with-temp-buffer
                     (insert-file-contents (expand-file-name filepath))
                     (buffer-string))
                 (error (format "Error reading file %s: %s" filepath (error-message-string err)))))
   :args (list '(:name "filepath" :type "string" :description "Path to the file to read")))

  (gptel-make-tool
   :name "list_directory"
   :description "List contents of a directory"
   :function (lambda (dirpath)
               (condition-case err
                   (mapconcat 'identity 
                              (directory-files (expand-file-name dirpath) nil "^[^.]")
                              "\n")
                 (error (format "Error listing directory %s: %s" dirpath (error-message-string err)))))
   :args (list '(:name "dirpath" :type "string" :description "Directory path to list"))))

(use-package! claude-code-ide
  :commands (claude-code-ide-menu claude-code-ide-open-here)
  :init
  (map! :leader
        (:prefix ("o" . "open")
         :desc "Claude Code IDE" "c" #'claude-code-ide-menu))
  :config
  (claude-code-ide-emacs-tools-setup)
  (setq claude-code-ide-cli-path "claude"
        claude-code-ide-cli-extra-flags "--dangerously-skip-permissions"
        claude-code-ide-focus-claude-after-ediff t
        claude-code-ide-focus-on-open t
        claude-code-ide-show-claude-window-in-ediff t
        claude-code-ide-switch-tab-on-ediff t
        claude-code-ide-use-ide-diff t
        claude-code-ide-use-side-window t
        claude-code-ide-window-height 20
        claude-code-ide-window-side 'right
        claude-code-ide-window-width 90))

(after! gptel
  (require 'gptel-tool-library)
  (setq gptel-tool-library-use-maybe-safe t
        gptel-tool-library-use-unsafe t)
  (dolist (module '("bbdb" "buffer" "elisp" "emacs" "gnus" "os" "search-and-replace" "url"))
    (gptel-tool-library-load-module module)))

;; mu4e email configuration
;; Add NixOS mu4e to load-path (installed via mu.mu4e package)
(when-let ((mu-path (executable-find "mu")))
  (add-to-list 'load-path
               (expand-file-name "../share/emacs/site-lisp/mu4e"
                                 (file-name-directory mu-path))))

(after! mu4e
  ;; User identity
  (setq user-mail-address "john@ogle.fyi"
        user-full-name "John Ogle")

  ;; Maildir location (no account prefix - single account)
  (setq mu4e-maildir "~/Mail"
        mu4e-attachment-dir "~/Downloads")

  ;; Folder config (matches ~/Mail/INBOX, ~/Mail/Sent, etc.)
  (setq mu4e-sent-folder "/Sent"
        mu4e-drafts-folder "/Drafts"
        mu4e-trash-folder "/Trash"
        mu4e-refile-folder "/Archive")

  ;; Shortcuts for common folders
  (setq mu4e-maildir-shortcuts
        '((:maildir "/INBOX"   :key ?i)
          (:maildir "/Archive" :key ?a)
          (:maildir "/Sent"    :key ?s)
          (:maildir "/Trash"   :key ?t)))

  ;; Behavior settings
  (setq mu4e-get-mail-command "mbsync -a"
        mu4e-update-interval 300  ; 5 minutes (matches systemd timer)
        mu4e-change-filenames-when-moving t  ; required for mbsync
        mu4e-headers-date-format "%Y-%m-%d"
        mu4e-headers-time-format "%H:%M")

  ;; Sending mail via msmtp
  (setq message-send-mail-function 'message-send-mail-with-sendmail
        sendmail-program (executable-find "msmtp")
        message-sendmail-envelope-from 'header
        mail-envelope-from 'header
        mail-specify-envelope-from t))

;; Whenever you reconfigure a package, make sure to wrap your config in an
;; `after!' block, otherwise Doom's defaults may override your settings. E.g.
;;
;;   (after! PACKAGE
;;     (setq x y))
;;
;; The exceptions to this rule:
;;
;;   - Setting file/directory variables (like `org-directory')
;;   - Setting variables which explicitly tell you to set them before their
;;     package is loaded (see 'C-h v VARIABLE' to look up their documentation).
;;   - Setting doom variables (which start with 'doom-' or '+').
;;
;; Here are some additional functions/macros that will help you configure Doom.
;;
;; - `load!' for loading external *.el files relative to this one
;; - `use-package!' for configuring packages
;; - `after!' for running code after a package has loaded
;; - `add-load-path!' for adding directories to the `load-path', relative to
;;   this file. Emacs searches the `load-path' when you load packages with
;;   `require' or `use-package'.
;; - `map!' for binding new keys
;;
;; To get information about any of these functions/macros, move the cursor over
;; the highlighted symbol at press 'K' (non-evil users must press 'C-c c k').
;; This will open documentation for it, including demos of how they are used.
;; Alternatively, use `C-h o' to look up a symbol (functions, variables, faces,
;; etc).
;;
;; You can also try 'gd' (or 'C-c c d') to jump to their definition and see how
;; they are implemented.
