oxi-cli 0.63.0

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
//! CLI-side `LspProvider` implementation — bridges the agent's `lsp`
//! tool to [`super::LspManager`].
//!
//! Implements every method of [`oxi_agent::tools::LspProvider`] by
//! routing to the manager's lazy-spawned [`oxi_lsp::LspClient`]s.
//! Errors are returned as plain `String` (the `ToolError` alias).

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;

use oxi_agent::tools::{
    DiagnosticsSummary, FileDiagnosticEntry, LspAction, LspProvider, ToolError,
};

use lsp_types::request::{
    CodeActionRequest, DocumentSymbolRequest, GotoDefinition, GotoImplementation,
    GotoTypeDefinition, HoverRequest, References, Rename, WillRenameFiles, WorkspaceSymbolRequest,
};
use lsp_types::{
    CodeActionContext, CodeActionParams, DocumentSymbolParams, FileRename, GotoDefinitionParams,
    HoverParams, Position, Range, ReferenceParams, RenameParams, TextDocumentIdentifier,
    TextDocumentPositionParams, WorkDoneProgressParams, WorkspaceSymbolParams,
};

use crate::lsp::manager::LspManager;

/// CLI-side `LspProvider` wrapping an [`LspManager`].
#[derive(Clone)]
pub struct CliLspProvider {
    manager: Arc<LspManager>,
}

impl std::fmt::Debug for CliLspProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CliLspProvider")
            .field("workspace_root", &self.manager.workspace_root())
            .field("server_count", &self.manager.server_count())
            .finish_non_exhaustive()
    }
}

/// Per-RPC timeout for LSP requests (definition, references, hover, …).
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

impl CliLspProvider {
    /// Construct a provider that shares the given manager.
    pub fn new(manager: Arc<LspManager>) -> Self {
        Self { manager }
    }

    /// Construct a provider owning a fresh manager configured from
    /// [`crate::lsp::manager::default_servers()`].
    pub fn with_defaults(workspace_root: PathBuf) -> Self {
        let manager = Arc::new(LspManager::with_defaults(workspace_root));
        Self::new(manager)
    }

    /// Borrow the wrapped manager.
    pub fn manager(&self) -> &LspManager {
        &self.manager
    }

    /// Best-effort shutdown of every spawned server.
    pub async fn shutdown_all(&self) {
        self.manager.shutdown_all().await;
    }

    /// Resolve a file argument to an absolute path inside the
    /// workspace root. Returns a `ToolError` when the file does not
    /// exist.
    fn resolve_file(&self, file: &str) -> Result<PathBuf, ToolError> {
        let p = PathBuf::from(file);
        let abs = if p.is_absolute() {
            p
        } else {
            self.manager.workspace_root().join(&p)
        };
        if !abs.exists() {
            return Err(format!("LSP file does not exist: {}", abs.display()));
        }
        Ok(abs)
    }

    fn work_done() -> WorkDoneProgressParams {
        WorkDoneProgressParams {
            work_done_token: None,
        }
    }

    fn position_params(uri: lsp_types::Url, line: u32) -> TextDocumentPositionParams {
        TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: line.saturating_sub(1),
                character: 0,
            },
        }
    }

    fn goto_params(uri: lsp_types::Url, line: u32) -> GotoDefinitionParams {
        GotoDefinitionParams {
            text_document_position_params: Self::position_params(uri, line),
            work_done_progress_params: Self::work_done(),
            partial_result_params: lsp_types::PartialResultParams {
                partial_result_token: None,
            },
        }
    }

    /// Spawn-or-fetch the LSP client owning `abs`'s extension.
    async fn client_for(
        &self,
        abs: &std::path::Path,
    ) -> Result<Arc<oxi_lsp::LspClient>, ToolError> {
        self.manager
            .client_for_path(abs)
            .await
            .map_err(|e| format!("LSP spawn failed: {e}"))?
            .ok_or_else(|| {
                format!(
                    "no LSP server configured for extension {:?}",
                    abs.extension().and_then(|e| e.to_str()).unwrap_or("")
                )
            })
    }

    fn uri(abs: &std::path::Path) -> Result<lsp_types::Url, ToolError> {
        oxi_lsp::uri_for(abs).ok_or_else(|| "invalid path for URI".to_string())
    }

    // ── Action handlers ──────────────────────────────────────────

    async fn action_diagnostics(&self, file: &str) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri_string = oxi_lsp::uri_for(&abs)
            .map(|u| u.to_string())
            .unwrap_or_default();
        let entries = client.read_diagnostics(&[uri_string]);
        Ok(summarize_entries(&abs, &entries))
    }

    async fn action_definition(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = Self::goto_params(uri, line);
        let resp: lsp_types::GotoDefinitionResponse = client
            .request::<GotoDefinition>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?
            .unwrap_or(lsp_types::GotoDefinitionResponse::Array(vec![]));
        Ok(format_locations(&resp))
    }

    async fn action_references(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = ReferenceParams {
            text_document_position: Self::position_params(uri, line),
            work_done_progress_params: Self::work_done(),
            partial_result_params: lsp_types::PartialResultParams {
                partial_result_token: None,
            },
            context: lsp_types::ReferenceContext {
                include_declaration: true,
            },
        };
        let locs: Vec<lsp_types::Location> = client
            .request::<References>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?
            .unwrap_or_default();
        let resp = lsp_types::GotoDefinitionResponse::Array(locs);
        Ok(format_locations(&resp))
    }

    async fn action_hover(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = HoverParams {
            text_document_position_params: Self::position_params(uri, line),
            work_done_progress_params: Self::work_done(),
        };
        let hover: Option<lsp_types::Hover> = client
            .request::<HoverRequest>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?;
        Ok(hover
            .map(|h| match h.contents {
                lsp_types::HoverContents::Scalar(s) => marked_string_to_string(&s),
                lsp_types::HoverContents::Array(arr) => arr
                    .into_iter()
                    .map(|m| marked_string_to_string(&m))
                    .collect::<Vec<_>>()
                    .join("\n"),
                lsp_types::HoverContents::Markup(m) => m.value,
            })
            .unwrap_or_else(|| "(no hover info)".into()))
    }

    async fn action_rename(
        &self,
        file: &str,
        line: u32,
        new_name: String,
        apply: bool,
    ) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = RenameParams {
            text_document_position: Self::position_params(uri, line),
            new_name,
            work_done_progress_params: Self::work_done(),
        };
        let resp: Option<lsp_types::WorkspaceEdit> = client
            .request::<Rename>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?;
        Ok(match resp {
            None => "(no edits)".into(),
            Some(edit) => {
                if apply {
                    let summary = summarize_workspace_edit(&edit);
                    apply_workspace_edit(&edit)?;
                    format!("Rename applied: {summary}")
                } else {
                    format!("Rename preview:\n{}", summarize_workspace_edit(&edit))
                }
            }
        })
    }

    async fn action_symbols(&self, file: &str, query: Option<String>) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;

        // Workspace symbol search when a non-empty query is given.
        if let Some(q) = query
            && !q.is_empty()
        {
            let params = WorkspaceSymbolParams {
                query: q,
                work_done_progress_params: Self::work_done(),
                partial_result_params: lsp_types::PartialResultParams {
                    partial_result_token: None,
                },
            };
            let resp: Option<lsp_types::WorkspaceSymbolResponse> = client
                .request::<WorkspaceSymbolRequest>(params, REQUEST_TIMEOUT)
                .await
                .map_err(lsp_err)?;
            let symbols: Vec<lsp_types::SymbolInformation> = match resp {
                Some(lsp_types::WorkspaceSymbolResponse::Flat(arr)) => arr,
                Some(lsp_types::WorkspaceSymbolResponse::Nested(_)) => {
                    return Ok("(nested workspace symbols not supported)".into());
                }
                None => Vec::new(),
            };
            return Ok(format_symbols_flat(&symbols));
        }

        // Document symbols otherwise.
        let uri = Self::uri(&abs)?;
        let params = DocumentSymbolParams {
            text_document: TextDocumentIdentifier { uri },
            work_done_progress_params: Self::work_done(),
            partial_result_params: lsp_types::PartialResultParams {
                partial_result_token: None,
            },
        };
        let resp: Option<lsp_types::DocumentSymbolResponse> = client
            .request::<DocumentSymbolRequest>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?;
        Ok(match resp {
            Some(lsp_types::DocumentSymbolResponse::Flat(flat)) => format_symbols_flat(&flat),
            Some(lsp_types::DocumentSymbolResponse::Nested(_)) => {
                "(nested document symbols — showing top-level only)".into()
            }
            None => "(no symbols)".into(),
        })
    }

    async fn action_code_actions(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier { uri },
            range: Range {
                start: Position {
                    line: line.saturating_sub(1),
                    character: 0,
                },
                end: Position {
                    line: line.saturating_sub(1),
                    character: u32::MAX,
                },
            },
            context: CodeActionContext::default(),
            work_done_progress_params: Self::work_done(),
            partial_result_params: lsp_types::PartialResultParams {
                partial_result_token: None,
            },
        };
        let actions: Vec<lsp_types::CodeActionOrCommand> = client
            .request::<CodeActionRequest>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?
            .unwrap_or_default();
        Ok(format_code_actions(&actions))
    }

    async fn action_type_definition(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = Self::goto_params(uri, line);
        let resp: lsp_types::GotoDefinitionResponse = client
            .request::<GotoTypeDefinition>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?
            .unwrap_or(lsp_types::GotoDefinitionResponse::Array(vec![]));
        Ok(format_locations(&resp))
    }

    async fn action_implementation(&self, file: &str, line: u32) -> Result<String, ToolError> {
        let abs = self.resolve_file(file)?;
        let client = self.client_for(&abs).await?;
        let uri = Self::uri(&abs)?;
        let params = Self::goto_params(uri, line);
        let resp = client
            .request::<GotoImplementation>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?
            .unwrap_or(lsp_types::GotoDefinitionResponse::Array(vec![]));
        Ok(format_locations(&resp))
    }

    async fn action_file_rename(
        &self,
        old_path: &str,
        new_path: &str,
        apply: bool,
    ) -> Result<String, ToolError> {
        let old_abs = self.resolve_file(old_path)?;
        let client = self.client_for(&old_abs).await?;
        let old_uri = Self::uri(&old_abs)?;
        let new_uri = oxi_lsp::uri_for(&PathBuf::from(new_path))
            .ok_or_else(|| "invalid new_path for URI".to_string())?;
        let params = lsp_types::RenameFilesParams {
            files: vec![FileRename {
                old_uri: old_uri.to_string(),
                new_uri: new_uri.to_string(),
            }],
        };
        let edit: Option<lsp_types::WorkspaceEdit> = client
            .request::<WillRenameFiles>(params, REQUEST_TIMEOUT)
            .await
            .map_err(lsp_err)?;
        Ok(match edit {
            None => "(no willRenameFiles response)".into(),
            Some(e) => {
                if apply {
                    let summary = summarize_workspace_edit(&e);
                    apply_workspace_edit(&e)?;
                    format!("File rename applied: {summary}")
                } else {
                    format!("File rename preview:\n{}", summarize_workspace_edit(&e))
                }
            }
        })
    }
}

#[async_trait]
impl LspProvider for CliLspProvider {
    fn ensure_started_background<'a>(
        &'a self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
        // Lazy spawn happens on first request. Eager pre-warm is a
        // documented follow-up — the hook exists so future work can
        // pre-warm configured servers without changing call sites.
        Box::pin(async {})
    }

    fn ensure_ready<'a>(
        &'a self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send + 'a>> {
        // Lazy initialization happens on first request, so there's
        // nothing to "wait for" until at least one server has been
        // spawned. Once spawned, `LspClient::start` already awaits
        // `initialize` before returning, so we're effectively ready
        // as soon as a client exists.
        Box::pin(async { Ok(()) })
    }

    fn drain_diagnostics<'a>(
        &'a self,
        timeout: Duration,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<DiagnosticsSummary>> + Send + 'a>>
    {
        let live = self.manager.live_clients();
        Box::pin(async move {
            let mut merged = DiagnosticsSummary::default();
            for (_name, client) in live {
                if let Some(entries) = client.drain_diagnostics(timeout).await {
                    for entry in entries {
                        let counts = count_diagnostics(&entry.diagnostics);
                        merged.count += counts.total;
                        merged.errors += counts.errors;
                        merged.warnings += counts.warnings;
                        merged.entries.push(FileDiagnosticEntry {
                            uri: entry.uri,
                            path: String::new(),
                            diagnostics: entry.diagnostics,
                        });
                    }
                }
            }
            if merged.count == 0 {
                None
            } else {
                Some(merged)
            }
        })
    }

    fn read_diagnostics<'a>(
        &'a self,
        paths: &'a [PathBuf],
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<FileDiagnosticEntry>> + Send + 'a>>
    {
        Box::pin(async move {
            let mut out = Vec::new();
            for path in paths {
                let Ok(Some(client)) = self.manager.client_for_path(path).await else {
                    continue;
                };
                let Some(uri) = oxi_lsp::uri_for(path) else {
                    continue;
                };
                let uri_string = uri.to_string();
                for entry in client.read_diagnostics(&[uri_string]) {
                    out.push(FileDiagnosticEntry {
                        uri: entry.uri,
                        path: path.to_string_lossy().into_owned(),
                        diagnostics: entry.diagnostics,
                    });
                }
            }
            out
        })
    }

    fn notify_file_changed<'a>(
        &'a self,
        path: &'a std::path::Path,
        content: &'a str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
        Box::pin(async move {
            let Ok(Some(client)) = self.manager.client_for_path(path).await else {
                return;
            };
            let Some(uri) = oxi_lsp::uri_for(path) else {
                return;
            };
            // Best-effort didOpen with the new content. We send
            // didOpen rather than didChange because the agent's
            // write/edit tools have already flushed the new content
            // to disk; the server sees the file as freshly opened
            // with the latest text.
            let _ = client.notify::<lsp_types::notification::DidOpenTextDocument>(
                lsp_types::DidOpenTextDocumentParams {
                    text_document: lsp_types::TextDocumentItem {
                        uri,
                        language_id: path
                            .extension()
                            .and_then(|e| e.to_str())
                            .unwrap_or("plaintext")
                            .into(),
                        version: 1,
                        text: content.into(),
                    },
                },
            );
        })
    }

    fn execute_action<'a>(
        &'a self,
        action: &'a LspAction,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, ToolError>> + Send + 'a>>
    {
        Box::pin(async move {
            match action {
                LspAction::Status => {
                    let live = self.manager.live_clients();
                    let mut s = format!(
                        "LSP status: {} configured, {} live\n",
                        self.manager.server_count(),
                        live.len()
                    );
                    for (name, _) in &live {
                        s.push_str(&format!("  - {name}\n"));
                    }
                    Ok(s)
                }
                LspAction::Diagnostics { file } => self.action_diagnostics(file).await,
                LspAction::Definition { file, line, .. } => {
                    self.action_definition(file, *line).await
                }
                LspAction::References { file, line, .. } => {
                    self.action_references(file, *line).await
                }
                LspAction::Hover { file, line, .. } => self.action_hover(file, *line).await,
                LspAction::Rename {
                    file,
                    line,
                    new_name,
                    apply,
                    ..
                } => {
                    self.action_rename(file, *line, new_name.clone(), *apply)
                        .await
                }
                LspAction::Symbols { file, query, .. } => {
                    self.action_symbols(file, query.clone()).await
                }
                LspAction::CodeActions { file, line, .. } => {
                    self.action_code_actions(file, *line).await
                }
                LspAction::TypeDefinition { file, line, .. } => {
                    self.action_type_definition(file, *line).await
                }
                LspAction::Implementation { file, line, .. } => {
                    self.action_implementation(file, *line).await
                }
                LspAction::FileRename {
                    old_path,
                    new_path,
                    apply,
                } => self.action_file_rename(old_path, new_path, *apply).await,
            }
        })
    }
}

// ── formatting helpers ───────────────────────────────────────────

fn lsp_err(e: oxi_lsp::LspError) -> ToolError {
    format!("LSP request failed: {e}")
}

fn marked_string_to_string(s: &lsp_types::MarkedString) -> String {
    match s {
        lsp_types::MarkedString::String(s) => s.clone(),
        lsp_types::MarkedString::LanguageString(ls) => ls.value.clone(),
    }
}

fn format_locations(resp: &lsp_types::GotoDefinitionResponse) -> String {
    use lsp_types::GotoDefinitionResponse::*;
    let locs: Vec<lsp_types::Location> = match resp {
        Scalar(l) => vec![l.clone()],
        Array(arr) => arr.clone(),
        Link(links) => links
            .iter()
            .map(|l| lsp_types::Location {
                uri: l.target_uri.clone(),
                range: l.target_selection_range,
            })
            .collect(),
    };
    if locs.is_empty() {
        return "(no locations)".into();
    }
    locs.iter()
        .map(|l| {
            format!(
                "{}:{}:{}",
                l.uri.as_str(),
                l.range.start.line + 1,
                l.range.start.character + 1
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_symbols_flat(symbols: &[lsp_types::SymbolInformation]) -> String {
    if symbols.is_empty() {
        return "(no symbols)".into();
    }
    symbols
        .iter()
        .map(|s| {
            let kind = format!("{:?}", s.kind).to_lowercase();
            format!(
                "{} ({}) — {}:{}",
                s.name,
                kind,
                s.location.uri.as_str(),
                s.location.range.start.line + 1
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_code_actions(actions: &[lsp_types::CodeActionOrCommand]) -> String {
    if actions.is_empty() {
        return "(no code actions)".into();
    }
    actions
        .iter()
        .map(|a| match a {
            lsp_types::CodeActionOrCommand::CodeAction(ca) => {
                format!("CodeAction: {} ({:?})", ca.title, ca.kind)
            }
            lsp_types::CodeActionOrCommand::Command(cmd) => {
                format!("Command: {} ({})", cmd.title, cmd.command)
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn summarize_workspace_edit(edit: &lsp_types::WorkspaceEdit) -> String {
    let changes = edit.changes.as_ref().map(|c| c.len()).unwrap_or(0);
    let doc_changes = edit
        .document_changes
        .as_ref()
        .map(|c| match c {
            lsp_types::DocumentChanges::Edits(e) => e.len(),
            lsp_types::DocumentChanges::Operations(o) => o.len(),
        })
        .unwrap_or(0);
    format!("WorkspaceEdit: {changes} uri-changes, {doc_changes} document-changes")
}

/// Apply a `WorkspaceEdit` to disk.
///
/// Supports `documentChanges` (modern) and `changes` (legacy) formats.
/// Edits are applied bottom-to-top per file to preserve positions.
/// Uses atomic temp+rename writes (crash-safe).
fn apply_workspace_edit(edit: &lsp_types::WorkspaceEdit) -> Result<(), ToolError> {
    if let Some(changes) = &edit.document_changes {
        match changes {
            lsp_types::DocumentChanges::Edits(edits) => {
                for doc_edit in edits {
                    apply_text_document_edit(doc_edit)?;
                }
            }
            lsp_types::DocumentChanges::Operations(_ops) => {
                // Resource operations (create/delete/rename) are rare;
                // skip for now to keep the implementation focused.
            }
        }
    } else if let Some(changes) = &edit.changes {
        for (_uri, text_edits) in changes {
            let path = _uri
                .to_file_path()
                .map_err(|_| format!("invalid URI in changes: {_uri}"))?;
            let content = std::fs::read_to_string(&path)
                .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
            let has_trailing_newline = content.ends_with('\n');
            let mut lines: Vec<String> = content.lines().map(String::from).collect();

            let mut sorted = text_edits.clone();
            sorted.sort_by_key(|b| std::cmp::Reverse(b.range.start.line));

            for text_edit in &sorted {
                apply_text_edit_to_lines(&mut lines, text_edit);
            }

            let mut output = lines.join("\n");
            if has_trailing_newline {
                output.push('\n');
            }
            atomic_write(&path, &output)?;
        }
    }
    Ok(())
}

/// Atomic file write: write to a temp file in the same directory, then
/// rename. Crash-safe: a crash mid-write leaves the original intact.
fn atomic_write(path: &std::path::Path, content: &str) -> Result<(), ToolError> {
    let dir = path.parent().unwrap_or(std::path::Path::new("."));
    let mut tmp = dir.to_path_buf();
    tmp.push(format!(
        ".tmp.{}",
        path.file_name().unwrap_or_default().to_string_lossy()
    ));
    std::fs::write(&tmp, content)
        .map_err(|e| format!("failed to write temp {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, path).map_err(|e| {
        format!(
            "failed to rename {} -> {}: {e}",
            tmp.display(),
            path.display()
        )
    })?;
    Ok(())
}

/// Apply a single `TextDocumentEdit` (modern format).
fn apply_text_document_edit(doc_edit: &lsp_types::TextDocumentEdit) -> Result<(), ToolError> {
    let uri = &doc_edit.text_document.uri;
    let path = uri
        .to_file_path()
        .map_err(|_| format!("invalid URI: {uri}"))?;
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
    let has_trailing_newline = content.ends_with('\n');
    let mut lines: Vec<String> = content.lines().map(String::from).collect();

    let mut edits: Vec<&lsp_types::TextEdit> = Vec::with_capacity(doc_edit.edits.len());
    for edit in &doc_edit.edits {
        match edit {
            lsp_types::OneOf::Left(text_edit) => edits.push(text_edit),
            lsp_types::OneOf::Right(annotated) => edits.push(&annotated.text_edit),
        }
    }

    edits.sort_by_key(|b| std::cmp::Reverse(b.range.start.line));

    for text_edit in edits {
        apply_text_edit_to_lines(&mut lines, text_edit);
    }

    let mut output = lines.join("\n");
    if has_trailing_newline {
        output.push('\n');
    }
    atomic_write(&path, &output)?;
    Ok(())
}

/// Convert an LSP UTF-16 code-unit offset to a Rust byte offset.
///
/// LSP uses UTF-16 code units for character positions (per the spec),
/// while Rust uses byte indices. Direct byte slicing with an LSP
/// offset would panic on non-ASCII characters.
fn u16_to_byte_offset(line: &str, u16_offset: usize) -> usize {
    let mut u16_pos = 0;
    for (byte_off, c) in line.char_indices() {
        if u16_pos >= u16_offset {
            return byte_off;
        }
        u16_pos += c.len_utf16();
    }
    line.len()
}

/// Apply a single `TextEdit` to a mutable line buffer (bottom-to-top safe).
///
/// Converts LSP UTF-16 code-unit offsets to byte offsets before slicing
/// to avoid panicking on non-ASCII characters.
fn apply_text_edit_to_lines(lines: &mut Vec<String>, edit: &lsp_types::TextEdit) {
    let start_line = edit.range.start.line as usize;
    let end_line = edit.range.end.line as usize;

    if start_line >= lines.len() {
        lines.push(edit.new_text.clone());
        return;
    }

    if start_line == end_line {
        let line = &lines[start_line];
        let start_col = u16_to_byte_offset(line, edit.range.start.character as usize);
        let end_col = u16_to_byte_offset(line, edit.range.end.character as usize);
        let end_col = end_col.min(line.len());
        let before = &line[..start_col.min(line.len())];
        let after = &line[end_col..];
        let mut new_line = String::with_capacity(before.len() + edit.new_text.len() + after.len());
        new_line.push_str(before);
        new_line.push_str(&edit.new_text);
        new_line.push_str(after);
        lines[start_line] = new_line;
    } else if end_line < lines.len() {
        let start_col = u16_to_byte_offset(&lines[start_line], edit.range.start.character as usize);
        let end_col = u16_to_byte_offset(&lines[end_line], edit.range.end.character as usize);
        let before = lines[start_line][..start_col.min(lines[start_line].len())].to_string();
        let after = lines[end_line][end_col.min(lines[end_line].len())..].to_string();
        let mut new_line = String::with_capacity(before.len() + edit.new_text.len() + after.len());
        new_line.push_str(&before);
        new_line.push_str(&edit.new_text);
        new_line.push_str(&after);
        let _ = lines.splice(start_line..=end_line, std::iter::once(new_line));
    }
}

fn summarize_entries(path: &std::path::Path, entries: &[oxi_lsp::PublishedDiagnostics]) -> String {
    if entries.is_empty() {
        return format!("{}: no diagnostics", path.display());
    }
    let mut out = String::new();
    for entry in entries {
        let counts = count_diagnostics(&entry.diagnostics);
        out.push_str(&format!(
            "{}: {} diagnostics ({} errors, {} warnings)\n",
            entry.uri, counts.total, counts.errors, counts.warnings
        ));
    }
    out
}

#[derive(Default)]
struct DiagnosticCounts {
    total: usize,
    errors: usize,
    warnings: usize,
}

fn count_diagnostics(value: &serde_json::Value) -> DiagnosticCounts {
    let mut c = DiagnosticCounts::default();
    if let Some(arr) = value.as_array() {
        c.total = arr.len();
        for d in arr {
            if let Some(sev) = d.get("severity").and_then(|v| v.as_u64()) {
                match sev {
                    1 => c.errors += 1,
                    2 => c.warnings += 1,
                    _ => {}
                }
            }
        }
    }
    c
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── u16_to_byte_offset ───────────────────────────────────────────

    #[test]
    fn u16_offset_ascii_returns_same() {
        assert_eq!(u16_to_byte_offset("hello", 0), 0);
        assert_eq!(u16_to_byte_offset("hello", 3), 3);
        assert_eq!(u16_to_byte_offset("hello", 5), 5);
    }

    #[test]
    fn u16_offset_beyond_line_returns_len() {
        assert_eq!(u16_to_byte_offset("hi", 100), 2);
        assert_eq!(u16_to_byte_offset("", 5), 0);
    }

    #[test]
    fn u16_offset_korean_converts_correctly() {
        // 한글 (Hangul) is in BMP (U+AC00-U+D7AF) = 1 UTF-16 unit each
        // "안녕하세요" = 5 chars = 5 UTF-16 units, each 3 UTF-8 bytes = 15 bytes
        let s = "안녕하세요";
        assert_eq!(u16_to_byte_offset(s, 0), 0); // '안'
        assert_eq!(u16_to_byte_offset(s, 1), 3); // '녕'
        assert_eq!(u16_to_byte_offset(s, 2), 6); // '하'
        assert_eq!(u16_to_byte_offset(s, 5), 15); // end
    }

    #[test]
    fn u16_offset_mixed_ascii_korean() {
        // "abc안녕" = 'a'(1U16,1byte) 'b'(1,1) 'c'(1,1) '안'(1U16,3byte) '녕'(1U16,3byte)
        // UTF-16 positions: 0→0, 1→1, 2→2, 3→3, 4→6, 5→9(end)
        let s = "abc안녕";
        assert_eq!(u16_to_byte_offset(s, 0), 0); // 'a'
        assert_eq!(u16_to_byte_offset(s, 2), 2); // 'c'
        assert_eq!(u16_to_byte_offset(s, 3), 3); // '안' start (byte 3)
        assert_eq!(u16_to_byte_offset(s, 4), 6); // '녕' start (byte 6)
        assert_eq!(u16_to_byte_offset(s, 5), 9); // end
    }

    // ── apply_text_edit_to_lines ─────────────────────────────────────

    fn make_edit(
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
        new_text: &str,
    ) -> lsp_types::TextEdit {
        lsp_types::TextEdit {
            range: lsp_types::Range {
                start: lsp_types::Position {
                    line: start_line,
                    character: start_char,
                },
                end: lsp_types::Position {
                    line: end_line,
                    character: end_char,
                },
            },
            new_text: new_text.to_string(),
        }
    }

    #[test]
    fn apply_single_line_replace_mid() {
        let mut lines = vec!["hello world".to_string()];
        let edit = make_edit(0, 6, 0, 11, "there");
        apply_text_edit_to_lines(&mut lines, &edit);
        assert_eq!(lines, vec!["hello there"]);
    }

    #[test]
    fn apply_single_line_insert() {
        let mut lines = vec!["ab".to_string()];
        let edit = make_edit(0, 1, 0, 1, "XX");
        apply_text_edit_to_lines(&mut lines, &edit);
        assert_eq!(lines, vec!["aXXb"]);
    }

    #[test]
    fn apply_multi_line_replace() {
        let mut lines = vec!["aaa".to_string(), "bbb".to_string(), "ccc".to_string()];
        // Replace from line 0 char 1 to line 2 char 2 with "X\nY"
        // After splice: one string "aX\nYc" replaces 3 lines.
        // The join will produce two lines separated by the embedded \n.
        let edit = make_edit(0, 1, 2, 2, "X\nY");
        apply_text_edit_to_lines(&mut lines, &edit);
        assert_eq!(
            lines.len(),
            1,
            "splice merges replaced range into one string"
        );
        assert_eq!(lines[0], "aX\nYc", "embedded newline in new_text");
        // When joined, the embedded \n produces correct vertical result
        let result = lines.join("\n");
        assert_eq!(result, "aX\nYc");
    }

    #[test]
    fn apply_edit_beyond_eof_appends() {
        let mut lines = vec!["a".to_string()];
        let edit = make_edit(5, 0, 5, 0, "new line");
        apply_text_edit_to_lines(&mut lines, &edit);
        assert_eq!(lines, vec!["a".to_string(), "new line".to_string()]);
    }

    #[test]
    fn apply_edit_korean_column() {
        let mut lines = vec!["abc안녕def".to_string()];
        // '안' is at UTF-16 offset 3, '녕' at 4, 'd' at 5 = byte 9
        // Replace from '안' (U16=3) to 'd' (U16=5) with "X"
        let edit = make_edit(0, 3, 0, 5, "X");
        apply_text_edit_to_lines(&mut lines, &edit);
        assert_eq!(lines, vec!["abcXdef"]);
    }

    #[test]
    fn apply_edit_preserves_trailing_newline() {
        let text = "line1\nline2\n";
        let edit = lsp_types::TextEdit {
            range: lsp_types::Range {
                start: lsp_types::Position {
                    line: 0,
                    character: 0,
                },
                end: lsp_types::Position {
                    line: 0,
                    character: 5,
                },
            },
            new_text: "LINE1".to_string(),
        };

        // Simulate what apply_text_document_edit does
        let has_trailing_newline = text.ends_with('\n');
        let mut lines: Vec<String> = text.lines().map(String::from).collect();
        apply_text_edit_to_lines(&mut lines, &edit);
        let mut output = lines.join("\n");
        if has_trailing_newline {
            output.push('\n');
        }
        assert_eq!(output, "LINE1\nline2\n");
    }

    #[test]
    fn apply_sorts_bottom_to_top() {
        // When two edits touch the same file, bottom-to-top order preserves
        // positions. This test verifies the sort used in apply_text_document_edit.
        let text = "first\nsecond\nthird";
        let mut lines: Vec<String> = text.lines().map(String::from).collect();

        // Edit line 0 first, then line 2 — but apply bottom-to-top
        let mut edits = vec![
            make_edit(0, 0, 0, 5, "FIRST"), // line 0: "first" → "FIRST"
            make_edit(2, 0, 2, 5, "THIRD"), // line 2: "third" → "THIRD"
        ];
        edits.sort_by_key(|b| std::cmp::Reverse(b.range.start.line));

        for edit in &edits {
            apply_text_edit_to_lines(&mut lines, edit);
        }

        assert_eq!(lines, vec!["FIRST", "second", "THIRD"]);
    }
}