------------------------------------------------------
------------------- Custom Settings ------------------
------------------------------------------------------
vim.api.nvim_create_autocmd("FileType", {
	pattern = "go",
	callback = function()
		vim.bo.textwidth = 120
	end,
})

require('render-markdown').setup({
	completions = { lsp = { enabled = true } },
	file_types = { 'markdown', 'codecompanion' },
	html = {
		-- CodeCompanion Markdown Tweaks
		tag = {
			file = { icon = '󰨸 ', highlight = 'Normal' },
			buf = { icon = '󰂥 ', highlight = 'Normal' },
		},
	},
})

------------------------------------------------------
---------------------- LSP Lines ---------------------
------------------------------------------------------
require("lsp_lines").setup()
vim.diagnostic.config({
	virtual_text = false,
	virtual_lines = true,
})

------------------------------------------------------
-------------------- Built-in LSP --------------------
------------------------------------------------------
local nix_vars = require("nix-vars")

local augroup = vim.api.nvim_create_augroup("LspFormatting", { clear = false })
local on_attach = function(client, bufnr)
	if client:supports_method("textDocument/formatting") then
		vim.api.nvim_clear_autocmds({ group = augroup, buffer = bufnr })
		vim.api.nvim_create_autocmd("BufWritePre", {
			group = augroup,
			buffer = bufnr,
			callback = function()
				vim.lsp.buf.format({ async = false, timeout_ms = 2000 })
			end,
		})
	end

	-- Create KeyMaps
	local bufopts = { noremap = true, silent = true, buffer = bufnr }
	vim.keymap.set("n", "K", vim.lsp.buf.hover, vim.tbl_extend("force", { desc = 'Hover documentation' }, bufopts))
	vim.keymap.set("n", "<C-k>", vim.lsp.buf.signature_help,
		vim.tbl_extend("force", { desc = "Show signature help" }, bufopts))
	vim.keymap.set("n", "<leader>lD", vim.lsp.buf.declaration,
		vim.tbl_extend("force", { desc = "Go to declaration" }, bufopts))
	vim.keymap.set("n", "<leader>ld", vim.lsp.buf.definition,
		vim.tbl_extend("force", { desc = "Go to definition" }, bufopts))
	vim.keymap.set("n", "<leader>li", vim.lsp.buf.implementation,
		vim.tbl_extend("force", { desc = "Go to implementation" }, bufopts))
	vim.keymap.set("n", "<leader>ln", vim.lsp.buf.rename, vim.tbl_extend("force", { desc = "Rename symbol" }, bufopts))
	vim.keymap.set("n", "<leader>lr", vim.lsp.buf.references,
		vim.tbl_extend("force", { desc = "Show references" }, bufopts))
	vim.keymap.set("n", "<leader>lt", vim.lsp.buf.type_definition,
		vim.tbl_extend("force", { desc = "Go to type definition" }, bufopts))
	vim.keymap.set("n", "<leader>lf", function()
		vim.lsp.buf.format({ async = true, timeout_ms = 2000 })
	end, vim.tbl_extend("force", { desc = "Format file" }, bufopts))
end

local on_attach_no_formatting = function(client, bufnr)
	-- Disable Formatting
	client.server_capabilities.documentFormattingProvider = false
	client.server_capabilities.documentRangeFormattingProvider = false
	on_attach(client, bufnr)
end

local organize_go_imports = function()
	local encoding = vim.lsp.util._get_offset_encoding()
	local params = vim.lsp.util.make_range_params(nil, encoding)
	params.context = { only = { "source.organizeImports" } }

	local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, 3000)
	for _, res in pairs(result or {}) do
		for _, r in pairs(res.result or {}) do
			if r.edit then
				vim.lsp.util.apply_workspace_edit(r.edit, encoding)
			else
				vim.lsp.buf.execute_command(r.command)
			end
		end
	end
end

local default_config = {
	flags = { debounce_text_changes = 150 },
	capabilities = require("cmp_nvim_lsp").default_capabilities(),
	on_attach = on_attach,
}

local setup_lsp = function(name, config, opts)
	opts = opts or {}
	local final_config = vim.tbl_deep_extend("force", default_config, config or {})

	vim.lsp.config(name, final_config)

	-- Manual Mode - Register a buffer-local command instead of auto-enabling.
	-- The command name is derived from opts.cmd_name or the LSP name.
	if opts.manual then
		local cmd_name = opts.cmd_name or name:gsub("^%l", string.upper):gsub("_%l", function(s)
			return s:sub(2):upper()
		end)
		local fts = final_config.filetypes or {}
		vim.api.nvim_create_autocmd("FileType", {
			pattern = fts,
			callback = function(ev)
				vim.api.nvim_buf_create_user_command(ev.buf, cmd_name, function()
					vim.lsp.enable(name)
				end, { desc = "Enable " .. name .. " LSP" })
			end,
		})
		return
	end

	vim.lsp.enable(name)
end

-- Python LSP Configuration
setup_lsp("pyright", {
	filetypes = { "starlark", "python" },
})

-- HTML LSP Configuration
setup_lsp("html", {
	on_attach = on_attach_no_formatting,
	cmd = { nix_vars.vscls .. "/bin/vscode-html-language-server", "--stdio" },
	filetypes = { "htm", "html" },
})

-- JSON LSP Configuration
setup_lsp("jsonls", {
	on_attach = on_attach_no_formatting,
	cmd = { nix_vars.vscls .. "/bin/vscode-html-language-server", "--stdio" },
	filetypes = { "json", "jsonc", "jsonl" },
})

-- CSS LSP Configuration
setup_lsp("cssls", {
	on_attach = on_attach_no_formatting,
	cmd = { nix_vars.vscls .. "/bin/vscode-html-language-server", "--stdio" },
	filetypes = { "css" },
})

-- Typescript / Javascript LSP Configuration
setup_lsp("ts_ls", {
	on_attach = on_attach_no_formatting,
	cmd = { nix_vars.tsls, "--stdio" },
	filetypes = { "typescript", "typescriptreact", "javascript" },
})

-- Oxlint - Prefer a project-local oxlint from node_modules so the LSP
-- version matches the project's pinned dependency; fall back to PATH.
setup_lsp("oxlint", {
	on_attach = on_attach_no_formatting,
	root_markers = { ".oxlintrc.json", "oxlint.config.json", "package.json", ".git" },
	cmd = function(dispatchers, config)
		local bin = "oxlint"
		if config.root_dir then
			local local_bin = config.root_dir .. "/node_modules/.bin/oxlint"
			if vim.fn.executable(local_bin) == 1 then
				bin = local_bin
			end
		end
		return vim.lsp.rpc.start({ bin, "--lsp" }, dispatchers, {
			cwd = config.root_dir,
		})
	end,
})

-- C LSP Configuration
setup_lsp("clangd", {
	cmd = { nix_vars.clangd },
	filetypes = { "c", "cpp", "objc", "objcpp", "cuda" },
})

-- Lua LSP Configuration
setup_lsp("lua_ls", {
	cmd = { nix_vars.luals },
	filetypes = { "lua" },
})

-- Unison LSP Configuration
setup_lsp("unison")

-- SQL Configuration
-- NOTE: root_markers resolves root_dir but Neovim does NOT use root_dir as
-- the process cwd (cmd_cwd defaults to Neovim's cwd). We use cmd as a
-- function so we can read root_dir from the resolved config and build an
-- absolute path to .sqls.yml.
setup_lsp("sqls", {
	on_attach = on_attach_no_formatting,
	root_markers = { ".sqls.yml", ".git" },
	cmd = function(dispatchers, config)
		local cmd = { nix_vars.sqls }
		if config.root_dir then
			local config_file = config.root_dir .. "/.sqls.yml"
			if vim.fn.filereadable(config_file) == 1 then
				cmd = { nix_vars.sqls, "-config", config_file }
			end
		end
		return vim.lsp.rpc.start(cmd, dispatchers, {
			cwd = config.root_dir,
		})
	end,
})

-- Nix LSP Configuration
setup_lsp("nil_ls", {
	filetypes = { "nix" },
})

-- Omnisharp LSP Configuration
-- NOTE: https://github.com/NixOS/nixpkgs/issues/479348
-- setup_lsp("omnisharp", {
-- 	enable_roslyn_analyzers = true,
-- 	enable_import_completion = true,
-- 	organize_imports_on_format = true,
-- 	enable_decompilation_support = true,
-- 	filetypes = { "cs", "vb", "csproj", "sln", "slnx", "props", "csx", "targets", "tproj", "slngen", "fproj" },
-- 	cmd = { nix_vars.omnisharp, "--languageserver", "--hostPID", tostring(vim.fn.getpid()) },
-- })

-- Go LSP Configuration
setup_lsp("gopls", {
	on_attach = function(client, bufnr)
		on_attach(client, bufnr)
		vim.api.nvim_create_autocmd("BufWritePre", {
			group = augroup,
			buffer = bufnr,
			callback = organize_go_imports,
		})
	end,
	filetypes = { "go" },
	cmd = { "gopls", "-remote=auto" },
	settings = {
		gopls = {
			buildFlags = { "-tags=e2e" },
		},
	},
})

-- Go LSP Linting
setup_lsp("golangci_lint_ls", {
	on_attach = on_attach_no_formatting,
	cmd = { nix_vars.golintls },
	filetypes = { "go" },
	init_options = {
		command = {
			"golangci-lint",
			"run",
			"--output.json.path",
			"stdout",
			"--show-stats=false",
			"--issues-exit-code=1",
		},
	},
}, { manual = true, cmd_name = "GolangciLint" })

------------------------------------------------------
--------------------- None-LS LSP --------------------
------------------------------------------------------
local none_ls = require("null-ls")

none_ls.setup({
	sources = {
		-- Formatting
		none_ls.builtins.formatting.prettier,
		none_ls.builtins.formatting.prettier.with({ filetypes = { "template" } }),
		none_ls.builtins.formatting.nixpkgs_fmt, -- TODO: nixd native LSP?
		none_ls.builtins.formatting.sql_formatter.with({
			extra_args = {
				"--config",
				'{"tabWidth":4,"keywordCase":"upper","language":"sql"}',
			}
		}),
		require("none-ls.formatting.autopep8").with({
			filetypes = { "starlark", "python" },
			extra_args = { "--max-line-length", "100" },
		}),

		-- Completion
		none_ls.builtins.completion.spell,
	},
	on_attach = function(client, bufnr)
		if client:supports_method("textDocument/formatting") then
			vim.api.nvim_clear_autocmds({ group = augroup, buffer = bufnr })
			vim.api.nvim_create_autocmd("BufWritePre", {
				group = augroup,
				buffer = bufnr,
				callback = function()
					vim.lsp.buf.format({ async = false, timeout_ms = 2000 })
				end,
			})
		end
	end,
})
