#!/usr/bin/env bash

DEST=${1:-/etc/skel}
LAZY_DEST=${DEST}/.config/nvim/lua/plugins
LAZY_SYNTAX=${DEST}/.config/nvim/after/queries

# Yazi tui filemanager
# For extra configuration options see:
# https://github.com/mikavilpas/yazi.nvim
# https://github.com/mikavilpas/yazi.nvim#%EF%B8%8F%EF%B8%8F-advanced-configuration
conf_print_yazi() {
  cat <<EOF
return {
  ---@type LazySpec
  {
    "mikavilpas/yazi.nvim",
    version = "*", -- use the latest stable version
    event = "VeryLazy",
    dependencies = {
      { "nvim-lua/plenary.nvim", lazy = true },
    },
    keys = {
      -- 👇 in this section, choose your own keymappings!
      {
        "<leader>-",
        mode = { "n", "v" },
        "<cmd>Yazi<cr>",
        desc = "Open yazi at the current file",
      },
      {
        -- Open in the current working directory
        "<leader>cw",
        "<cmd>Yazi cwd<cr>",
        desc = "Open the file manager in nvim's working directory",
      },
      {
        "<c-up>",
        "<cmd>Yazi toggle<cr>",
        desc = "Resume the last yazi session",
      },
    },
    ---@type YaziConfig | {}
    opts = {
      -- if you want to open yazi instead of netrw, see below for more info
      open_for_directories = false,
      keymaps = {
        show_help = "<f1>",
      },
    },
    -- 👇 if you use $(open_for_directories=true), this is recommended
    init = function()
      -- mark netrw as loaded so it's not loaded at all.
      --
      -- More details: https://github.com/mikavilpas/yazi.nvim/issues/802
      vim.g.loaded_netrwPlugin = 1
    end,
  }
}
EOF
}
conf_print_yazi | tee ${LAZY_DEST}/yazi.lua

# Use triple backtick for code blocks rather than tab
# set code-block-style: or MD046: om ~/.markdownlint-cli2.yaml
conf_print_markdownlint_yaml() {
  cat <<EOF
config:
  code-block-style:
    style: "fenced"   
EOF
}
conf_print_markdownlint_yaml | tee ${DEST}/.markdownlint-cli2.yaml

conf_print_markdownlint() {
  cat <<EOF
return {
  {
    "mfussenegger/nvim-lint",
    opts = {
      linters = {
        ["markdownlint-cli2"] = {
          args = { "--config", vim.env.HOME .. "/.markdownlint-cli2.yaml", "--" },
        },
      },
    },
  },
}
EOF
}
conf_print_markdownlint | tee ${LAZY_DEST}/lint.lua

# mise-en-plave
# https://mise.jdx.dev/mise-cookbook/neovim.html
#
config_print_mise_syntax() {
  cat <<EOF
return {
  "nvim-treesitter/nvim-treesitter",
  init = function()
    require("vim.treesitter.query").add_predicate("is-mise?", function(_, _, bufnr, _)
      local filepath = vim.api.nvim_buf_get_name(tonumber(bufnr) or 0)
      local filename = vim.fn.fnamemodify(filepath, ":t")
      return string.match(filename, ".*mise.*%.toml$") ~= nil
    end, { force = true, all = false })
  end,
}
EOF

}
config_print_mise_syntax | tee ${LAZY_DEST}/mise-syntax.lua

# define Tree-sitter query files that extend or customize syntax highlighting and
# code injection for TOML files
mkdir -p ${LAZY_SYNTAX}/toml

# languages using # comments
mkdir -p ${LAZY_SYNTAX}/bash
mkdir -p ${LAZY_SYNTAX}/python

# languages using // comments
mkdir -p ${LAZY_SYNTAX}/go
mkdir -p ${LAZY_SYNTAX}/rust

# Other
mkdir -p ${LAZY_SYNTAX}/markdown
mkdir -p ${LAZY_SYNTAX}/html
mkdir -p ${LAZY_SYNTAX}/yaml

conf_print_toml_injections() {
  cat <<EOF
; extends

(pair
  (bare_key) @key (#eq? @key "run")
  (string) @injection.content @injection.language

  (#is-mise?)
  (#match? @injection.language "^['\"]{3}\n*#!(/\\w+)+/env\\s+\\w+") ; multiline shebang using env
  (#gsub! @injection.language "^.*#!/.*/env%s+([^%s]+).*" "%1") ; extract lang
  (#offset! @injection.content 0 3 0 -3) ; rm quotes
)

(pair
  (bare_key) @key (#eq? @key "run")
  (string) @injection.content @injection.language

  (#is-mise?)
  (#match? @injection.language "^['\"]{3}\n*#!(/\\w+)+\s*\n") ; multiline shebang
  (#gsub! @injection.language "^.*#!/.*/([^/%s]+).*" "%1") ; extract lang
  (#offset! @injection.content 0 3 0 -3) ; rm quotes
)

(pair
  (bare_key) @key (#eq? @key "run")
  (string) @injection.content

  (#is-mise?)
  (#match? @injection.content "^['\"]{3}\n*.*") ; multiline
  (#not-match? @injection.content "^['\"]{3}\n*#!") ; no shebang
  (#offset! @injection.content 0 3 0 -3) ; rm quotes
  (#set! injection.language "bash") ; default to bash
)

(pair
  (bare_key) @key (#eq? @key "run")
  (string) @injection.content

  (#is-mise?)
  (#not-match? @injection.content "^['\"]{3}") ; not multiline
  (#offset! @injection.content 0 1 0 -1) ; rm quotes
  (#set! injection.language "bash") ; default to bash
)
EOF
}
conf_print_toml_injections | tee ${LAZY_SYNTAX}/toml/injections.scm

conf_print_toml_injections() {
  cat <<EOF
; extends

; ============================================================================
; #MISE comments - TOML injection
; ============================================================================
; This injection captures comment lines starting with "#MISE " or "#[MISE]" or
; "# [MISE]" and treats them as TOML code blocks for syntax highlighting.
;
; #MISE format
; The (#offset!) directive skips the "#MISE " prefix (6 characters) from the source
((comment) @injection.content
  (#lua-match? @injection.content "^#MISE ")
  (#offset! @injection.content 0 6 0 1)
  (#set! injection.language "toml"))

; #[MISE] format
((comment) @injection.content
  (#lua-match? @injection.content "^#%[MISE%] ")
  (#offset! @injection.content 0 8 0 1)
  (#set! injection.language "toml"))

; # [MISE] format
((comment) @injection.content
  (#lua-match? @injection.content "^# %[MISE%] ")
  (#offset! @injection.content 0 9 0 1)
  (#set! injection.language "toml"))

; ============================================================================
; #USAGE comments - KDL injection
; ============================================================================
; This injection captures consecutive comment lines starting with "#USAGE " or
; "#[USAGE]" or "# [USAGE]" and treats them as a single KDL code block for
; syntax highlighting.
;
; #USAGE format
((comment) @injection.content
  (#lua-match? @injection.content "^#USAGE ")
  ; Extend the range one byte to the right, to include the trailing newline.
  ; see https://github.com/neovim/neovim/discussions/36669#discussioncomment-15054154
  (#offset! @injection.content 0 7 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))

; #[USAGE] format
((comment) @injection.content
  (#lua-match? @injection.content "^#%[USAGE%] ")
  (#offset! @injection.content 0 9 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))

; # [USAGE] format
((comment) @injection.content
  (#lua-match? @injection.content "^# %[USAGE%] ")
  (#offset! @injection.content 0 10 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))

; NOTE: on neovim >= 0.12, you can use the multi node pattern instead of
; combining injections:
;
; ((comment)+ @injection.content
;   (#lua-match? @injection.content "^#USAGE ")
;   (#offset! @injection.content 0 7 0 1)
;   (#set! injection.language "kdl"))
;
; this is the preferred way as combined injections have multiple
; limitations:
; https://github.com/neovim/neovim/issues/32635
EOF
}
conf_print_bash_injections | tee ${LAZY_SYNTAX}/bash/injections.scm
conf_print_bash_injections | tee ${LAZY_SYNTAX}/python/injections.scm

conf_print_go_injections() {
  cat <<EOF
((comment) @injection.content
  (#lua-match? @injection.content "^//MISE ")
  (#offset! @injection.content 0 7 0 1)
  (#set! injection.language "toml"))
((comment) @injection.content
  (#lua-match? @injection.content "^//%[MISE%] ")
  (#offset! @injection.content 0 9 0 1)
  (#set! injection.language "toml"))
((comment) @injection.content
  (#lua-match? @injection.content "^// %[MISE%] ")
  (#offset! @injection.content 0 10 0 1)
  (#set! injection.language "toml"))
((comment) @injection.content
  (#lua-match? @injection.content "^//USAGE ")
  (#offset! @injection.content 0 8 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))
((comment) @injection.content
  (#lua-match? @injection.content "^//%[USAGE%] ")
  (#offset! @injection.content 0 10 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))
((comment) @injection.content
  (#lua-match? @injection.content "^// %[USAGE%] ")
  (#offset! @injection.content 0 11 0 1)
  (#set! injection.combined)
  (#set! injection.language "kdl"))
EOF
}
conf_print_go_injections | tee ${LAZY_SYNTAX}/go/injections.scm
conf_print_go_injections | tee ${LAZY_SYNTAX}/rust/injections.scm

# To only apply the highlighting on mise files instead of all toml files, the
# is-mise? predicate is used. THe following will consider any toml file
# containing mise in its name as a mise file.
conf_print_predicates() {
  cat <<EOF
return {
  "nvim-treesitter/nvim-treesitter",
  init = function()
    require("vim.treesitter.query").add_predicate("is-mise?", function(_, _, bufnr, _)
      local filepath = vim.api.nvim_buf_get_name(tonumber(bufnr) or 0)
      local filename = vim.fn.fnamemodify(filepath, ":t")
      return string.match(filename, ".*mise.*%.toml$") ~= nil
    end, { force = true, all = false })
  end,
}
  EOF
}
conf_print_predicates() | tee ${LAZYDEST}/mise-treesitter.lua


# otter https://github.com/jmbuhr/otter.nvim
# https://github.com/jmbuhr/LazyVim/blob/main/lua/lazyvim/plugins/extras/lsp/otter.lua
# provides lsp features, including code completion, for code embedded in other documents
conf_print_otter_lsp() {
  cat <<'EOF'
return {
  "jmbuhr/otter.nvim",
  dependencies = {
    "nvim-treesitter/nvim-treesitter",
  },
  config = function()
    vim.api.nvim_create_autocmd({ "FileType" }, {
      pattern = { "toml" },
      group = vim.api.nvim_create_augroup("EmbedToml", {}),
      callback = function()
        require("otter").activate()
      end,
    })
  end,
}
EOF
}
conf_print_otter_lsp | tee ${LAZY_DEST}/otter-lsp.lua

conf_print_otter_lsp() {
  cat <<'EOF'
return {
  "jmbuhr/otter.nvim",
  dependencies = {
    "nvim-treesitter/nvim-treesitter",
  },
  config = function()
    vim.api.nvim_create_autocmd({ "FileType" }, {
      pattern = { "toml" },
      group = vim.api.nvim_create_augroup("EmbedToml", {}),
      callback = function()
        require("otter").activate()
      end,
    })
  end,
}
EOF
}
conf_print_otter_lsp | tee ${LAZY_DEST}/otter-lsp.lua

# Scrollback for kitty terminal
config_print_kitty_scrollback() {
  cat <<EOF
return {
  'mikesmithgh/kitty-scrollback.nvim',
  enabled = true,
  lazy = true,
  cmd = { 'KittyScrollbackGenerateKittens', 'KittyScrollbackCheckHealth', 'KittyScrollbackGenerateCommandLineEditing' },
  event = { 'User KittyScrollbackLaunch' },
  -- version = '*', -- latest stable version, may have breaking changes if major version changed
  -- version = '^6.0.0', -- pin major version, include fixes and features that do not have breaking changes
  config = function()
    require('kitty-scrollback').setup()
  end,
}
EOF
}
config_print_kitty_scrollback | tee ${LAZY_DEST}/kitty-scrollback.lua

# Scrollback for kitty terminal with options
config_print_kitty_scrollback() {
  cat <<EOF
return {
  "mikesmithgh/kitty-scrollback.nvim",
  enabled = true,
  lazy = true,
  cmd = { "KittyScrollbackLoad", "KittyScrollbackReduceBgOpacity" },
  event = { "User KittyScrollbackLaunch" },
  -- recommended to also set opacity reduction on launch
  opts = {
    background_opacity = 0.7,   -- optional: make pager background slightly transparent
    -- other options: see wiki https://github.com/mikesmithgh/kitty-scrollback.nvim/wiki
  },
  config = function(_, opts)
    require('kitty-scrollback').setup(opts)
  end,
}
EOF
}
# config_print_kitty_scrollback | tee ${LAZY_DEST}/kitty-scrollback.lua

# Scrollback for kitty terminal using kitty-scrollback.nvim (2026 recommended style)
config_print_kitty_scrollback() {
  cat <<'EOF'
return {
  'mikesmithgh/kitty-scrollback.nvim',
  enabled = true,
  lazy = true,
  cmd = {
    'KittyScrollbackGenerateKittens',
    'KittyScrollbackCheckHealth',
    'KittyScrollbackGenerateCommandLineEditing',
  },
  event = { 'User KittyScrollbackLaunch' },
  config = function()
    require('kitty-scrollback').setup({

      -- ────────────────────────────────────────────────
      -- Global defaults applied to all configurations
      -- ────────────────────────────────────────────────
      status_window = {
        enabled = true,
        style_simple = false,          -- use nice Nerd Font icons
        autoclose = true,              -- auto close after loaded
        show_timer = true,             -- shows loading time (great for debugging slow startups)
        icons = {
          kitty  = '󰄛',               -- or  /  etc.
          heart  = '󰣐',
          nvim   = '',
        },
      },

      paste_window = {
        filetype = nil,                -- auto-detect shell (bash/zsh/fish)
        hide_footer = false,
        yank_register = '',            -- default register
        yank_register_enabled = true,
        winblend = 0,                  -- no transparency (clean look)
      },

      -- Useful callbacks & extras
      callbacks = {
        after_ready = nil,             -- can be overridden per config
      },

      -- ────────────────────────────────────────────────
      -- Named configurations you can call with --config <name>
      -- ────────────────────────────────────────────────

      -- Default (what you get with just kitty_scrollback_nvim)
      default = {},

      -- Opens scrollback and immediately starts backward search (?)
      search = {
        callbacks = {
          after_ready = function()
            vim.api.nvim_feedkeys('?', 'n', false)
          end,
        },
      },

      -- Only shows the last command output (very clean for quick checks)
      last_cmd = {
        kitty_get_text = {
          extent = 'last_non_empty_output',   -- or 'output' / 'screen'
        },
        status_window = {
          enabled = false,   -- cleaner without status if only last cmd
        },
      },

    })
  end,
}
EOF
}
config_print_kitty_scrollback | tee "${LAZY_DEST}/kitty-scrollback.lua"

# PlatformIO wrapper for neovim written lua.
# conf_print_platformio() {
#   cat <<EOF
#   return {
#     "anurag3301/nvim-platformio.lua",
#     dependencies = {
#         { "akinsho/nvim-toggleterm.lua" },
#         { "nvim-telescope/telescope.nvim" },
#         { "nvim-lua/plenary.nvim" },
#     },
# }
# EOF
# }
# conf_print_platformio | tee ${LAZY_DEST}/platformio.lua
