bkmr-lsp 0.8.0

Language Server Protocol implementation for bkmr snippet manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
// File: bkmr-lsp/src/backend.rs - Word-based completion with manual triggering

use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use std::path::Path;
use tower_lsp::{Client, LanguageServer, jsonrpc::Result as LspResult, lsp_types::*};
use tracing::{debug, error, info, instrument, warn};

use crate::domain::CompletionContext;
use crate::repositories::{BkmrRepository, RepositoryConfig};
use crate::services::CompletionService;

/// Language-specific information for Rust pattern translation
#[derive(Debug, Clone)]
pub struct LanguageInfo {
    pub line_comment: Option<String>,
    pub block_comment: Option<(String, String)>,
    pub indent_char: String,
}

/// Configuration for the bkmr-lsp server
#[derive(Debug, Clone)]
pub struct BkmrConfig {
    pub bkmr_binary: String,
    pub max_completions: usize,
    pub enable_interpolation: bool,
}

impl Default for BkmrConfig {
    fn default() -> Self {
        Self {
            bkmr_binary: "bkmr".to_string(),
            max_completions: 50,
            enable_interpolation: true,
        }
    }
}

/// Represents a bkmr snippet from JSON output
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct BkmrSnippet {
    pub id: i32,
    pub title: String,
    pub url: String, // This contains the actual snippet content
    pub description: String,
    pub tags: Vec<String>,
    #[serde(default)]
    pub access_count: i32,
}

#[derive(Debug)]
pub struct BkmrLspBackend {
    client: Client,
    config: BkmrConfig,
    completion_service: CompletionService,
    /// Cache of document contents to extract prefixes
    document_cache: std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, String>>>,
    /// Cache of document language IDs for filetype-based filtering
    language_cache: std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, String>>>,
}

impl BkmrLspBackend {
    pub fn new(client: Client) -> Self {
        Self::with_config(client, BkmrConfig::default())
    }

    pub fn with_config(client: Client, config: BkmrConfig) -> Self {
        debug!("Creating BkmrLspBackend with config: {:?}", config);
        
        // Create repository with configuration from BkmrConfig
        let repo_config = RepositoryConfig {
            binary_path: config.bkmr_binary.clone(),
            max_results: config.max_completions,
            timeout_seconds: 10,
            enable_interpolation: config.enable_interpolation,
        };
        let repository = std::sync::Arc::new(BkmrRepository::new(repo_config));
        
        // Create completion service with repository and configuration
        let completion_service = CompletionService::with_config(repository, config.clone());
        
        Self {
            client,
            config,
            completion_service,
            document_cache: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            language_cache: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
        }
    }

    /// Extract word backwards from cursor position and return both query and range
    #[instrument(skip(self))]
    fn extract_snippet_query(&self, uri: &Url, position: Position) -> Option<(String, Range)> {
        let cache = self.document_cache.read().ok()?;
        let content = cache.get(&uri.to_string())?;

        let lines: Vec<&str> = content.lines().collect();
        if position.line as usize >= lines.len() {
            return None;
        }

        let line = lines[position.line as usize];
        let char_pos = position.character as usize;

        if char_pos > line.len() {
            return None;
        }

        let before_cursor = &line[..char_pos];
        debug!(
            "Extracting from line: '{}', char_pos: {}, before_cursor: '{}'",
            line, char_pos, before_cursor
        );

        // Extract word backwards from cursor - find where the word starts
        let word_start = before_cursor
            .char_indices()
            .rev()
            .take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '-')
            .last()
            .map(|(i, _)| i)
            .unwrap_or(char_pos);

        debug!("Word boundaries: start={}, end={}", word_start, char_pos);

        if word_start < char_pos {
            let word = &before_cursor[word_start..];
            if !word.is_empty() && word.chars().any(|c| c.is_alphanumeric()) {
                debug!("Extracted word: '{}' from position {}", word, char_pos);

                // Create range for the word to be replaced
                let range = Range {
                    start: Position {
                        line: position.line,
                        character: word_start as u32,
                    },
                    end: Position {
                        line: position.line,
                        character: char_pos as u32,
                    },
                };

                return Some((word.to_string(), range));
            }
        }

        debug!("No valid word found at position {}", char_pos);
        None
    }

    /// Get the language ID for a document URI
    fn get_language_id(&self, uri: &Url) -> Option<String> {
        let cache = self.language_cache.read().ok()?;
        cache.get(&uri.to_string()).cloned()
    }







    /// Check if bkmr binary is available
    #[instrument(skip(self))]
    async fn verify_bkmr_availability(&self) -> Result<()> {
        debug!("Verifying bkmr availability");

        let command_future = tokio::process::Command::new(&self.config.bkmr_binary)
            .args(["--help"])
            .output();

        let output =
            match tokio::time::timeout(std::time::Duration::from_secs(5), command_future).await {
                Ok(Ok(output)) => output,
                Ok(Err(e)) => {
                    return Err(anyhow!("bkmr binary not found: {}", e));
                }
                Err(_) => {
                    return Err(anyhow!("bkmr --help command timed out"));
                }
            };

        if !output.status.success() {
            return Err(anyhow!("bkmr binary is not working properly"));
        }

        info!("bkmr binary verified successfully");
        Ok(())
    }

    /// Get language-specific information for Rust pattern translation
    pub fn get_language_info(&self, language_id: &str) -> LanguageInfo {
        match language_id.to_lowercase().as_str() {
            "rust" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "javascript" | "js" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "  ".to_string(),
            },
            "typescript" | "ts" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "  ".to_string(),
            },
            "python" => LanguageInfo {
                line_comment: Some("#".to_string()),
                block_comment: Some(("\"\"\"".to_string(), "\"\"\"".to_string())),
                indent_char: "    ".to_string(),
            },
            "go" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "\t".to_string(),
            },
            "java" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "c" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "cpp" | "c++" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "html" => LanguageInfo {
                line_comment: None,
                block_comment: Some(("<!--".to_string(), "-->".to_string())),
                indent_char: "  ".to_string(),
            },
            "css" => LanguageInfo {
                line_comment: None,
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "  ".to_string(),
            },
            "scss" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "  ".to_string(),
            },
            "ruby" => LanguageInfo {
                line_comment: Some("#".to_string()),
                block_comment: Some(("=begin".to_string(), "=end".to_string())),
                indent_char: "  ".to_string(),
            },
            "php" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "swift" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "kotlin" => LanguageInfo {
                line_comment: Some("//".to_string()),
                block_comment: Some(("/*".to_string(), "*/".to_string())),
                indent_char: "    ".to_string(),
            },
            "shell" | "bash" | "sh" => LanguageInfo {
                line_comment: Some("#".to_string()),
                block_comment: None,
                indent_char: "    ".to_string(),
            },
            "yaml" | "yml" => LanguageInfo {
                line_comment: Some("#".to_string()),
                block_comment: None,
                indent_char: "  ".to_string(),
            },
            "json" => LanguageInfo {
                line_comment: None,
                block_comment: None,
                indent_char: "  ".to_string(),
            },
            "markdown" | "md" => LanguageInfo {
                line_comment: None,
                block_comment: Some(("<!--".to_string(), "-->".to_string())),
                indent_char: "  ".to_string(),
            },
            "xml" => LanguageInfo {
                line_comment: None,
                block_comment: Some(("<!--".to_string(), "-->".to_string())),
                indent_char: "  ".to_string(),
            },
            "vim" | "viml" => LanguageInfo {
                line_comment: Some("\"".to_string()),
                block_comment: None,
                indent_char: "  ".to_string(),
            },
            // Default fallback for unknown languages
            _ => LanguageInfo {
                line_comment: Some("#".to_string()),
                block_comment: None,
                indent_char: "    ".to_string(),
            },
        }
    }



    /// Legacy method for backward compatibility - uses new language info system
    fn get_comment_syntax(&self, file_path: &str) -> &'static str {
        let path = Path::new(file_path);
        let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("");

        // Map file extension to language ID for language info lookup
        let language_id = match extension {
            "rs" => "rust",
            "js" | "mjs" => "javascript",
            "ts" | "tsx" => "typescript",
            "py" | "pyw" => "python",
            "go" => "go",
            "java" => "java",
            "c" | "h" => "c",
            "cpp" | "cc" | "cxx" | "hpp" => "cpp",
            "html" | "htm" => "html",
            "css" => "css",
            "scss" => "scss",
            "rb" => "ruby",
            "php" => "php",
            "swift" => "swift",
            "kt" | "kts" => "kotlin",
            "sh" | "bash" | "zsh" => "shell",
            "yaml" | "yml" => "yaml",
            "json" => "json",
            "md" | "markdown" => "markdown",
            "xml" => "xml",
            "vim" => "vim",
            _ => "unknown",
        };

        let lang_info = self.get_language_info(language_id);
        // Return line comment or block comment start, fallback to #
        if let Some(_line_comment) = &lang_info.line_comment {
            // This is a bit of a hack since we need to return &'static str
            // but the LanguageInfo returns String. For the legacy method,
            // we'll use a simple lookup.
            match language_id {
                "rust" | "javascript" | "typescript" | "go" | "java" | "c" | "cpp" | "swift"
                | "kotlin" | "scss" | "php" => "//",
                "python" | "shell" | "yaml" => "#",
                "html" | "markdown" | "xml" => "<!--",
                "css" => "/*",
                "vim" => "\"",
                _ => "#",
            }
        } else {
            "#"
        }
    }

    /// Get the relative path from project root
    fn get_relative_path(&self, file_uri: &str) -> String {
        let url = match Url::parse(file_uri) {
            Ok(u) => u,
            Err(_) => return file_uri.to_string(),
        };

        let file_path = match url.to_file_path() {
            Ok(p) => p,
            Err(_) => return file_uri.to_string(),
        };

        // Try to find a project root by looking for common indicators
        let mut current = file_path.as_path();
        while let Some(parent) = current.parent() {
            // Check for common project root indicators
            if parent.join("Cargo.toml").exists()
                || parent.join("package.json").exists()
                || parent.join("pom.xml").exists()
                || parent.join("build.gradle").exists()
                || parent.join("build.gradle.kts").exists()
                || parent.join("Makefile").exists()
                || parent.join(".git").exists()
            {
                // Found project root, return relative path
                if let Ok(rel_path) = file_path.strip_prefix(parent) {
                    return rel_path.to_string_lossy().to_string();
                }
                break;
            }
            current = parent;
        }

        // Fall back to just the filename if no project root found
        file_path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| file_uri.to_string())
    }

    /// Insert filepath comment at the beginning of the file
    #[instrument(skip(self))]
    async fn insert_filepath_comment(&self, file_uri: &str) -> Result<Vec<TextEdit>> {
        let relative_path = self.get_relative_path(file_uri);
        let comment_syntax = self.get_comment_syntax(file_uri);

        let comment_text = match comment_syntax {
            "<!--" => format!("<!-- {} -->\n", relative_path),
            "/*" => format!("/* {} */\n", relative_path),
            _ => format!("{} {}\n", comment_syntax, relative_path),
        };

        debug!("Inserting filepath comment: {}", comment_text.trim());

        // Create a text edit to insert at the beginning of the file
        let edit = TextEdit {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 0,
                },
            },
            new_text: comment_text,
        };

        Ok(vec![edit])
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for BkmrLspBackend {
    #[instrument(skip(self, params))]
    async fn initialize(&self, params: InitializeParams) -> LspResult<InitializeResult> {
        info!(
            "Initialize request received from client: {:?}",
            params.client_info
        );

        // Verify bkmr is available
        if let Err(e) = self.verify_bkmr_availability().await {
            error!("bkmr verification failed: {}", e);
            self.client
                .log_message(
                    MessageType::ERROR,
                    &format!("Failed to verify bkmr availability: {}", e),
                )
                .await;
        }

        // Check if client supports snippets
        let snippet_support = params
            .capabilities
            .text_document
            .as_ref()
            .and_then(|td| td.completion.as_ref())
            .and_then(|comp| comp.completion_item.as_ref())
            .and_then(|item| item.snippet_support)
            .unwrap_or(false);

        info!("Client snippet support: {}", snippet_support);

        if !snippet_support {
            warn!("Client does not support snippets");
            self.client
                .log_message(
                    MessageType::WARNING,
                    "Client does not support snippets, functionality may be limited",
                )
                .await;
        }

        let result = InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                completion_provider: Some(CompletionOptions {
                    resolve_provider: Some(false),
                    trigger_characters: None, // No automatic triggers - manual completion only
                    all_commit_characters: None,
                    work_done_progress_options: WorkDoneProgressOptions::default(),
                    completion_item: None,
                }),
                execute_command_provider: Some(ExecuteCommandOptions {
                    commands: vec!["bkmr.insertFilepathComment".to_string()],
                    work_done_progress_options: WorkDoneProgressOptions::default(),
                }),
                ..Default::default()
            },
            ..Default::default()
        };

        info!("Initialize complete - manual completion only (no trigger characters)");
        Ok(result)
    }

    #[instrument(skip(self))]
    async fn initialized(&self, _: InitializedParams) {
        info!("Server initialized successfully");

        self.client
            .log_message(MessageType::INFO, "bkmr-lsp server ready")
            .await;
    }

    #[instrument(skip(self))]
    async fn shutdown(&self) -> LspResult<()> {
        info!("Shutdown request received");
        self.client
            .log_message(MessageType::INFO, "Shutting down bkmr-lsp server")
            .await;
        Ok(())
    }

    #[instrument(skip(self, params))]
    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri.to_string();
        let content = params.text_document.text;
        let language_id = params.text_document.language_id;

        debug!("Document opened: {} (language: {})", uri, language_id);

        if let Ok(mut cache) = self.document_cache.write() {
            cache.insert(uri.clone(), content);
        }

        if let Ok(mut lang_cache) = self.language_cache.write() {
            lang_cache.insert(uri, language_id);
        }
    }

    #[instrument(skip(self, params))]
    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri.to_string();

        debug!("Document changed: {}", uri);

        if let Ok(mut cache) = self.document_cache.write() {
            for change in params.content_changes {
                if let Some(content) = cache.get_mut(&uri) {
                    // For FULL sync, replace entire content
                    if change.range.is_none() {
                        *content = change.text;
                    } else {
                        // For incremental sync, would need more complex logic
                        // For now, just replace entirely
                        *content = change.text;
                    }
                }
            }
        }
    }

    #[instrument(skip(self, params))]
    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri.to_string();

        debug!("Document closed: {}", uri);

        if let Ok(mut cache) = self.document_cache.write() {
            cache.remove(&uri);
        }

        if let Ok(mut lang_cache) = self.language_cache.write() {
            lang_cache.remove(&uri);
        }
    }

    #[instrument(skip(self, params))]
    async fn completion(&self, params: CompletionParams) -> LspResult<Option<CompletionResponse>> {
        let uri = &params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;

        debug!(
            "Completion request for {}:{},{}",
            uri, position.line, position.character
        );

        // Only respond to manual completion requests (Ctrl+Space)
        if let Some(context) = &params.context {
            match context.trigger_kind {
                CompletionTriggerKind::INVOKED => {
                    // Manual Ctrl+Space - proceed with word-based completion
                    debug!("Manual completion request - proceeding with word-based snippet search");
                }
                CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS => {
                    debug!("Completion for incomplete results - proceeding");
                }
                _ => {
                    debug!("Ignoring automatic trigger - only manual completion supported");
                    return Ok(Some(CompletionResponse::Array(vec![])));
                }
            }
        } else {
            debug!("No completion context - skipping");
            return Ok(Some(CompletionResponse::Array(vec![])));
        }

        // Extract the query after trigger and get replacement range
        let query_info = self.extract_snippet_query(uri, position);
        debug!("Extracted snippet query info: {:?}", query_info);

        // Get the language ID for filetype-based filtering
        let language_id = self.get_language_id(uri);
        debug!("Document language ID: {:?}", language_id);

        // Create completion context for the service
        let mut context = CompletionContext::new(
            uri.clone(),
            position,
            language_id
        );
        
        // Add query information if extracted
        if let Some((query, range)) = query_info {
            debug!("Query: '{}', Range: {:?}", query, range);
            context = context.with_query(crate::domain::CompletionQuery::new(query, range));
        } else {
            debug!("No query extracted, using empty query");
        }

        // Use CompletionService to get completion items
        match self.completion_service.get_completions(&context).await {
            Ok(completion_items) => {
                info!(
                    "Returning {} completion items for query: {:?}",
                    completion_items.len(),
                    context.get_query_text().unwrap_or("")
                );

                // Only log first few items to reduce noise in LSP logs
                for (i, item) in completion_items.iter().enumerate().take(3) {
                    debug!(
                        "Item {}: label='{}', sort_text={:?}",
                        i, item.label, item.sort_text
                    );
                }
                if completion_items.len() > 3 {
                    debug!("... and {} more items", completion_items.len() - 3);
                }

                Ok(Some(CompletionResponse::List(CompletionList {
                    is_incomplete: true,
                    items: completion_items,
                })))
            }
            Err(e) => {
                error!("Failed to get completions: {}", e);
                self.client
                    .log_message(
                        MessageType::ERROR,
                        &format!("Failed to get completions: {}", e),
                    )
                    .await;
                Ok(Some(CompletionResponse::Array(vec![])))
            }
        }
    }

    #[instrument(skip(self, params))]
    async fn execute_command(
        &self,
        params: ExecuteCommandParams,
    ) -> LspResult<Option<serde_json::Value>> {
        debug!("Execute command request: {}", params.command);

        match params.command.as_str() {
            "bkmr.insertFilepathComment" => {
                // Extract file URI from arguments
                if !params.arguments.is_empty() {
                    if let Some(first_arg) = params.arguments.first() {
                        if let Ok(uri_str) = serde_json::from_value::<String>(first_arg.clone()) {
                            match self.insert_filepath_comment(&uri_str).await {
                                Ok(edits) => {
                                    // Apply the text edits to the document
                                    let workspace_edit = WorkspaceEdit {
                                        changes: Some({
                                            let mut changes = std::collections::HashMap::new();
                                            if let Ok(uri) = Url::parse(&uri_str) {
                                                changes.insert(uri, edits);
                                            }
                                            changes
                                        }),
                                        document_changes: None,
                                        change_annotations: None,
                                    };

                                    // Request client to apply the edit
                                    match self.client.apply_edit(workspace_edit).await {
                                        Ok(response) => {
                                            if response.applied {
                                                info!("Successfully inserted filepath comment");
                                                self.client
                                                    .log_message(
                                                        MessageType::INFO,
                                                        "Filepath comment inserted successfully",
                                                    )
                                                    .await;
                                            } else {
                                                warn!("Client rejected the edit");
                                                self.client
                                                    .log_message(
                                                        MessageType::WARNING,
                                                        "Failed to apply filepath comment edit",
                                                    )
                                                    .await;
                                            }
                                        }
                                        Err(e) => {
                                            error!("Failed to apply edit: {}", e);
                                            self.client
                                                .log_message(
                                                    MessageType::ERROR,
                                                    &format!("Failed to apply edit: {}", e),
                                                )
                                                .await;
                                        }
                                    }
                                }
                                Err(e) => {
                                    error!("Failed to create filepath comment: {}", e);
                                    self.client
                                        .log_message(
                                            MessageType::ERROR,
                                            &format!("Failed to create filepath comment: {}", e),
                                        )
                                        .await;
                                }
                            }
                        } else {
                            error!("Invalid argument format for insertFilepathComment");
                        }
                    } else {
                        error!("No arguments provided for insertFilepathComment command");
                    }
                } else {
                    error!("No arguments provided for insertFilepathComment command");
                }
            }
            _ => {
                error!("Unknown command: {}", params.command);
                self.client
                    .log_message(
                        MessageType::ERROR,
                        &format!("Unknown command: {}", params.command),
                    )
                    .await;
            }
        }

        Ok(None)
    }
}

/// Start a bkmr-lsp server with given input/output streams
/// This function is used by tests to spawn a real LSP server for testing
pub async fn start_server<I, O>(read: I, write: O)
where
    I: tokio::io::AsyncRead + Unpin,
    O: tokio::io::AsyncWrite,
{
    use tower_lsp::{LspService, Server};

    // Create the LSP service
    let (service, socket) = LspService::new(BkmrLspBackend::new);

    // Start the server with the provided streams
    Server::new(read, write, socket).serve(service).await;
}