-- Test script for code actions
-- Enable debug logging
vim.lsp.set_log_level("debug")

print("Starting LSP client...")
local client = vim.lsp.start_client({
    name = "educationallsp",
    cmd = { "/Users/russellboley/git/educationallsp/target/debug/educationallsp" },
    root_dir = vim.fn.getcwd(),
})

if not client then
    print("Failed to start educationallsp")
    vim.cmd("quit!")
    return
end

print("LSP client started with ID: " .. client)

-- Open the test file
vim.cmd("edit tmp/test.md")
local bufnr = vim.api.nvim_get_current_buf()
print("Opened buffer: " .. bufnr)

-- Set filetype
vim.bo.filetype = "markdown"

-- Attach LSP client
local success = vim.lsp.buf_attach_client(bufnr, client)
print("LSP attach result: " .. tostring(success))

-- Wait for LSP to initialize
print("Waiting for LSP to initialize...")
vim.wait(3000, function() return false end)

-- Check if client is still alive
local clients = vim.lsp.get_active_clients()
print("Active clients: " .. #clients)
for _, c in ipairs(clients) do
    print("  - Client: " .. c.name .. " (ID: " .. c.id .. ")")
end

-- Get code actions
local params = {
    textDocument = vim.lsp.util.make_text_document_params(),
    range = {
        start = { line = 0, character = 0 },
        ["end"] = { line = 0, character = 50 }
    },
    context = { diagnostics = {} }
}
local result = vim.lsp.buf_request_sync(bufnr, "textDocument/codeAction", params, 5000)

print("Raw result: " .. vim.inspect(result))

if result and result[client] and result[client].result then
    local actions = result[client].result
    print("Found " .. #actions .. " code actions")
    
    if #actions > 0 then
        print("First code action: " .. vim.inspect(actions[1]))
        print("Applying first code action: " .. actions[1].title)
        
        -- Apply the first code action
        if actions[1].edit then
            print("Edit details: " .. vim.inspect(actions[1].edit))
            local success = vim.lsp.util.apply_workspace_edit(actions[1].edit, "utf-8")
            print("Apply workspace edit result: " .. tostring(success))
        else
            print("No edit in code action")
        end
        
        -- Save the file
        vim.cmd("write")
        print("File saved after applying code action")
        
        -- Check if content changed
        local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
        print("Current buffer content: " .. vim.inspect(lines))
    else
        print("No code actions found")
    end
else
    print("No code action response received")
    if result then
        print("Result keys: " .. vim.inspect(vim.tbl_keys(result)))
        for k, v in pairs(result) do
            print("Result[" .. k .. "]: " .. vim.inspect(v))
        end
    end
end

-- Quit
vim.cmd("quit!")