;;; eca-chat-context.el --- ECA chat context and completion -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Eric Dallo
;;
;; SPDX-License-Identifier: Apache-2.0
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;;  Context management, completion-at-point, cursor tracking, and
;;  media/image handling for ECA chat.
;;
;;; Code:

(require 'f)
(require 'eca-util)
(require 'eca-api)
(require 'eca-chat-expandable)

;; Forward declarations for eca-chat.el core
(defvar eca-chat-mode-map)
(defvar eca-chat--id)
(defvar eca-chat-window-width)
(declare-function eca-chat--insert "eca-chat")
(declare-function eca-chat--prompt-field-start-point "eca-chat")
(declare-function eca-chat--refine-context "eca-chat")
(declare-function eca-chat--prompt-context-field-ov "eca-chat")
(declare-function eca-chat--point-at-new-context-p "eca-chat")
(declare-function eca-chat--point-at-prompt-field-p "eca-chat")
(declare-function eca-chat--new-context-start-point "eca-chat")
(declare-function eca-chat--select-window "eca-chat")
(declare-function eca-chat--get-last-buffer "eca-chat")
(declare-function eca-chat--insert-prompt "eca-chat")
(declare-function eca-chat--relativize-filename-for-workspace-root "eca-chat")
(declare-function eca-chat--task-find-by-id "eca-chat")

;;;; Customization

(defcustom eca-chat-auto-add-repomap nil
  "Whether to auto include repoMap context when opening eca."
  :type 'boolean
  :group 'eca)

(defcustom eca-chat-auto-add-cursor t
  "Whether to auto track cursor opened files/position and add them to context."
  :type 'boolean
  :group 'eca)

(defcustom eca-chat-cursor-context-debounce 0.3
  "Seconds to debounce updates when tracking cursor to context."
  :type 'number
  :group 'eca)

(defcustom eca-chat-context-prefix "@"
  "The context prefix string used in eca chat buffer."
  :type 'string
  :group 'eca)

(defcustom eca-chat-filepath-prefix "#"
  "The filepath prefix string used in eca chat buffer."
  :type 'string
  :group 'eca)

(defcustom eca-chat-yank-image-context-location 'user
  "Where to paste images from clipboard."
  :type '(choice (const :tag "System context area" system)
                 (const :tag "user context area" user))
  :group 'eca)

(defcustom eca-chat-context-buffer-predicate #'eca-chat-context-buffer-include-p
  "Predicate deciding if a buffer can be offered as text context.
Called with a buffer, should return non-nil to offer it in the
`@' completion and DWIM context commands."
  :type 'function
  :group 'eca)

(defcustom eca-chat-context-buffer-max-chars 100000
  "Max chars of buffer content sent as text context, keeping its tail.
When nil, send the whole buffer content."
  :type '(choice (const :tag "No limit" nil) integer)
  :group 'eca)

;;;; Faces

(defface eca-chat-context-unlinked-face
  '((((background dark))  (:foreground "gold" :height 0.9))
    (((background light)) (:foreground "dark goldenrod" :height 0.9)))
  "Face for contexts to be added."
  :group 'eca)

(defface eca-chat-context-file-face
  '((((background dark))  (:foreground "coral" :underline t :height 0.9))
    (((background light)) (:foreground "firebrick" :underline t :height 0.9)))
  "Face for contexts of file type."
  :group 'eca)

(defface eca-chat-context-repo-map-face
  '((((background dark))  (:foreground "turquoise" :underline t :height 0.9))
    (((background light)) (:foreground "dark cyan" :underline t :height 0.9)))
  "Face for contexts of repoMap type."
  :group 'eca)

(defface eca-chat-context-mcp-resource-face
  '((((background dark))  (:foreground "lime green" :underline t :height 0.9))
    (((background light)) (:foreground "dark green" :underline t :height 0.9)))
  "Face for contexts of mcpResource type."
  :group 'eca)

(defface eca-chat-context-cursor-face
  '((((background dark))  (:foreground "gainsboro" :underline t :height 0.9))
    (((background light)) (:foreground "dim gray" :underline t :height 0.9)))
  "Face for contexts of cursor type."
  :group 'eca)

(defface eca-chat-context-buffer-face
  '((((background dark))  (:foreground "orchid" :underline t :height 0.9))
    (((background light)) (:foreground "dark magenta" :underline t :height 0.9)))
  "Face for contexts of text (buffer) type."
  :group 'eca)

;;;; Variables

(defvar-local eca-chat--context-completion-cache nil)
(defvar-local eca-chat--file-completion-cache nil)
(defvar-local eca-chat--command-completion-cache nil)
(defvar-local eca-chat--context '())
(defvar-local eca-chat--cursor-context nil)

;; Timer used to debounce post-command driven context updates
(defvar eca-chat--cursor-context-timer nil)

;;;; Constants

(defconst eca-chat--kind->symbol
  '(("file" . file)
    ("directory" . folder)
    ("repoMap" . module)
    ("cursor" . class)
    ("mcpPrompt" . function)
    ("mcpResource" . file)
    ("text" . text)
    ("native" . variable)
    ("custom-prompt" . method)))

(defconst eca-chat-media--mime-extension-map
  '(("image/png" . "png")
    ("image/x-png" . "png")
    ("image/jpeg" . "jpg")
    ("image/jpg" . "jpg")
    ("image/gif" . "gif")
    ("image/webp" . "webp")
    ("image/heic" . "heic")
    ("image/heif" . "heif")
    ("image/svg+xml" . "svg"))
  "Mapping of mime types to screenshot file extensions.")

;;;; Context functions

(defun eca-chat--context-presentable-path (filename)
  "Return the presentable string for FILENAME."
  (or (when (-first (lambda (root) (f-ancestor-of? root filename))
                    (eca--session-workspace-folders (eca-session)))
        (f-filename filename))
      filename))

(defun eca-chat-context-buffer-include-p (buffer)
  "Return non-nil when BUFFER can be offered as a text context.
Excludes file-visiting, hidden, minibuffer and ECA own buffers."
  (let ((name (buffer-name buffer)))
    (and (buffer-live-p buffer)
         (not (buffer-file-name buffer))
         (not (minibufferp buffer))
         (not (string-prefix-p " " name))
         (not (string-match-p "\\`\\(\\*eca\\|<eca-\\)" name)))))

(defun eca-chat--buffer-context (buffer &optional lines-range)
  "Return the text context plist for BUFFER.
When LINES-RANGE is non-nil, a (:start N :end M) plist, restrict
the context to those lines of BUFFER."
  (append (list :type "text" :label (buffer-name buffer))
          (when lines-range (list :linesRange lines-range))))

(defvar eca-chat--buffer-list-tick 0
  "Counter bumped whenever the buffer list changes.")

(defvar eca-chat--buffer-contexts-cache nil
  "Cons of (TICK . CONTEXTS) caching eligible buffer contexts.")

(defvar eca-chat--buffer-completion-items-cache nil
  "Cons of (TICK . ITEMS) caching buffer completion items.")

(defun eca-chat--buffer-list-changed ()
  "Invalidate buffer context caches after a buffer list update."
  (setq eca-chat--buffer-list-tick (1+ eca-chat--buffer-list-tick)))

(add-hook 'buffer-list-update-hook #'eca-chat--buffer-list-changed)

(defun eca-chat--all-buffer-contexts ()
  "Return text contexts for all eligible buffers.
Recomputed only when the buffer list changes."
  (let ((tick eca-chat--buffer-list-tick))
    (unless (and eca-chat--buffer-contexts-cache
                 (eq (car eca-chat--buffer-contexts-cache) tick))
      (setq eca-chat--buffer-contexts-cache
            (cons tick
                  (->> (buffer-list)
                       (-filter (lambda (buffer)
                                  (funcall eca-chat-context-buffer-predicate buffer)))
                       (-map #'eca-chat--buffer-context)))))
    (cdr eca-chat--buffer-contexts-cache)))

(defun eca-chat--buffer-contexts ()
  "Return text contexts for eligible buffers not already added."
  (-remove (lambda (context) (member context eca-chat--context))
           (eca-chat--all-buffer-contexts)))

(defun eca-chat--buffer-context-content (buffer &optional lines-range)
  "Return BUFFER text limited to `eca-chat-context-buffer-max-chars'.
When LINES-RANGE is non-nil, a (:start N :end M) plist, restrict
to those lines first, resolved against the live buffer state.
When over the limit the tail is kept, where recent output lives."
  (with-current-buffer buffer
    (save-restriction
      (widen)
      (-let* (((&plist :start start-line :end end-line) lines-range)
              (region-start (if start-line
                                (save-excursion
                                  (goto-char (point-min))
                                  (forward-line (1- start-line))
                                  (point))
                              (point-min)))
              (region-end (if end-line
                              (save-excursion
                                (goto-char (point-min))
                                (forward-line (1- end-line))
                                (line-end-position))
                            (point-max)))
              (max-chars eca-chat-context-buffer-max-chars)
              (start (if (and max-chars (> (- region-end region-start) max-chars))
                         (- region-end max-chars)
                       region-start)))
        (buffer-substring-no-properties start region-end)))))

(defun eca-chat--materialize-context (context)
  "Return CONTEXT filled with content needed right before sending.
Text contexts get fresh buffer content by label, sliced to their
lines range when present (the range is resolved client-side and
not sent); contexts of killed buffers return nil so callers can
drop them.  Cursor contexts with no tracked position return nil
too."
  (pcase (plist-get context :type)
    ("text" (let* ((label (plist-get context :label))
                   (buffer (get-buffer label)))
              (if (buffer-live-p buffer)
                  (list :type "text"
                        :label label
                        :content (eca-chat--buffer-context-content
                                  buffer (plist-get context :linesRange)))
                (progn (eca-info "Skipping killed buffer context: %s" label)
                       nil))))
    ("cursor" (when (plist-get context :position)
                context))
    (_ context)))

(defun eca-chat--context->str (context &optional static?)
  "Convert CONTEXT to a presentable str in buffer.
If STATIC? return strs with no dynamic values."
  (-let* (((&plist :type type) context)
          (context-str
           (pcase type
             ("file" (let ((path (plist-get context :path))
                           (lines-range (plist-get context :linesRange)))
                       (propertize (concat eca-chat-context-prefix
                                           (eca-chat--context-presentable-path path)
                                           (-when-let ((&plist :start start :end end) lines-range)
                                             (format "(%d-%d)" start end)))
                                   'eca-chat-expanded-item-str (concat eca-chat-context-prefix path
                                                                       (-when-let ((&plist :start start :end end) lines-range)
                                                                         (format ":L%d-L%d" start end)))
                                   'font-lock-face 'eca-chat-context-file-face)))
             ("directory" (propertize (concat eca-chat-context-prefix (eca-chat--context-presentable-path (plist-get context :path)))
                                      'eca-chat-expanded-item-str (concat eca-chat-context-prefix (plist-get context :path))
                                      'font-lock-face 'eca-chat-context-file-face))
             ("repoMap" (propertize (concat eca-chat-context-prefix "repoMap")
                                    'eca-chat-expanded-item-str (concat eca-chat-context-prefix "repoMap")
                                    'font-lock-face 'eca-chat-context-repo-map-face))
             ("mcpResource" (propertize (concat eca-chat-context-prefix (plist-get context :server) ":" (plist-get context :name))
                                        'eca-chat-expanded-item-str (concat eca-chat-context-prefix (plist-get context :server) ":" (plist-get context :name))
                                        'font-lock-face 'eca-chat-context-mcp-resource-face))
             ("cursor" (propertize (cond
                                    (static? (concat eca-chat-context-prefix "cursor"))
                                    ((not eca-chat--cursor-context)
                                     (concat eca-chat-context-prefix "cursor" "(no file)"))
                                    (t (concat eca-chat-context-prefix "cursor"
                                               "("
                                               (-some-> (plist-get eca-chat--cursor-context :path)
                                                 (f-filename))
                                               " "
                                               (-some->>
                                                   (-> eca-chat--cursor-context
                                                       (plist-get :position)
                                                       (plist-get :start)
                                                       (plist-get :line))
                                                 (funcall #'number-to-string))
                                               ":"
                                               (-some->>
                                                   (-> eca-chat--cursor-context
                                                       (plist-get :position)
                                                       (plist-get :start)
                                                       (plist-get :character))
                                                 (funcall #'number-to-string))
                                               ")")))
                                   'eca-chat-expanded-item-str (concat eca-chat-context-prefix "cursor")
                                   'font-lock-face 'eca-chat-context-cursor-face))
             ("text" (let ((label (plist-get context :label))
                           (lines-range (plist-get context :linesRange)))
                       (propertize (concat eca-chat-context-prefix
                                           label
                                           (-when-let ((&plist :start start :end end) lines-range)
                                             (format "(%d-%d)" start end)))
                                   'eca-chat-expanded-item-str (concat eca-chat-context-prefix label
                                                                       (-when-let ((&plist :start start :end end) lines-range)
                                                                         (format ":L%d-L%d" start end)))
                                   'font-lock-face 'eca-chat-context-buffer-face)))
             (_ (concat eca-chat-context-prefix "unknown:" type)))))
    (propertize context-str
                'eca-chat-item-type 'context
                'eca-chat-item-str-length (length context-str)
                'eca-chat-context-item context)))

(defun eca-chat--filepath->str (filepath lines-range)
  "Convert FILEPATH and LINES-RANGE to a presentable str in buffer."
  (let* ((item-str (concat eca-chat-filepath-prefix
                           (eca-chat--context-presentable-path filepath)
                           (-when-let ((&plist :start start :end end) lines-range)
                             (format "(%d-%d)" start end)))))
    (propertize item-str
                'eca-chat-item-type 'filepath
                'eca-chat-item-str-length (length item-str)
                'eca-chat-expanded-item-str (concat eca-chat-filepath-prefix
                                                    filepath
                                                    (-when-let ((&plist :start start :end end) lines-range)
                                                      (format ":L%d-L%d" start end)))
                'font-lock-face 'eca-chat-context-file-face)))

(defun eca-chat--refresh-context ()
  "Refresh chat context."
  (save-excursion
    (-some-> (eca-chat--prompt-context-field-ov)
      (overlay-start)
      (goto-char))
    (delete-region (point) (line-end-position))
    (seq-doseq (context eca-chat--context)
      (eca-chat--insert (eca-chat--context->str context))
      (eca-chat--insert " "))
    (eca-chat--insert (propertize eca-chat-context-prefix 'font-lock-face 'eca-chat-context-unlinked-face))))

(defun eca-chat--add-context (context)
  "Add to chat CONTEXT."
  (add-to-list 'eca-chat--context context t)
  (eca-chat--refresh-context))

(defun eca-chat--remove-context (context)
  "Remove from chat CONTEXT."
  (setq eca-chat--context (remove context eca-chat--context))
  (eca-chat--refresh-context))

;;;; Cursor tracking

(defun eca-chat--cur-position ()
  "Return the start and end positions for current point.
Resteps a cons cell (START . END) where START and END are cons cells
of (LINE . CHARACTER) representing the current selection or cursor position."
  (save-excursion
    (let* ((start-pos (if (use-region-p) (region-beginning) (point)))
           (end-pos (if (use-region-p) (region-end) (point)))
           (start-line (line-number-at-pos start-pos t))
           (start-char (1+ (progn
                             (goto-char start-pos)
                             (current-column))))
           (end-line (line-number-at-pos end-pos t))
           (end-char (1+ (progn
                           (goto-char end-pos)
                           (current-column)))))
      (cons (cons start-line start-char)
            (cons end-line end-char)))))

(defun eca-chat--get-last-visited-buffer ()
  "Return the last visited file buffer inside a session workspace.
More recent file buffers outside any session workspace root are
skipped so the cursor context keeps pointing to workspace files."
  (-first (lambda (buff)
            (when (buffer-live-p buff)
              (-some-> (buffer-file-name buff)
                (eca-chat--session-for-path))))
          (buffer-list)))

(defun eca-chat--session-for-path (path)
  "Return the session whose workspace folders contain PATH, or nil.
Pure in-memory lookup over existing sessions, unlike `eca-session'
which may probe project.el and shell out to git, so it is cheap
enough for timers running in arbitrary buffers."
  (-first (lambda (session)
            (--any? (and it (f-ancestor-of? it path))
                    (eca--session-workspace-folders session)))
          (eca-vals eca--sessions)))

(defun eca-chat--track-cursor (&rest _args)
  "Change chat context considering current open file and point."
  (when-let* ((buffer (eca-chat--get-last-visited-buffer))
              (path (buffer-file-name buffer))
              (session (eca-chat--session-for-path path)))
    (with-current-buffer buffer
      (when-let (chat-buffer (eca-chat--get-last-buffer session))
        (when (buffer-live-p chat-buffer)
          (-let* (((start . end) (eca-chat--cur-position))
                  ((start-line . start-character) start)
                  ((end-line . end-character) end))
            (eca-chat--with-current-buffer chat-buffer
              (let ((new-context (list :path path
                                       :position (list :start (list :line start-line :character start-character)
                                                       :end (list :line end-line :character end-character)))))
                (when (not (eca-plist-equal eca-chat--cursor-context new-context))
                  (setq eca-chat--cursor-context new-context)
                  (eca-chat--refresh-context))))))))))

(defun eca-chat--track-cursor-position-schedule ()
  "Debounce `eca-chat--track-cursor' via an idle timer."
  (unless eca-chat--cursor-context-timer
    (setq eca-chat--cursor-context-timer
          (run-with-idle-timer eca-chat-cursor-context-debounce t
                               #'eca-chat--track-cursor))))

;;;; Media/yank functions

(defun eca-chat-media--extension-for-type (type)
  "Return file extension (without dot) for mime TYPE.
TYPE can be a string or symbol."
  (let* ((type-str (if (symbolp type) (symbol-name type) type))
         (clean (and type-str (string-trim type-str))))
    (or (cdr (assoc-string clean eca-chat-media--mime-extension-map t))
        (when clean
          (let* ((parts (split-string clean "/"))
                 (raw-subtype (cadr parts))
                 (subtype (car (split-string (or raw-subtype "") "\\+"))))
            (unless (string-empty-p subtype)
              subtype)))
        "png")))

(defun eca-chat-media--save-clipboard-image (type data)
  "Write clipboard image DATA of mime TYPE to a temp file.
Returns the path to the written file, or nil (after reporting the
failure via `eca-error') when writing fails.  Shared by the eca
chat buffer and the compose buffer clipboard-paste handlers."
  (let* ((extension (eca-chat-media--extension-for-type type))
         (output-path (make-temp-file "eca-screenshot-" nil (concat "." extension))))
    (condition-case err
        (progn
          (let ((coding-system-for-write 'no-conversion))
            (write-region data nil output-path nil 'silent))
          (and (f-exists? output-path) output-path))
      (error
       (eca-error "Failed to save yanked image: %s" (error-message-string err))
       nil))))

(defun eca-chat--yank-image-handler (type data)
  "Handler for `yank-media' to insert images from clipboard.
TYPE is the MIME type (e.g., image/png).
DATA is the binary image data as a string."
  (when-let* ((session (eca-session))
              (chat-buffer (eca-chat--get-last-buffer session))
              (output-path (eca-chat-media--save-clipboard-image type data)))
    (eca-chat--with-current-buffer chat-buffer
      (let ((context (list :type "file" :path output-path))
            (file-size (file-size-human-readable (file-attribute-size (file-attributes output-path)))))
        (eca-chat--select-window)
        (if (eq 'system eca-chat-yank-image-context-location)
            (eca-chat--add-context context)
          (progn
            (eca-chat--insert-prompt (concat (eca-chat--context->str context 'static) " "))
            (goto-char (+ (point) (+ 2 (length output-path))))))
        (eca-info "Image added, size: %s" file-size)))))

(defun eca-chat--clipboard-image-p ()
  "Return non-nil when an image is available on the clipboard."
  (when-let* ((targets (and (display-graphic-p)
                            (gui-get-selection 'CLIPBOARD 'TARGETS))))
    (seq-some (lambda (type)
                (and (symbolp type)
                     (string-match-p "^image/" (symbol-name type))))
              (if (vectorp targets) (append targets nil) targets))))

(defun eca-chat--yank-considering-image (orig-fun &rest args)
  "Around advice for paste commands to use `yank-media' for images.
Call ORIG-FUN with ARGS if not media."
  (if (and (derived-mode-p 'eca-chat-mode)
           (fboundp 'yank-media)
           (boundp 'yank-media--registered-handlers)
           yank-media--registered-handlers
           (eca-chat--clipboard-image-p))
      (call-interactively #'yank-media)
    (apply orig-fun args)))

;;;; DWIM / query functions

(defun eca-chat--find-typed-query (prefix)
  "Return the text typed after the last item after PREFIX (@ or #).
For example: `@foo @bar @baz` => `baz`. If nothing is typed, resteps an empty
string."
  (when (eca-chat--point-at-new-context-p)
    (save-excursion
      (goto-char (eca-chat--new-context-start-point))
      (end-of-line)))
  (save-excursion
    (let* ((start (line-beginning-position))
           (end (point))
           (last-prefix-pos (search-backward prefix start t)))
      (if last-prefix-pos
          (string-trim (buffer-substring-no-properties (+ last-prefix-pos (length prefix)) end))
        ""))))

(defun eca-chat--resolve-path-token (token)
  "Resolve TOKEN to an existing absolute path, else nil.
TOKEN may be absolute, start with ~, or be relative to one of
the session workspace roots (including ./ and ../ tokens)."
  (when (and token (not (string-empty-p token)))
    (if (file-name-absolute-p token)
        (let ((expanded (directory-file-name (expand-file-name token))))
          (when (f-exists? expanded) expanded))
      (-some (lambda (root)
               (let ((expanded (directory-file-name (expand-file-name token root))))
                 (when (f-exists? expanded) expanded)))
             (eca--session-workspace-folders (eca-session))))))

(defun eca-chat--raw-prompt-contexts ()
  "Return contexts for raw @path tokens typed in the prompt field.
Only workspace-relative tokens are considered: absolute, ~ and
dot prefixed mentions are already parsed by the server from the
message text, and tokens already linked to a context chip are
skipped."
  (when-let ((prompt-start (eca-chat--prompt-field-start-point)))
    (let ((contexts '())
          (regexp (concat "\\(?:^\\|[^[:alnum:]]\\)"
                          (regexp-quote eca-chat-context-prefix)
                          "\\([^[:space:]]+\\)")))
      (save-excursion
        (goto-char prompt-start)
        (while (re-search-forward regexp nil t)
          (let ((token (match-string-no-properties 1)))
            (unless (or (get-text-property (match-beginning 1) 'eca-chat-context-item)
                        (file-name-absolute-p token)
                        (string-prefix-p "." token))
              (when-let ((path (eca-chat--resolve-path-token token)))
                (let ((context (list :type (if (f-dir? path) "directory" "file")
                                     :path path)))
                  (unless (member context contexts)
                    (push context contexts))))))))
      (nreverse contexts))))

(defun eca-chat--maybe-finalize-context-token ()
  "Turn a raw @path or #path token before point into a proper item.
Meant to be called right after a space was inserted.  Does
nothing when the previous word does not resolve to an existing
file or directory."
  (let* ((end (1- (point)))
         (start (save-excursion
                  (goto-char end)
                  (if (re-search-backward "[[:space:]]" (line-beginning-position) t)
                      (1+ (point))
                    (line-beginning-position)))))
    (when (< start end)
      (let ((word (buffer-substring-no-properties start end)))
        (when (and (> (length word) 1)
                   (or (string-prefix-p eca-chat-context-prefix word)
                       (string-prefix-p eca-chat-filepath-prefix word))
                   (not (get-text-property start 'eca-chat-item-type)))
          (when-let ((path (eca-chat--resolve-path-token (substring word 1))))
            (let ((context? (string-prefix-p eca-chat-context-prefix word)))
              (cond
               ;; On the context line: add to the context list; the
               ;; refresh wipes the typed text.
               ((and context? (eca-chat--point-at-new-context-p))
                (eca-chat--add-context
                 (list :type (if (f-dir? path) "directory" "file")
                       :path path)))
               ;; In the prompt: replace the raw token with an item.
               ((eca-chat--point-at-prompt-field-p)
                (let ((item-str (if context?
                                    (eca-chat--context->str
                                     (list :type (if (f-dir? path) "directory" "file")
                                           :path path)
                                     'static)
                                  (eca-chat--filepath->str path nil))))
                  (delete-region start (point))
                  (eca-chat--insert item-str)
                  (eca-chat--insert " ")))))))))))

(defun eca-chat--post-self-insert ()
  "Finalize raw context tokens after inserting a space."
  (when (eq last-command-event ?\s)
    (eca-chat--maybe-finalize-context-token)))

(declare-function dired-get-marked-files "dired")
(declare-function treemacs-node-at-point "treemacs")
(declare-function treemacs-button-get "treemacs")

(defun eca-chat--region-lines-range ()
  "Return the active region as a lines range plist (:start N :end M).
Lines are absolute (1-based, ignoring narrowing) since consumers
resolve them against the whole file or buffer.  A region ending at
the beginning of a line (whole-lines selection) does not include
that line."
  (let* ((rb (region-beginning))
         (re (region-end))
         (re (if (and (> re rb)
                      (save-excursion (goto-char re) (bolp)))
                 (1- re)
               re)))
    (list :start (line-number-at-pos rb t)
          :end (line-number-at-pos re t))))

(defun eca-chat--get-contexts-dwim ()
  "Get contexts in a DWIM manner."
  (cond
   ((and (buffer-file-name)
         (use-region-p))
    (list
     (list :type "file"
           :path (buffer-file-name)
           :linesRange (eca-chat--region-lines-range))))

   ((derived-mode-p 'dired-mode)
    (--map (list :type (if (f-dir? it) "directory" "file")
                 :path it)
           (dired-get-marked-files)))

   ((derived-mode-p 'treemacs-mode)
    (when-let (path (-some-> (treemacs-node-at-point)
                      (treemacs-button-get :path)))
      (list
       (list :type (if (f-dir? path) "directory" "file")
             :path path))))

   ((buffer-file-name)
    (list
     (list :type "file" :path (buffer-file-name))))

   ;; Explicit selection in a non-file buffer (magit, vterm, the
   ;; chat itself, ...): intentional, so no predicate check.
   ((use-region-p)
    (list (eca-chat--buffer-context (current-buffer)
                                    (eca-chat--region-lines-range))))

   ((funcall eca-chat-context-buffer-predicate (current-buffer))
    (list (eca-chat--buffer-context (current-buffer))))))

;;;; Completion functions

(defun eca-chat--completion-item-kind (item)
  "Return the kind for ITEM."
  (alist-get (plist-get item :type)
             eca-chat--kind->symbol
             nil
             nil
             #'string=))

(defun eca-chat--completion-item-label-kind (item-label)
  "Return the kind for ITEM-LABEL."
  (eca-chat--completion-item-kind (get-text-property 0 'eca-chat-completion-item item-label)))

(defun eca-chat--completion-item-company-box-icon (item-label)
  "Return the kind for ITEM-LABEL."
  (let ((symbol (eca-chat--completion-item-label-kind item-label)))
    (intern (capitalize (symbol-name symbol)))))

(defun eca-chat--completion-context-annotate (roots item-label)
  "Annonate ITEM-LABEL detail for ROOTS."
  (-let (((&plist :type type :path path :description description) (get-text-property 0 'eca-chat-completion-item item-label)))
    (pcase type
      ("file" (eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename))
      ("directory" (eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename))
      ("repoMap" "Summary view of workspaces files")
      ("cursor" "Current cursor file + position")
      ("mcpResource" description)
      ("text" "Buffer content")
      (_ ""))))

(defun eca-chat--completion-file-annotate (roots item-label)
  "Annonate ITEM-LABEL detail for ROOTS."
  (-let (((&plist :path path) (get-text-property 0 'eca-chat-completion-item item-label)))
    (eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename)))

(defun eca-chat--completion-prompts-annotate (item-label)
  "Annotate prompt ITEM-LABEL."
  (-let (((&plist :description description :arguments args)
          (get-text-property 0 'eca-chat-completion-item item-label)))
    (concat "(" (string-join (--map (plist-get it :name) args) ", ")
            ") "
            (when description
              (truncate-string-to-width description (* 100 eca-chat-window-width))))))

(defvar eca-chat--completion-retrigger-timer nil)

(defun eca-chat--completion-retrigger ()
  "Schedule a new completion session at point.
Used after completing a directory so the user can keep
completing its contents without retyping the trigger."
  (when (timerp eca-chat--completion-retrigger-timer)
    (cancel-timer eca-chat--completion-retrigger-timer))
  (let ((buffer (current-buffer)))
    (setq eca-chat--completion-retrigger-timer
          (run-at-time
           0 nil
           (lambda ()
             (setq eca-chat--completion-retrigger-timer nil)
             (when (and (buffer-live-p buffer)
                        (eq buffer (window-buffer (selected-window))))
               (with-current-buffer buffer
                 (cond
                  ((and (bound-and-true-p company-mode)
                        (fboundp 'company-manual-begin))
                   (company-manual-begin))
                  (t (completion-at-point))))))))))

(defun eca-chat--completion-drill-in (prefix)
  "Keep completing after PREFIX instead of finalizing the item.
Strips the completion text properties from the just inserted
directory text and re-triggers completion so the user can drill
into the directory contents."
  (let ((start-pos (save-excursion
                     (search-backward prefix (line-beginning-position) t))))
    (when start-pos
      (remove-text-properties (+ start-pos (length prefix)) (point)
                              '(eca-chat-completion-item nil face nil))))
  (eca-chat--completion-retrigger))

(defun eca-chat--completion-item-directory-p (item)
  "Return non-nil when completion ITEM points to a directory."
  (string= "directory"
           (plist-get (get-text-property 0 'eca-chat-completion-item item)
                      :type)))

(defun eca-chat--completion-context-from-new-context-exit-function (item _status)
  "Add to context the selected ITEM.
Directories are not finalized: completion keeps going inside
them; typing a space adds the directory itself as context."
  (if (eca-chat--completion-item-directory-p item)
      (eca-chat--completion-drill-in eca-chat-context-prefix)
    (eca-chat--add-context (get-text-property 0 'eca-chat-completion-item item))
    (end-of-line)))

(defun eca-chat--completion-context-from-prompt-exit-function (item _status)
  "Add to context the selected ITEM.
Add text property to prompt text to match context.  Directories
are not finalized: completion keeps going inside them; typing a
space turns the directory into a context."
  (if (eca-chat--completion-item-directory-p item)
      (eca-chat--completion-drill-in eca-chat-context-prefix)
    (let ((context (get-text-property 0 'eca-chat-completion-item item)))
      (let ((start-pos (save-excursion
                         (search-backward eca-chat-context-prefix (line-beginning-position) t)))
            (end-pos (point)))
        (delete-region start-pos end-pos)
        (eca-chat--insert (eca-chat--context->str context 'static))))
    (eca-chat--insert " ")))

(defun eca-chat--completion-file-from-prompt-exit-function (item _status)
  "Add to files the selected ITEM.
Directories are not finalized: completion keeps going inside
them; typing a space turns the directory into a filepath."
  (if (eca-chat--completion-item-directory-p item)
      (eca-chat--completion-drill-in eca-chat-filepath-prefix)
    (let* ((file (get-text-property 0 'eca-chat-completion-item item))
           (start-pos (save-excursion
                        (search-backward eca-chat-filepath-prefix (line-beginning-position) t)))
           (end-pos (point)))
      (delete-region start-pos end-pos)
      (eca-chat--insert (eca-chat--filepath->str (plist-get file :path) nil)))
    (eca-chat--insert " ")))

(defun eca-chat--completion-prompt-exit-function (item _status)
  "Finish prompt completion for ITEM."
  (-let* (((&plist :arguments arguments) (get-text-property 0 'eca-chat-completion-item item)))
    (when (> (length arguments) 0)
      (seq-doseq (arg arguments)
        (-let (((&plist :name name :description description :required required) arg))
          (eca-chat--insert " ")
          (let* ((desc-part (if (and description (not (string-empty-p description)))
                                (format "\nDescription: %s" description)
                              ""))
                 (value-suffix (if required "" " (leave blank for default)"))
                 (prompt (format "Arg: %s%s\nValue%s: " name desc-part value-suffix))
                 (arg-text (read-string prompt)))
            (if (and arg-text (string-match-p " " arg-text))
                (eca-chat--insert (format "\"%s\"" arg-text))
              (eca-chat--insert arg-text)))))
      (end-of-line))))

(defun eca-chat--completion-path-label (query roots path directory?)
  "Return the completion label for PATH given typed QUERY and ROOTS.
Keeps the directory part the user typed as the label prefix so
the probe keeps matching while drilling into folders, falling
back to a workspace-relative path.  Appends a trailing slash
when DIRECTORY? is non-nil."
  (let* ((qdir (file-name-directory query))
         (label
          (or
           ;; Keep what the user typed as prefix (handles ~, ./, ../,
           ;; absolute and workspace-relative directory parts).
           (when qdir
             (-some (lambda (base)
                      (let ((resolved (file-name-as-directory
                                       (expand-file-name qdir base))))
                        (when (string-prefix-p resolved path)
                          (concat qdir (substring path (length resolved))))))
                    (if (file-name-absolute-p qdir) (list nil) roots)))
           ;; Fallback: relativize to a workspace root.
           (-some (lambda (root)
                    (when (f-ancestor-of? root path)
                      (f-relative path root)))
                  roots)
           path)))
    (if directory? (file-name-as-directory label) label)))

(defun eca-chat--context-to-completion (query roots context)
  "Convert CONTEXT to a completion item for typed QUERY and ROOTS."
  (let* ((ctx-type (plist-get context :type))
         (ctx-path (plist-get context :path))
         (raw-label (pcase ctx-type
                      ("file" (eca-chat--completion-path-label query roots ctx-path nil))
                      ("directory" (eca-chat--completion-path-label query roots ctx-path t))
                      ("repoMap" "repoMap")
                      ("cursor" "cursor")
                      ("mcpResource" (concat (plist-get context :server) ":" (plist-get context :name)))
                      ("text" (plist-get context :label))
                      (_ (concat "Unknown - " ctx-type))))
         (face (pcase ctx-type
                 ("file" 'eca-chat-context-file-face)
                 ("directory" 'eca-chat-context-file-face)
                 ("repoMap" 'eca-chat-context-repo-map-face)
                 ("cursor" 'eca-chat-context-cursor-face)
                 ("mcpResource" 'eca-chat-context-mcp-resource-face)
                 ("text" 'eca-chat-context-buffer-face)
                 (_ nil))))
    (propertize raw-label
                'eca-chat-completion-item context
                'face face)))

(defun eca-chat--buffer-completion-items ()
  "Return completion items for eligible buffers not already added.
Items are recomputed only when the buffer list changes; the
already-added filter always runs against the live context list."
  (let ((tick eca-chat--buffer-list-tick))
    (unless (and eca-chat--buffer-completion-items-cache
                 (eq (car eca-chat--buffer-completion-items-cache) tick))
      (setq eca-chat--buffer-completion-items-cache
            (cons tick
                  (-map (lambda (context)
                          (eca-chat--context-to-completion nil nil context))
                        (eca-chat--all-buffer-contexts)))))
    (let ((items (cdr eca-chat--buffer-completion-items-cache))
          (added-text-contexts (-filter (lambda (context)
                                          (equal "text" (plist-get context :type)))
                                        eca-chat--context)))
      (if added-text-contexts
          (-remove (lambda (item)
                     (member (get-text-property 0 'eca-chat-completion-item item)
                             added-text-contexts))
                   items)
        items))))

(defun eca-chat--file-to-completion (query roots file)
  "Convert FILE to a completion item for typed QUERY and ROOTS."
  (propertize (eca-chat--completion-path-label
               query roots
               (plist-get file :path)
               (string= "directory" (plist-get file :type)))
              'eca-chat-completion-item file
              'face 'eca-chat-context-file-face))

(defun eca-chat--command-to-completion (command)
  "Convert COMMAND to a completion item."
  (propertize (plist-get command :name)
              'eca-chat-completion-item command))

;;;; Eldoc function

(defun eca-chat-eldoc-function (cb &rest _ignored)
  "Eldoc function to show details of context and prompt in eldoc.
Calls CB with the resulting message."
  (cond
   ;; Task eldoc: show description and blocked-by
   ((when-let* ((task (get-text-property (point) 'eca-chat-task)))
      (let* ((subject (plist-get task :subject))
             (description (plist-get task :description))
             (blocked-by (append (plist-get task :blockedBy) nil))
             (blocked-subjects
              (when blocked-by
                (mapcar (lambda (id)
                          (if-let* ((tk (eca-chat--task-find-by-id id)))
                              (plist-get tk :subject)
                            (format "#%s" id)))
                        blocked-by)))
             (doc (concat
                   (propertize subject 'face 'bold)
                   (when description
                     (concat "\n" description))
                   (when blocked-subjects
                     (concat "\n"
                             (propertize "Blocked by: " 'face 'font-lock-keyword-face)
                             (string-join blocked-subjects ", "))))))
        (funcall cb doc)
        t)))
   ;; Context/filepath eldoc
   ((when-let ((item-type (get-text-property (point) 'eca-chat-item-type)))
      (when-let ((item-str (get-text-property (point) 'eca-chat-expanded-item-str)))
        (when-let ((face (get-text-property (point) 'font-lock-face)))
          (funcall cb (format "%s: %s"
                              (pcase item-type
                                ('context "Context")
                                ('filepath "Filepath"))
                              (propertize item-str 'face face)))
          t))))))

;;;; Completion-at-point function

(defun eca-chat--completion-type-at-point ()
  "Return the kind of completion available at point, or nil."
  (let ((full-text (buffer-substring-no-properties (line-beginning-position) (point))))
    (cond
     ;; completing contexts
     ((eca-chat--point-at-new-context-p)
      'contexts-from-new-context)

     ((when-let (last-word (car (last (string-split full-text "[\s]"))))
        (string-match-p (concat "\\(?:^\\|[^[:alnum:]]\\)" (regexp-quote eca-chat-context-prefix)) last-word))
      'contexts-from-prompt)

     ((when-let (last-word (car (last (string-split full-text "[\s]"))))
        (string-match-p (concat "\\(?:^\\|[^[:alnum:]]\\)" (regexp-quote eca-chat-filepath-prefix)) last-word))
      'files-from-prompt)

     ;; completing commands with `/`
     ((and (eca-chat--point-at-prompt-field-p)
           (string-prefix-p "/" full-text))
      'prompts)

     (t nil))))

(defun eca-chat--completion-prefix-end (prefix)
  "Return the position right after the last PREFIX before point.
Searches only in the current line; return nil when PREFIX is not
found."
  (save-excursion
    (when (search-backward prefix (line-beginning-position) t)
      (+ (point) (length prefix)))))

(defconst eca-chat--completion-cache-max-size 100
  "Max cached queries per completion cache before it is reset.")

(defun eca-chat--completion-cached-items (cache-var query fetch-fn key to-item-fn)
  "Return completion items for QUERY, caching them in CACHE-VAR.
CACHE-VAR is a buffer-local hash table variable, created on
demand.  On cache miss call FETCH-FN; when it returns a response
plist, convert each element of its KEY list with TO-ITEM-FN and
cache the result.  Interrupted requests (nil response) are not
cached so they are retried on the next keystroke."
  (let* ((cache (or (symbol-value cache-var)
                    (set cache-var (make-hash-table :test 'equal))))
         (cached (gethash query cache :eca-chat--miss)))
    (if (not (eq cached :eca-chat--miss))
        cached
      (when-let ((resp (funcall fetch-fn)))
        (let ((items (-map to-item-fn (append (plist-get resp key) nil))))
          (when (> (hash-table-count cache) eca-chat--completion-cache-max-size)
            (clrhash cache))
          (puthash query items cache)
          items)))))

(defun eca-chat-completion-at-point ()
  "Complete at point in the chat."
  (when-let ((type (eca-chat--completion-type-at-point)))
    (let* ((bounds-start (pcase type
                           ('prompts (1+ (line-beginning-position)))
                           ('files-from-prompt (or (eca-chat--completion-prefix-end eca-chat-filepath-prefix)
                                                   (point)))
                           (_ (or (eca-chat--completion-prefix-end eca-chat-context-prefix)
                                  (point)))))
           (candidates-fn (lambda ()
                            (eca-api-catch 'input
                                (eca-api-while-no-input
                                  (pcase type
                                    ((or 'contexts-from-prompt
                                         'contexts-from-new-context)
                                     (let* ((query (eca-chat--find-typed-query eca-chat-context-prefix))
                                            (roots (eca--session-workspace-folders (eca-session)))
                                            (server-items (eca-chat--completion-cached-items
                                                           'eca-chat--context-completion-cache query
                                                           (lambda ()
                                                             (eca-api-request-while-no-input
                                                              (eca-session)
                                                              :method "chat/queryContext"
                                                              :params (list :chatId eca-chat--id
                                                                            :query query
                                                                            :contexts (vconcat (mapcar #'eca-chat--refine-context
                                                                                                       eca-chat--context)))))
                                                           :contexts
                                                           (lambda (context)
                                                             (eca-chat--context-to-completion query roots context))))
                                            (buffer-items (eca-chat--buffer-completion-items)))
                                       (append server-items buffer-items)))

                                    ('files-from-prompt
                                     (let ((query (eca-chat--find-typed-query eca-chat-filepath-prefix))
                                           (roots (eca--session-workspace-folders (eca-session))))
                                       (eca-chat--completion-cached-items
                                        'eca-chat--file-completion-cache query
                                        (lambda ()
                                          (eca-api-request-while-no-input
                                           (eca-session)
                                           :method "chat/queryFiles"
                                           :params (list :chatId eca-chat--id
                                                         :query query)))
                                        :files
                                        (lambda (file)
                                          (eca-chat--file-to-completion query roots file)))))

                                    ('prompts
                                     (let ((query (buffer-substring-no-properties
                                                   (1+ (line-beginning-position)) (point))))
                                       (eca-chat--completion-cached-items
                                        'eca-chat--command-completion-cache query
                                        (lambda ()
                                          (eca-api-request-while-no-input
                                           (eca-session)
                                           :method "chat/queryCommands"
                                           :params (list :chatId eca-chat--id
                                                         :query query)))
                                        :commands
                                        #'eca-chat--command-to-completion)))

                                    (_ nil)))
                              (:interrupted nil)
                              (`,res res))))
           (exit-fn (pcase type
                      ('contexts-from-new-context #'eca-chat--completion-context-from-new-context-exit-function)
                      ('contexts-from-prompt #'eca-chat--completion-context-from-prompt-exit-function)
                      ('files-from-prompt #'eca-chat--completion-file-from-prompt-exit-function)
                      ('prompts #'eca-chat--completion-prompt-exit-function)
                      (_ nil)))
           (annotation-fn (pcase type
                            ((or 'contexts-from-prompt
                                 'contexts-from-new-context) (-partial #'eca-chat--completion-context-annotate (eca--session-workspace-folders (eca-session))))
                            ('files-from-prompt (-partial #'eca-chat--completion-file-annotate (eca--session-workspace-folders (eca-session))))
                            ('prompts #'eca-chat--completion-prompts-annotate))))
      (list
       bounds-start
       (point)
       (lambda (probe pred action)
         (cond
          ((eq action 'metadata)
           '(metadata (category . eca-capf)
                      (display-sort-function . identity)
                      (cycle-sort-function . identity)))
          ((eq (car-safe action) 'boundaries) nil)
          (t
           (complete-with-action action (funcall candidates-fn) probe pred))))
       :company-kind #'eca-chat--completion-item-label-kind
       :company-require-match 'never
       :annotation-function annotation-fn
       :exit-function exit-fn))))

(provide 'eca-chat-context)
;;; eca-chat-context.el ends here
