-- Dart/Flutter LSP configuration
-- dartls is bundled with the Dart SDK (which ships with Flutter)

local function get_dart_sdk_path()
    -- Try Flutter's bundled Dart SDK first
    local flutter_dart = vim.fn.expand("~/development/flutter/bin/cache/dart-sdk/bin/dart")
    if vim.fn.executable(flutter_dart) == 1 then
        return flutter_dart
    end
    -- Fall back to system dart
    return "dart"
end

vim.lsp.config("dartls", {
    cmd = { get_dart_sdk_path(), "language-server", "--protocol=lsp" },
    filetypes = { "dart" },
    root_markers = { "pubspec.yaml", "pubspec.yml" },

    -- Dart-specific settings
    settings = {
        dart = {
            -- Enable Flutter integration
            completeFunctionCalls = true,
            showTodos = true,
            runPubGetOnPubspecChanges = true,
            updateImportsOnRename = true,
            closingLabels = true,
            -- Flutter-specific
            enableSdkFormatter = true,
            lineLength = 80,
            -- Analysis
            enableSnippets = true,
        },
    },
})

-- Dart/Flutter-specific LSP attach handlers
vim.api.nvim_create_autocmd("LspAttach", {
    callback = function(args)
        local client = vim.lsp.get_client_by_id(args.data.client_id)
        if client and client.name == "dartls" then
            local bufnr = args.buf

            -- Flutter hot reload
            vim.keymap.set("n", "<leader>fr", function()
                vim.lsp.buf_request(bufnr, "dart/reanalyze", nil)
                vim.cmd("write")
                vim.cmd("!flutter hot-reload 2>/dev/null || flutter run --hot")
            end, { buffer = bufnr, desc = "Flutter: Hot Reload" })

            -- Flutter hot restart
            vim.keymap.set("n", "<leader>fR", function()
                vim.cmd("write")
                vim.cmd("!flutter run --restart 2>/dev/null")
            end, { buffer = bufnr, desc = "Flutter: Hot Restart" })

            -- Organize imports
            vim.keymap.set("n", "<leader>fo", function()
                vim.lsp.buf.execute_command({ command = "dart.organizeImports", arguments = { vim.fn.expand("%:p") } })
            end, { buffer = bufnr, desc = "Dart: Organize Imports" })

            -- Fix all auto-fixable issues
            vim.keymap.set("n", "<leader>fa", function()
                vim.lsp.buf.code_action({
                    context = { only = { "source.fixAll" } },
                    apply = true,
                })
            end, { buffer = bufnr, desc = "Dart: Fix All" })

            -- Sort members
            vim.keymap.set("n", "<leader>fs", function()
                vim.lsp.buf.execute_command({ command = "dart.sortMembers", arguments = { vim.fn.expand("%:p") } })
            end, { buffer = bufnr, desc = "Dart: Sort Members" })
        end
    end,
})

-- Enable the server
vim.lsp.enable("dartls")
