1package lsp
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log/slog"
  8	"maps"
  9	"os"
 10	"path/filepath"
 11	"strings"
 12	"sync/atomic"
 13	"time"
 14
 15	"github.com/charmbracelet/crush/internal/config"
 16	"github.com/charmbracelet/crush/internal/csync"
 17	"github.com/charmbracelet/crush/internal/fsext"
 18	"github.com/charmbracelet/crush/internal/home"
 19	powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
 20	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
 21	"github.com/charmbracelet/x/powernap/pkg/transport"
 22)
 23
 24type Client struct {
 25	client *powernap.Client
 26	name   string
 27
 28	// File types this LSP server handles (e.g., .go, .rs, .py)
 29	fileTypes []string
 30
 31	// Configuration for this LSP client
 32	config config.LSPConfig
 33
 34	// Diagnostic change callback
 35	onDiagnosticsChanged func(name string, count int)
 36
 37	// Diagnostic cache
 38	diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
 39
 40	// Files are currently opened by the LSP
 41	openFiles *csync.Map[string, *OpenFileInfo]
 42
 43	// Server state
 44	serverState atomic.Value
 45}
 46
 47// New creates a new LSP client using the powernap implementation.
 48func New(ctx context.Context, name string, config config.LSPConfig, resolver config.VariableResolver) (*Client, error) {
 49	// Convert working directory to file URI
 50	workDir, err := os.Getwd()
 51	if err != nil {
 52		return nil, fmt.Errorf("failed to get working directory: %w", err)
 53	}
 54
 55	rootURI := string(protocol.URIFromPath(workDir))
 56
 57	command, err := resolver.ResolveValue(config.Command)
 58	if err != nil {
 59		return nil, fmt.Errorf("invalid lsp command: %w", err)
 60	}
 61
 62	// Create powernap client config
 63	clientConfig := powernap.ClientConfig{
 64		Command: home.Long(command),
 65		Args:    config.Args,
 66		RootURI: rootURI,
 67		Environment: func() map[string]string {
 68			env := make(map[string]string)
 69			maps.Copy(env, config.Env)
 70			return env
 71		}(),
 72		Settings:    config.Options,
 73		InitOptions: config.InitOptions,
 74		WorkspaceFolders: []protocol.WorkspaceFolder{
 75			{
 76				URI:  rootURI,
 77				Name: filepath.Base(workDir),
 78			},
 79		},
 80	}
 81
 82	// Create the powernap client
 83	powernapClient, err := powernap.NewClient(clientConfig)
 84	if err != nil {
 85		return nil, fmt.Errorf("failed to create lsp client: %w", err)
 86	}
 87
 88	client := &Client{
 89		client:      powernapClient,
 90		name:        name,
 91		fileTypes:   config.FileTypes,
 92		diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
 93		openFiles:   csync.NewMap[string, *OpenFileInfo](),
 94		config:      config,
 95	}
 96
 97	// Initialize server state
 98	client.serverState.Store(StateStarting)
 99
100	return client, nil
101}
102
103// Initialize initializes the LSP client and returns the server capabilities.
104func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
105	if err := c.client.Initialize(ctx, false); err != nil {
106		return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
107	}
108
109	// Convert powernap capabilities to protocol capabilities
110	caps := c.client.GetCapabilities()
111	protocolCaps := protocol.ServerCapabilities{
112		TextDocumentSync: caps.TextDocumentSync,
113		CompletionProvider: func() *protocol.CompletionOptions {
114			if caps.CompletionProvider != nil {
115				return &protocol.CompletionOptions{
116					TriggerCharacters:   caps.CompletionProvider.TriggerCharacters,
117					AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
118					ResolveProvider:     caps.CompletionProvider.ResolveProvider,
119				}
120			}
121			return nil
122		}(),
123	}
124
125	result := &protocol.InitializeResult{
126		Capabilities: protocolCaps,
127	}
128
129	c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
130	c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
131	c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
132	c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
133	c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
134		HandleDiagnostics(c, params)
135	})
136
137	return result, nil
138}
139
140// Close closes the LSP client.
141func (c *Client) Close(ctx context.Context) error {
142	// Try to close all open files first
143	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
144	defer cancel()
145
146	c.CloseAllFiles(ctx)
147
148	// Shutdown and exit the client
149	if err := c.client.Shutdown(ctx); err != nil {
150		slog.Warn("Failed to shutdown LSP client", "error", err)
151	}
152
153	return c.client.Exit()
154}
155
156// ServerState represents the state of an LSP server
157type ServerState int
158
159const (
160	StateStarting ServerState = iota
161	StateReady
162	StateError
163	StateDisabled
164)
165
166// GetServerState returns the current state of the LSP server
167func (c *Client) GetServerState() ServerState {
168	if val := c.serverState.Load(); val != nil {
169		return val.(ServerState)
170	}
171	return StateStarting
172}
173
174// SetServerState sets the current state of the LSP server
175func (c *Client) SetServerState(state ServerState) {
176	c.serverState.Store(state)
177}
178
179// GetName returns the name of the LSP client
180func (c *Client) GetName() string {
181	return c.name
182}
183
184// SetDiagnosticsCallback sets the callback function for diagnostic changes
185func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
186	c.onDiagnosticsChanged = callback
187}
188
189// WaitForServerReady waits for the server to be ready
190func (c *Client) WaitForServerReady(ctx context.Context) error {
191	cfg := config.Get()
192
193	// Set initial state
194	c.SetServerState(StateStarting)
195
196	// Create a context with timeout
197	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
198	defer cancel()
199
200	// Try to ping the server with a simple request
201	ticker := time.NewTicker(500 * time.Millisecond)
202	defer ticker.Stop()
203
204	if cfg != nil && cfg.Options.DebugLSP {
205		slog.Debug("Waiting for LSP server to be ready...")
206	}
207
208	c.openKeyConfigFiles(ctx)
209
210	for {
211		select {
212		case <-ctx.Done():
213			c.SetServerState(StateError)
214			return fmt.Errorf("timeout waiting for LSP server to be ready")
215		case <-ticker.C:
216			// Check if client is running
217			if !c.client.IsRunning() {
218				if cfg != nil && cfg.Options.DebugLSP {
219					slog.Debug("LSP server not ready yet", "server", c.name)
220				}
221				continue
222			}
223
224			// Server is ready
225			c.SetServerState(StateReady)
226			if cfg != nil && cfg.Options.DebugLSP {
227				slog.Debug("LSP server is ready")
228			}
229			return nil
230		}
231	}
232}
233
234// OpenFileInfo contains information about an open file
235type OpenFileInfo struct {
236	Version int32
237	URI     protocol.DocumentURI
238}
239
240// HandlesFile checks if this LSP client handles the given file based on its extension.
241func (c *Client) HandlesFile(path string) bool {
242	// If no file types are specified, handle all files (backward compatibility)
243	if len(c.fileTypes) == 0 {
244		return true
245	}
246
247	name := strings.ToLower(filepath.Base(path))
248	for _, filetype := range c.fileTypes {
249		suffix := strings.ToLower(filetype)
250		if !strings.HasPrefix(suffix, ".") {
251			suffix = "." + suffix
252		}
253		if strings.HasSuffix(name, suffix) {
254			slog.Debug("handles file", "name", c.name, "file", name, "filetype", filetype)
255			return true
256		}
257	}
258	slog.Debug("doesn't handle file", "name", c.name, "file", name)
259	return false
260}
261
262// OpenFile opens a file in the LSP server.
263func (c *Client) OpenFile(ctx context.Context, filepath string) error {
264	if !c.HandlesFile(filepath) {
265		return nil
266	}
267
268	uri := string(protocol.URIFromPath(filepath))
269
270	if _, exists := c.openFiles.Get(uri); exists {
271		return nil // Already open
272	}
273
274	// Skip files that do not exist or cannot be read
275	content, err := os.ReadFile(filepath)
276	if err != nil {
277		return fmt.Errorf("error reading file: %w", err)
278	}
279
280	// Notify the server about the opened document
281	if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(DetectLanguageID(uri)), 1, string(content)); err != nil {
282		return err
283	}
284
285	c.openFiles.Set(uri, &OpenFileInfo{
286		Version: 1,
287		URI:     protocol.DocumentURI(uri),
288	})
289
290	return nil
291}
292
293// NotifyChange notifies the server about a file change.
294func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
295	uri := string(protocol.URIFromPath(filepath))
296
297	content, err := os.ReadFile(filepath)
298	if err != nil {
299		return fmt.Errorf("error reading file: %w", err)
300	}
301
302	fileInfo, isOpen := c.openFiles.Get(uri)
303	if !isOpen {
304		return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
305	}
306
307	// Increment version
308	fileInfo.Version++
309
310	// Create change event
311	changes := []protocol.TextDocumentContentChangeEvent{
312		{
313			Value: protocol.TextDocumentContentChangeWholeDocument{
314				Text: string(content),
315			},
316		},
317	}
318
319	return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
320}
321
322// IsFileOpen checks if a file is currently open.
323func (c *Client) IsFileOpen(filepath string) bool {
324	uri := string(protocol.URIFromPath(filepath))
325	_, exists := c.openFiles.Get(uri)
326	return exists
327}
328
329// CloseAllFiles closes all currently open files.
330func (c *Client) CloseAllFiles(ctx context.Context) {
331	cfg := config.Get()
332	debugLSP := cfg != nil && cfg.Options.DebugLSP
333	for uri := range c.openFiles.Seq2() {
334		if debugLSP {
335			slog.Debug("Closing file", "file", uri)
336		}
337		if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
338			slog.Warn("Error closing rile", "uri", uri, "error", err)
339			continue
340		}
341		c.openFiles.Del(uri)
342	}
343}
344
345// GetFileDiagnostics returns diagnostics for a specific file.
346func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
347	diags, _ := c.diagnostics.Get(uri)
348	return diags
349}
350
351// GetDiagnostics returns all diagnostics for all files.
352func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
353	return maps.Collect(c.diagnostics.Seq2())
354}
355
356// OpenFileOnDemand opens a file only if it's not already open.
357func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
358	// Check if the file is already open
359	if c.IsFileOpen(filepath) {
360		return nil
361	}
362
363	// Open the file
364	return c.OpenFile(ctx, filepath)
365}
366
367// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
368func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
369	documentURI := protocol.URIFromPath(filepath)
370
371	// Make sure the file is open
372	if !c.IsFileOpen(filepath) {
373		if err := c.OpenFile(ctx, filepath); err != nil {
374			return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
375		}
376
377		// Give the LSP server a moment to process the file
378		time.Sleep(100 * time.Millisecond)
379	}
380
381	// Get diagnostics
382	diagnostics, _ := c.diagnostics.Get(documentURI)
383
384	return diagnostics, nil
385}
386
387// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
388func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
389	c.diagnostics.Del(uri)
390}
391
392// RegisterNotificationHandler registers a notification handler.
393func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
394	c.client.RegisterNotificationHandler(method, handler)
395}
396
397// RegisterServerRequestHandler handles server requests.
398func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
399	c.client.RegisterHandler(method, handler)
400}
401
402// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
403func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
404	return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
405}
406
407// openKeyConfigFiles opens important configuration files that help initialize the server.
408func (c *Client) openKeyConfigFiles(ctx context.Context) {
409	wd, err := os.Getwd()
410	if err != nil {
411		return
412	}
413
414	// Try to open each file, ignoring errors if they don't exist
415	for _, file := range c.config.RootMarkers {
416		file = filepath.Join(wd, file)
417		if _, err := os.Stat(file); err == nil {
418			// File exists, try to open it
419			if err := c.OpenFile(ctx, file); err != nil {
420				slog.Debug("Failed to open key config file", "file", file, "error", err)
421			} else {
422				slog.Debug("Opened key config file for initialization", "file", file)
423			}
424		}
425	}
426}
427
428// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
429func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
430	ticker := time.NewTicker(200 * time.Millisecond)
431	defer ticker.Stop()
432	timeout := time.After(d)
433	pv := c.diagnostics.Version()
434	for {
435		select {
436		case <-ctx.Done():
437			return
438		case <-timeout:
439			return
440		case <-ticker.C:
441			if pv != c.diagnostics.Version() {
442				return
443			}
444		}
445	}
446}
447
448// HasRootMarkers checks if any of the specified root marker patterns exist in the given directory.
449// Uses glob patterns to match files, allowing for more flexible matching.
450func HasRootMarkers(dir string, rootMarkers []string) bool {
451	if len(rootMarkers) == 0 {
452		return true
453	}
454	for _, pattern := range rootMarkers {
455		// Use fsext.GlobWithDoubleStar to find matches
456		matches, _, err := fsext.GlobWithDoubleStar(pattern, dir, 1)
457		if err == nil && len(matches) > 0 {
458			return true
459		}
460	}
461	return false
462}