(require 'common-lsp)
(require 'util-tree-sitter)

(defun python-backspace (arg)
  "Special handling of python backspace."
  (interactive "*p")
  (if mark-active
      (backward-delete-char-untabify arg)
    (python-indent-dedent-line-backspace arg)
    )
  )

(defun locate-venv-poetry ()
  "Find a poetry venv."
  (run-command-in-directory nil "poetry" "env" "info" "-p")
  )

(defun locate-pyproject-directory ()
  "Adapt lsp-python-ms for poetry."
  (let ((pypoetry-file (locate-dominating-file (buffer-file-name) "pyproject.toml")))
    pypoetry-file
    )
  )


(defun python-fmt ()
  "format python."
  (python-fmt-black)
  (python-fmt-isort)
  )

(defun python-fmt-black ()
  "Run black."
  (run-command-on-buffer "black" "--quiet" "--fast" "-")
  )

(defun python-fmt-isort ()
  "Run isort."
  (run-command-on-buffer "isort" "-")
  )

(defun add-poetry-venv-to-path ()
  "Add the bin folder in the poetry venv to exec-path."
  (let (
        (venv-path (locate-venv-poetry))
        )
    (when venv-path
      (make-local-variable 'exec-path)
      (add-to-list 'exec-path (concat venv-path "/bin"))
      )
    )
  )

(use-package python
  :mode ("\\.py\\'" . python-mode)
  :commands python-mode
  :pin manual
  :hook (
         (python-mode . (lambda ()
                          (when (executable-find "poetry")
                            (add-poetry-venv-to-path)
                            (let ((venv (locate-venv-poetry))) (when venv
                                                                 (setq eglot-workspace-configuration
                                                                       (list (cons ':python (list ':venvPath venv ':pythonPath (concat venv "/bin/python")))))
                                                                 ))
                            )
                          (eglot-ensure)

                          (add-hook 'before-save-hook 'python-fmt nil 'local)
                          (tree-sitter-hl-mode +1)
                          ))
         )
  :bind ((:map python-mode-map ([backspace] . python-backspace))
         )
  )

(provide 'lang-python)