scope-cli 0.9.2

Code intelligence CLI for LLM coding agents — structural navigation, dependency graphs, and semantic search without reading full source files
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
//! Human-readable output formatting for all Scope commands.
//!
//! Rules:
//! - Separator line uses `─` (U+2500), never `-` or `=`
//! - File paths always use forward slashes, even on Windows
//! - Line ranges formatted as `start-end`
//! - Caller counts in square brackets: `[11 callers]`, `[internal]`
//! - Similarity scores always 2 decimal places: `0.91`

use std::collections::HashMap;

use crate::commands::entrypoints::EntrypointInfo;
use crate::commands::flow::FlowPath;
use crate::commands::map::{CoreSymbol, DirStats, MapStats};
use crate::core::graph::{
    CallerInfo, ClassRelationships, Dependency, ImpactResult, Reference, Symbol, TraceResult,
};
use crate::core::searcher::SearchResult;

/// The separator line used between header and body in all command output.
pub const SEPARATOR: &str =
    "──────────────────────────────────────────────────────────────────────────────";

/// Normalize a file path to always use forward slashes in output.
pub fn normalize_path(path: &str) -> String {
    path.replace('\\', "/")
}

/// Format a line range as `start-end`, or just `start` if start == end.
pub fn format_line_range(start: u32, end: u32) -> String {
    if start == end {
        format!("{start}")
    } else {
        format!("{start}-{end}")
    }
}

/// Format the header line: `name  kind  file:line_range`
fn print_header(symbol: &Symbol) {
    let path = normalize_path(&symbol.file_path);
    let line_range = format_line_range(symbol.line_start, symbol.line_end);
    println!(
        "{:<50}{}  {}:{}",
        symbol.name, symbol.kind, path, line_range
    );
    println!("{SEPARATOR}");
}

/// Print a class sketch.
///
/// Format:
/// ```text
/// PaymentService                                    class  src/payments/service.ts:12
/// ──────────────────────────────────────────────────────────────────────────────
/// deps:     StripeClient, UserRepository, Logger
/// extends:  BaseService
/// implements: IPaymentService
///
/// methods:
///   processPayment(amount: Decimal, userId: string) → PaymentResult       [11 callers]
///   validateCard(card: CardDetails) → ValidationResult                     [internal]
///
/// fields:
///   private client: StripeClient
/// ```
pub fn print_class_sketch(
    symbol: &Symbol,
    methods: &[Symbol],
    caller_counts: &HashMap<String, usize>,
    relationships: &ClassRelationships,
    limit: usize,
    show_docs: bool,
) {
    print_header(symbol);

    // Dependencies line
    if !relationships.dependencies.is_empty() {
        println!("deps:     {}", relationships.dependencies.join(", "));
    }

    // Extends line
    if !relationships.extends.is_empty() {
        println!("extends:  {}", relationships.extends.join(", "));
    }

    // Implements line
    if !relationships.implements.is_empty() {
        println!("implements: {}", relationships.implements.join(", "));
    }

    // Separate sections: methods and fields
    let (method_syms, field_syms): (Vec<&Symbol>, Vec<&Symbol>) = methods
        .iter()
        .partition(|m| m.kind == "method" || m.kind == "function");

    // Methods section
    if !method_syms.is_empty() {
        println!();
        println!("methods:");
        let display_methods = if method_syms.len() > limit {
            &method_syms[..limit]
        } else {
            &method_syms
        };

        for method in display_methods {
            // Show first line of docstring if available and docs are enabled
            if show_docs {
                if let Some(ref doc) = method.docstring {
                    let first_line = doc.lines().next().unwrap_or("").trim();
                    let clean = first_line
                        .trim_start_matches("///")
                        .trim_start_matches("//")
                        .trim_start_matches("/**")
                        .trim_start_matches("*")
                        .trim_start_matches("*/")
                        .trim();
                    if !clean.is_empty() {
                        println!("  /// {clean}");
                    }
                }
            }

            let sig = method_display_line(method);
            let count = caller_counts.get(&method.id).copied().unwrap_or(0);
            let count_label = if count > 0 {
                format!("[{count} caller{}]", if count == 1 { "" } else { "s" })
            } else {
                "[internal]".to_string()
            };
            // Right-align the caller count
            let padding = SEPARATOR
                .chars()
                .count()
                .saturating_sub(2 + sig.chars().count() + count_label.chars().count());
            println!(
                "  {sig}{:>width$}",
                count_label,
                width = padding + count_label.len()
            );
        }

        if method_syms.len() > limit {
            println!(
                "  ... {} more (use --limit to show more)",
                method_syms.len() - limit
            );
        }
    }

    // Fields section (properties)
    let field_syms: Vec<&Symbol> = field_syms
        .into_iter()
        .filter(|s| s.kind == "property")
        .collect();

    if !field_syms.is_empty() {
        println!();
        println!("fields:");
        for field in &field_syms {
            let sig = field.signature.as_deref().unwrap_or(&field.name);
            println!("  {sig}");
        }
    }
}

/// Print a method/function sketch.
///
/// Format:
/// ```text
/// processPayment                        method  src/payments/service.ts:34-67
/// ──────────────────────────────────────────────────────────────────────────────
/// signature:  (amount: Decimal, userId: string) → PaymentResult
/// calls:      validateCard, repo.findUser
/// called by:  OrderController.checkout [x3]
/// ```
pub fn print_method_sketch(
    symbol: &Symbol,
    outgoing_calls: &[String],
    incoming_callers: &[CallerInfo],
) {
    print_header(symbol);

    // Language-specific enrichment line (annotations, decorators, receiver)
    let enrichment = extract_enrichment_prefix(&symbol.language, &symbol.metadata);
    if !enrichment.is_empty() {
        println!("{enrichment}");
    }

    // Modifiers line (only if any non-default modifiers exist)
    let modifiers = extract_modifiers(&symbol.metadata);
    if !modifiers.is_empty() {
        println!("{}", modifiers.join(" "));
    }

    // Signature line
    if let Some(sig) = &symbol.signature {
        println!("signature:  {sig}");
    }

    // Calls line
    if !outgoing_calls.is_empty() {
        println!("calls:      {}", outgoing_calls.join(", "));
    }

    // Called by line
    if !incoming_callers.is_empty() {
        let caller_parts: Vec<String> = incoming_callers
            .iter()
            .map(|c| {
                if c.count > 1 {
                    format!("{} [x{}]", c.name, c.count)
                } else {
                    c.name.clone()
                }
            })
            .collect();
        println!("called by:  {}", caller_parts.join(", "));
    }
}

/// Print an interface sketch.
///
/// Format:
/// ```text
/// IPaymentService                          interface  src/types/payment.ts:4
/// ──────────────────────────────────────────────────────────────────────────────
/// implemented by:  PaymentService
///
/// methods:
///   processPayment(amount: Decimal, userId: string) → Promise<PaymentResult>
/// ```
pub fn print_interface_sketch(
    symbol: &Symbol,
    methods: &[Symbol],
    implementors: &[String],
    limit: usize,
) {
    print_header(symbol);

    // Implemented by
    if !implementors.is_empty() {
        println!("implemented by:  {}", implementors.join(", "));
    }

    // Methods section
    if !methods.is_empty() {
        println!();
        println!("methods:");
        let display_methods = if methods.len() > limit {
            &methods[..limit]
        } else {
            methods
        };

        for method in display_methods {
            let sig = method_display_line(method);
            println!("  {sig}");
        }

        if methods.len() > limit {
            println!(
                "  ... {} more (use --limit to show more)",
                methods.len() - limit
            );
        }
    }
}

/// Print a file-level sketch.
///
/// Format:
/// ```text
/// src/payments/service.ts
/// ──────────────────────────────────────────────────────────────────────────────
///   PaymentService          class     12-89    [11 callers]
///   processPayment          method    34-67    [11 callers]
/// ```
pub fn print_file_sketch(
    file_path: &str,
    symbols: &[Symbol],
    caller_counts: &HashMap<String, usize>,
) {
    let path = normalize_path(file_path);
    println!("{path}");
    println!("{SEPARATOR}");

    for sym in symbols {
        let line_range = format_line_range(sym.line_start, sym.line_end);
        let count = caller_counts.get(&sym.id).copied().unwrap_or(0);
        let count_label = if count > 0 {
            format!("[{count} caller{}]", if count == 1 { "" } else { "s" })
        } else {
            "[internal]".to_string()
        };
        println!(
            "  {:<24}{:<10}{:<9}{}",
            sym.name, sym.kind, line_range, count_label
        );
    }
}

/// Print an enum sketch — variants and caller count.
///
/// Format:
/// ```text
/// PaymentStatus                                     enum  src/payments/types.ts:1-6
/// ──────────────────────────────────────────────────────────────────────────────
/// variants:
///   Active
///   Inactive
///   Pending
///
/// [3 callers]
/// ```
pub fn print_enum_sketch(symbol: &Symbol, variants: &[&Symbol], caller_count: usize) {
    print_header(symbol);

    if !variants.is_empty() {
        println!("variants:");
        for v in variants {
            // Show signature (data shape) if available, otherwise just the name
            let display = v.signature.as_deref().unwrap_or(&v.name);
            println!("  {display}");
        }
    }

    println!();
    if caller_count > 0 {
        println!(
            "[{caller_count} caller{}]",
            if caller_count == 1 { "" } else { "s" }
        );
    } else {
        println!("[internal]");
    }
}

/// Print a generic symbol sketch (const, type, struct).
///
/// Falls back to a simple header + signature.
pub fn print_generic_sketch(symbol: &Symbol) {
    print_header(symbol);

    if let Some(sig) = &symbol.signature {
        println!("signature:  {sig}");
    }
}

/// Build the display string for a method in a class/interface listing.
///
/// Uses the signature if available, otherwise just the name.
/// Prepends any modifiers from metadata that are not already present in the signature.
/// Adds language-specific enrichments: Java annotations, Python decorators, Go receivers.
fn method_display_line(method: &Symbol) -> String {
    let sig = method.signature.as_deref().unwrap_or(&method.name);

    let modifiers = extract_modifiers(&method.metadata);
    let base = if modifiers.is_empty() {
        sig.to_string()
    } else {
        // Only prepend modifiers not already present in the signature text
        let missing: Vec<&str> = modifiers
            .iter()
            .filter(|m| !sig.contains(m.as_str()))
            .map(|m| m.as_str())
            .collect();

        if missing.is_empty() {
            sig.to_string()
        } else {
            format!("{} {}", missing.join(" "), sig)
        }
    };

    // Add language-specific enrichment prefix
    let enrichment = extract_enrichment_prefix(&method.language, &method.metadata);
    if enrichment.is_empty() {
        base
    } else {
        format!("{enrichment} {base}")
    }
}

/// Extract a language-specific enrichment prefix from a symbol's metadata JSON.
///
/// - **Java**: annotations (e.g. `@Override`, `@Deprecated`)
/// - **Python**: decorators (e.g. `@staticmethod`, `@property`)
/// - **Go**: receiver type (e.g. `(s *Server)`)
///
/// Returns an empty string if the language has no enrichments or parsing fails.
fn extract_enrichment_prefix(language: &str, metadata_json: &str) -> String {
    let parsed: serde_json::Value = match serde_json::from_str(metadata_json) {
        Ok(v) => v,
        Err(_) => return String::new(),
    };

    match language {
        "java" => {
            // Show annotations as @Name prefixes
            if let Some(annotations) = parsed.get("annotations").and_then(|v| v.as_array()) {
                let prefixes: Vec<String> = annotations
                    .iter()
                    .filter_map(|a| a.as_str())
                    .filter(|a| !a.is_empty())
                    .map(|a| format!("@{a}"))
                    .collect();
                if !prefixes.is_empty() {
                    return prefixes.join(" ");
                }
            }
            String::new()
        }
        "python" => {
            // Show decorators as @name prefixes
            if let Some(decorators) = parsed.get("decorators").and_then(|v| v.as_array()) {
                let prefixes: Vec<String> = decorators
                    .iter()
                    .filter_map(|d| d.as_str())
                    .filter(|d| !d.is_empty())
                    .map(|d| format!("@{d}"))
                    .collect();
                if !prefixes.is_empty() {
                    return prefixes.join(" ");
                }
            }
            String::new()
        }
        "go" => {
            // Show receiver type as (name *Type) or (name Type) prefix
            if let Some(receiver) = parsed.get("receiver").and_then(|v| v.as_str()) {
                if !receiver.is_empty() {
                    let is_pointer = parsed
                        .get("is_pointer_receiver")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);
                    // Extract a short variable name from the receiver type
                    let var_name = receiver
                        .chars()
                        .next()
                        .map(|c| c.to_lowercase().to_string())
                        .unwrap_or_default();
                    let type_display = if is_pointer {
                        format!("*{receiver}")
                    } else {
                        receiver.to_string()
                    };
                    return format!("({var_name} {type_display})");
                }
            }
            String::new()
        }
        _ => String::new(),
    }
}

/// Extract display-worthy modifiers from a symbol's metadata JSON.
///
/// Returns modifiers that differ from defaults (public is default, so omit it).
/// Example output: `vec!["async", "private", "static"]`
fn extract_modifiers(metadata_json: &str) -> Vec<String> {
    let parsed: serde_json::Value = match serde_json::from_str(metadata_json) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };

    let mut mods = Vec::new();

    // Access modifier (only show non-public)
    if let Some(access) = parsed.get("access").and_then(|v| v.as_str()) {
        match access {
            "private" | "protected" | "internal" | "protected internal" => {
                mods.push(access.to_string());
            }
            _ => {} // "public" is default, don't show
        }
    }

    if parsed
        .get("is_async")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        mods.push("async".to_string());
    }

    if parsed
        .get("is_static")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        mods.push("static".to_string());
    }

    if parsed
        .get("is_abstract")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        mods.push("abstract".to_string());
    }

    if parsed
        .get("is_virtual")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        mods.push("virtual".to_string());
    }

    if parsed
        .get("is_override")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        mods.push("override".to_string());
    }

    mods
}

/// Print references to a function or method (flat list).
///
/// Format:
/// ```text
/// processPayment — 11 references
/// ──────────────────────────────────────────────────────────────────────────────
/// src/controllers/order.ts:89       OrderController.checkout
/// src/controllers/order.ts:134      OrderController.retryPayment
/// ... 8 more (use --limit to show more)
/// ```
pub fn print_refs(symbol_name: &str, refs: &[Reference], total: usize) {
    println!(
        "{} \u{2014} {} reference{}",
        symbol_name,
        total,
        if total == 1 { "" } else { "s" }
    );
    println!("{SEPARATOR}");

    for r in refs {
        let path = normalize_path(&r.file_path);
        let location = if let Some(line) = r.line {
            format!("{path}:{line}")
        } else {
            path
        };
        let display_text = r.snippet_line.as_deref().unwrap_or(&r.context);
        let truncated_text = truncate_str(display_text.trim(), 80);
        println!("{:<40}{}", location, truncated_text);

        // Show multi-line context if available
        if let Some(ref snippet) = r.snippet {
            print_snippet_context(snippet, r.line);
        }
    }

    if refs.len() < total {
        println!("... {} more (use --limit to show more)", total - refs.len());
    }
}

/// Print references to a class symbol, grouped by kind.
///
/// Format:
/// ```text
/// PaymentService — 18 references
/// ──────────────────────────────────────────────────────────────────────────────
/// instantiated (4):
///   src/controllers/order.ts:23       new PaymentService(config)
///   ...
///
/// extended (1):
///   src/payments/stripe-service.ts:4  class StripeService extends PaymentService
/// ```
pub fn print_refs_grouped(symbol_name: &str, groups: &[(String, Vec<Reference>)], total: usize) {
    println!(
        "{} \u{2014} {} reference{}",
        symbol_name,
        total,
        if total == 1 { "" } else { "s" }
    );
    println!("{SEPARATOR}");

    let mut shown = 0;
    for (kind, refs) in groups {
        let kind_label = humanize_edge_kind(kind);
        println!("{kind_label} ({}):", refs.len());
        for r in refs {
            let path = normalize_path(&r.file_path);
            let location = if let Some(line) = r.line {
                format!("{path}:{line}")
            } else {
                path
            };
            let display_text = r.snippet_line.as_deref().unwrap_or(&r.context);
            let truncated_text = truncate_str(display_text.trim(), 80);
            println!("  {:<38}{}", location, truncated_text);

            // Show multi-line context if available
            if let Some(ref snippet) = r.snippet {
                print_snippet_context(snippet, r.line);
            }
        }
        shown += refs.len();
        println!();
    }

    if shown < total {
        println!("... {} more (use --limit to show more)", total - shown);
    }
}

/// Print file-level references.
///
/// Same as `print_refs` but with the file path as header.
pub fn print_file_refs(file_path: &str, refs: &[Reference], total: usize) {
    let path = normalize_path(file_path);
    println!(
        "{} \u{2014} {} reference{}",
        path,
        total,
        if total == 1 { "" } else { "s" }
    );
    println!("{SEPARATOR}");

    for r in refs {
        let rpath = normalize_path(&r.file_path);
        let location = if let Some(line) = r.line {
            format!("{rpath}:{line}")
        } else {
            rpath
        };
        let display_text = r.snippet_line.as_deref().unwrap_or(&r.context);
        let truncated_text = truncate_str(display_text.trim(), 80);
        println!("{:<40}{}", location, truncated_text);

        // Show multi-line context if available
        if let Some(ref snippet) = r.snippet {
            print_snippet_context(snippet, r.line);
        }
    }

    if refs.len() < total {
        println!("... {} more (use --limit to show more)", total - refs.len());
    }
}

/// Print dependencies of a symbol.
///
/// Format:
/// ```text
/// PaymentService — direct dependencies
/// ──────────────────────────────────────────────────────────────────────────────
/// imports:
///   StripeClient            src/clients/stripe.ts
///   Decimal                 (external)
///
/// calls:
///   stripe.charges.create   (external)
/// ```
pub fn print_deps(symbol_name: &str, deps: &[Dependency], max_depth: usize) {
    let depth_label = if max_depth <= 1 {
        "direct dependencies".to_string()
    } else {
        format!("transitive dependencies (depth {max_depth})")
    };

    println!("{} \u{2014} {}", symbol_name, depth_label);
    println!("{SEPARATOR}");

    if deps.is_empty() {
        println!("(no dependencies found)");
        return;
    }

    // Group by kind
    let mut groups: Vec<(String, Vec<&Dependency>)> = Vec::new();
    for dep in deps {
        if let Some(group) = groups.iter_mut().find(|(k, _)| *k == dep.kind) {
            group.1.push(dep);
        } else {
            let kind = dep.kind.clone();
            groups.push((kind, vec![dep]));
        }
    }

    for (kind, group_deps) in &groups {
        // Check if all deps in this group are external
        let all_external = group_deps.iter().all(|d| d.is_external);
        let kind_label = if all_external {
            format!("{kind} (external):")
        } else {
            format!("{kind}:")
        };
        println!("{kind_label}");

        for dep in group_deps {
            if dep.is_external {
                println!("  {:<24}(external)", dep.name);
            } else if let Some(fp) = &dep.file_path {
                let path = normalize_path(fp);
                println!("  {:<24}{}", dep.name, path);
            } else {
                println!("  {}", dep.name);
            }
        }

        println!();
    }
}

/// Print file-level dependencies.
pub fn print_file_deps(file_path: &str, deps: &[Dependency], max_depth: usize) {
    let path = normalize_path(file_path);
    let depth_label = if max_depth <= 1 {
        "direct dependencies".to_string()
    } else {
        format!("transitive dependencies (depth {max_depth})")
    };

    println!("{} \u{2014} {}", path, depth_label);
    println!("{SEPARATOR}");

    if deps.is_empty() {
        println!("(no dependencies found)");
        return;
    }

    // Group by kind
    let mut groups: Vec<(String, Vec<&Dependency>)> = Vec::new();
    for dep in deps {
        if let Some(group) = groups.iter_mut().find(|(k, _)| *k == dep.kind) {
            group.1.push(dep);
        } else {
            let kind = dep.kind.clone();
            groups.push((kind, vec![dep]));
        }
    }

    for (kind, group_deps) in &groups {
        let all_external = group_deps.iter().all(|d| d.is_external);
        let kind_label = if all_external {
            format!("{kind} (external):")
        } else {
            format!("{kind}:")
        };
        println!("{kind_label}");

        for dep in group_deps {
            if dep.is_external {
                println!("  {:<24}(external)", dep.name);
            } else if let Some(fp) = &dep.file_path {
                let fpath = normalize_path(fp);
                println!("  {:<24}{}", dep.name, fpath);
            } else {
                println!("  {}", dep.name);
            }
        }

        println!();
    }
}

/// Print an impact analysis result.
///
/// Format:
/// ```text
/// Impact analysis: processPayment
/// ──────────────────────────────────────────────────────────────────────────────
/// Direct callers (11):
///   OrderController.checkout          src/controllers/order.ts
///   SubscriptionService.renew         src/services/subscription.ts
///   ... (9 more)
///
/// Second-degree (3):
///   src/api/routes/checkout.ts        → imports OrderController
///
/// Test files affected: 6
///   tests/unit/payment.test.ts
///   tests/unit/order.test.ts
///   ... (4 more)
/// ```
pub fn print_impact(symbol_name: &str, result: &ImpactResult) {
    println!("Impact analysis: {symbol_name}");
    println!("{SEPARATOR}");

    if result.nodes_by_depth.is_empty() && result.test_files.is_empty() {
        println!("(no impact detected)");
        return;
    }

    for (depth, nodes) in &result.nodes_by_depth {
        let depth_label = impact_depth_label(*depth);
        println!("{depth_label} ({}):", nodes.len());

        let max_display = 10;
        let display_nodes = if nodes.len() > max_display {
            &nodes[..max_display]
        } else {
            nodes
        };

        for node in display_nodes {
            let path = normalize_path(&node.file_path);
            println!("  {:<40}{}", node.name, path);
        }

        if nodes.len() > max_display {
            println!("  ... ({} more)", nodes.len() - max_display);
        }

        println!();
    }

    if !result.test_files.is_empty() {
        println!("Test files affected: {}", result.test_files.len());

        let max_display = 10;
        let display_tests = if result.test_files.len() > max_display {
            &result.test_files[..max_display]
        } else {
            &result.test_files
        };

        for node in display_tests {
            let path = normalize_path(&node.file_path);
            println!("  {path}");
        }

        if result.test_files.len() > max_display {
            println!("  ... ({} more)", result.test_files.len() - max_display);
        }
    }
}

/// Print trace results showing call paths from entry points to the target.
///
/// Format:
/// ```text
/// processRenewal — 2 entry paths
/// ──────────────────────────────────────────────────────────────────────────────
/// Path 1: SubscriptionController.renewSubscription
///   └─→ SubscriptionService.processRenewal          src/services/sub.ts:72
///
/// Path 2: SubscriptionRenewalWorker.autoRenewDue
///   └─→ SubscriptionService.processRenewal          src/services/sub.ts:72
/// ```
pub fn print_trace(symbol_name: &str, result: &TraceResult, total: usize, truncated: bool) {
    let path_count = result.paths.len();
    let path_word = if path_count == 1 { "path" } else { "paths" };

    let display_count = if truncated { total } else { path_count };
    println!(
        "{} \u{2014} {} entry {}",
        symbol_name, display_count, path_word
    );
    println!("{SEPARATOR}");

    if result.paths.is_empty() {
        println!("(no entry paths found)");
        return;
    }

    for (i, call_path) in result.paths.iter().enumerate() {
        if call_path.steps.is_empty() {
            continue;
        }

        // First step: the entry point (no arrow prefix)
        let entry = &call_path.steps[0];
        let entry_name = entry.symbol_name.clone();
        println!("Path {}: {}", i + 1, entry_name);

        // Subsequent steps: indented with └─→
        for (step_idx, step) in call_path.steps.iter().enumerate().skip(1) {
            let indent = "  ".repeat(step_idx);
            let step_name = step.symbol_name.clone();
            let path = normalize_path(&step.file_path);
            let location = format!("{path}:{}", step.line);
            println!(
                "{indent}\u{2514}\u{2500}\u{2192} {:<40}{}",
                step_name, location
            );
        }

        // Blank line between paths (but not after the last one)
        if i < path_count - 1 {
            println!();
        }
    }

    if truncated {
        println!(
            "... {} more paths (use --limit to show more)",
            total - path_count
        );
    }
}

/// Print flow paths between two symbols.
///
/// Format:
/// ```text
/// PaymentService → OrderProcessor → NotificationService
///   src/payments/service.ts:15  →  src/orders/processor.ts:42  →  src/notifications/service.ts:22
///
/// ─ 2 paths found (depth limit: 10)
/// ```
pub fn print_flow(start: &str, end: &str, paths: &[FlowPath], total: usize, depth_limit: usize) {
    if paths.is_empty() {
        println!(
            "No path found from {} to {} within depth {}.",
            start, end, depth_limit
        );
        return;
    }

    for (i, path) in paths.iter().enumerate() {
        // Line 1: symbol names connected by ` → `
        let names: Vec<&str> = path.steps.iter().map(|s| s.name.as_str()).collect();
        println!("{}", names.join(" \u{2192} "));

        // Line 2 (indented): file:line for each step, connected by `  →  `
        let locations: Vec<String> = path
            .steps
            .iter()
            .map(|s| format!("{}:{}", normalize_path(&s.file_path), s.line_start))
            .collect();
        println!("  {}", locations.join("  \u{2192}  "));

        // Blank line between paths (but not after the last one)
        if i < paths.len() - 1 {
            println!();
        }
    }

    let path_word = if total == 1 { "path" } else { "paths" };
    println!(
        "\n\u{2500} {} {} found (depth limit: {})",
        total, path_word, depth_limit
    );
}

/// Print entry points grouped by type.
///
/// Format:
/// ```text
/// Entrypoints — 8 across 6 files
/// ──────────────────────────────────────────────────────────────────────────────
/// API Controllers:
///   PaymentController              src/Api/Controllers/PaymentController.cs       → 3 methods
///   SubscriptionController         src/Api/Controllers/SubscriptionController.cs  → 2 methods
///
/// Background Workers:
///   PaymentRetryWorker             src/Infrastructure/Workers/PaymentRetryWorker.cs
/// ```
pub fn print_entrypoints(
    groups: &[(String, Vec<EntrypointInfo>)],
    total: usize,
    file_count: usize,
) {
    let file_word = if file_count == 1 { "file" } else { "files" };
    println!(
        "Entrypoints \u{2014} {} across {} {}",
        total, file_count, file_word
    );
    println!("{SEPARATOR}");

    if groups.is_empty() {
        println!("(no entry points found)");
        return;
    }

    for (i, (group_name, entries)) in groups.iter().enumerate() {
        println!("{group_name}:");

        // Calculate max name width for alignment within this group.
        let max_name_len = entries
            .iter()
            .map(|e| e.name.chars().count())
            .max()
            .unwrap_or(0);
        let name_width = max_name_len.max(20) + 2; // Minimum 20 chars + padding

        for entry in entries {
            let path = normalize_path(&entry.file_path);
            let suffix = if entry.method_count > 0 {
                format!(
                    "   \u{2192} {} method{}",
                    entry.method_count,
                    if entry.method_count == 1 { "" } else { "s" }
                )
            } else {
                String::new()
            };
            println!(
                "  {:<width$}{}{}",
                entry.name,
                path,
                suffix,
                width = name_width
            );
        }

        // Blank line between groups (but not after the last one).
        if i < groups.len() - 1 {
            println!();
        }
    }
}

/// Print a structural map of the entire repository.
///
/// Format:
/// ```text
/// project-name — 181 files, 1,147 symbols, 1,409 edges
/// ──────────────────────────────────────────────────────────────────────────────
/// Languages: C#
///
/// Entry points:
///   PaymentController              Api/Controllers/                → 3 methods
///   SubscriptionController         Api/Controllers/                → 2 methods
///
/// Core symbols (by caller count):
///   ProcessPayment                 7 callers    Infrastructure/Services/PaymentService.cs
///
/// Architecture:
///   Api/                    7 files    62 symbols
///   Application/            22 files   145 symbols
/// ```
pub fn print_map(
    project_name: &str,
    stats: &MapStats,
    entrypoints: &[(String, Vec<EntrypointInfo>)],
    core_symbols: &[CoreSymbol],
    directories: &[DirStats],
) {
    // Header line: project-name — N files, N symbols, N edges
    println!(
        "{} \u{2014} {} files, {} symbols, {} edges",
        project_name,
        format_number(stats.file_count),
        format_number(stats.symbol_count),
        format_number(stats.edge_count),
    );
    println!("{SEPARATOR}");

    // Languages line.
    if !stats.languages.is_empty() {
        println!("Languages: {}", stats.languages.join(", "));
    }

    // Entry points section.
    let mut ep_count = 0usize;
    let mut ep_lines: Vec<String> = Vec::new();

    for (_group_name, entries) in entrypoints {
        for entry in entries {
            let path = normalize_path(&entry.file_path);
            // Extract directory portion of the path.
            let dir = if let Some(pos) = path.rfind('/') {
                format!("{}/", &path[..pos])
            } else {
                String::new()
            };

            // Strip leading "src/" for brevity.
            let display_dir = dir.strip_prefix("src/").unwrap_or(&dir).to_string();

            let suffix = if entry.method_count > 0 {
                format!(
                    "   \u{2192} {} method{}",
                    entry.method_count,
                    if entry.method_count == 1 { "" } else { "s" }
                )
            } else {
                String::new()
            };

            ep_lines.push(format!("  {:<32}{:<32}{}", entry.name, display_dir, suffix));
            ep_count += 1;
        }
    }

    if !ep_lines.is_empty() {
        println!();
        println!("Entry points:");
        let max_display = 8;
        for line in ep_lines.iter().take(max_display) {
            println!("{line}");
        }
        if ep_count > max_display {
            println!("  ... {} more", ep_count - max_display);
        }
    }

    // Core symbols section.
    if !core_symbols.is_empty() {
        println!();
        println!("Core symbols (by caller count):");
        for sym in core_symbols {
            let path = normalize_path(&sym.file_path);
            // Strip leading "src/" for brevity.
            let display_path = path.strip_prefix("src/").unwrap_or(&path).to_string();

            let caller_label = format!(
                "{} caller{}",
                sym.caller_count,
                if sym.caller_count == 1 { "" } else { "s" }
            );
            println!("  {:<32}{:<14}{}", sym.name, caller_label, display_path);
        }
    }

    // Architecture section.
    if !directories.is_empty() {
        println!();
        println!("Architecture:");
        for dir in directories {
            let file_label = format!(
                "{} file{}",
                dir.file_count,
                if dir.file_count == 1 { "" } else { "s" }
            );
            let sym_label = format!(
                "{} symbol{}",
                dir.symbol_count,
                if dir.symbol_count == 1 { "" } else { "s" }
            );
            println!("  {:<24}{:<14}{}", dir.directory, file_label, sym_label);
        }
    }
}

/// Human-readable label for an impact depth level.
fn impact_depth_label(depth: usize) -> &'static str {
    match depth {
        1 => "Direct callers",
        2 => "Second-degree",
        3 => "Third-degree",
        _ => "Further impact",
    }
}

/// Print incremental indexing results.
///
/// Format:
/// ```text
/// 3 files changed. Re-indexing...
///   Modified: src/payments/processor.ts
///   Added:    src/payments/refund.ts
/// Updated in 0.3s.
/// ```
pub fn print_incremental_result(
    modified: &[String],
    added: &[String],
    deleted: &[String],
    duration_secs: f64,
) {
    let total = modified.len() + added.len() + deleted.len();
    eprintln!(
        "{} file{} changed. Re-indexing...",
        total,
        if total == 1 { "" } else { "s" }
    );

    for path in modified {
        eprintln!("  Modified: {}", normalize_path(path));
    }
    for path in added {
        eprintln!("  Added:    {}", normalize_path(path));
    }
    for path in deleted {
        eprintln!("  Deleted:  {}", normalize_path(path));
    }

    eprintln!("Updated in {duration_secs:.1}s.");
}

/// Print search results from `scope find`.
///
/// Format:
/// ```text
/// Results for: "handles authentication errors"
/// ──────────────────────────────────────────────────────────────────────────────
/// 0.91  AuthMiddleware.handleUnauthorized    src/middleware/auth.ts:34      method
/// 0.88  errorHandler (auth branch)           src/api/middleware/errors.ts:67  function
/// 0.85  TokenValidator.onExpired             src/auth/token.ts:112          method
/// ```
pub fn print_find_results(query: &str, results: &[SearchResult]) {
    println!("Results for: \"{query}\"");
    println!("{SEPARATOR}");

    if results.is_empty() {
        println!("(no results found)");
        return;
    }

    for result in results {
        let path = normalize_path(&result.file_path);
        let location = format!("{path}:{}", result.line_start);
        println!(
            "{:.2}  {:<40}{:<36}  {}",
            result.score, result.name, location, result.kind
        );
    }
}

/// Print index status.
///
/// Format:
/// ```text
/// Index status: up to date
///   Symbols:    6,764
///   Files:      847
///   Edges:      12,340
///   Last index: 2 minutes ago
/// ```
pub fn print_status(
    status_label: &str,
    symbol_count: usize,
    file_count: usize,
    edge_count: usize,
    last_indexed: Option<&str>,
) {
    println!("Index status: {status_label}");
    println!("  Symbols:    {}", format_number(symbol_count));
    println!("  Files:      {}", format_number(file_count));
    println!("  Edges:      {}", format_number(edge_count));
    if let Some(relative) = last_indexed {
        println!("  Last index: {relative}");
    } else {
        println!("  Last index: never");
    }
}

/// Format a number with comma separators (e.g. 6764 -> "6,764").
fn format_number(n: usize) -> String {
    let s = n.to_string();
    let bytes = s.as_bytes();
    let len = bytes.len();
    if len <= 3 {
        return s;
    }

    let mut result = String::with_capacity(len + len / 3);
    for (i, ch) in s.chars().enumerate() {
        if i > 0 && (len - i).is_multiple_of(3) {
            result.push(',');
        }
        result.push(ch);
    }
    result
}

/// Truncate a string to a maximum character width, adding "..." if truncated.
fn truncate_str(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_chars.saturating_sub(3)).collect();
        format!("{truncated}...")
    }
}

/// Print multi-line snippet context with line numbers.
///
/// Marks the reference line with `>` and other lines with a space.
fn print_snippet_context(snippet: &[String], ref_line: Option<i64>) {
    // We need to figure out what line number the first snippet line corresponds to.
    // The snippet is centered around ref_line, so first line = ref_line - (snippet.len()-1)/2 approx.
    // But we need the actual start line. We can compute it from ref_line and snippet length.
    let Some(line_num) = ref_line else { return };
    let ref_idx_in_snippet = snippet.len() / 2; // approximate center
    let start_line = (line_num as usize).saturating_sub(ref_idx_in_snippet);

    for (i, code) in snippet.iter().enumerate() {
        let current_line = start_line + i;
        let marker = if current_line == line_num as usize {
            ">"
        } else {
            " "
        };
        println!("  {marker} {current_line:>4} | {code}");
    }
}

/// Print workspace member list in human-readable format.
///
/// Shows each member's name, path, index status, file count, and symbol count.
pub fn print_workspace_list(
    workspace_name: &str,
    members: &[crate::commands::workspace::MemberStatus],
) {
    println!("Workspace: {workspace_name}");
    println!("{SEPARATOR}");

    if members.is_empty() {
        println!("  (no members)");
        return;
    }

    // Find column widths
    let max_name = members
        .iter()
        .map(|m| m.name.len())
        .max()
        .unwrap_or(4)
        .max(4);
    let max_path = members
        .iter()
        .map(|m| m.path.len())
        .max()
        .unwrap_or(4)
        .max(4);

    // Header
    println!(
        "  {:<name_w$}  {:<path_w$}  {:<15}  {:>5}  {:>7}",
        "Name",
        "Path",
        "Status",
        "Files",
        "Symbols",
        name_w = max_name,
        path_w = max_path,
    );

    for member in members {
        println!(
            "  {:<name_w$}  {:<path_w$}  {:<15}  {:>5}  {:>7}",
            member.name,
            normalize_path(&member.path),
            member.status,
            if member.file_count > 0 {
                format_number(member.file_count)
            } else {
                "".to_string()
            },
            if member.symbol_count > 0 {
                format_number(member.symbol_count)
            } else {
                "".to_string()
            },
            name_w = max_name,
            path_w = max_path,
        );
    }
}

/// Convert an edge kind string to a human-readable label for grouped output.
fn humanize_edge_kind(kind: &str) -> &str {
    match kind {
        "instantiates" => "instantiated",
        "extends" => "extended",
        "implements" => "implemented",
        "references_type" => "used as type",
        "imports" => "imported",
        "calls" => "called",
        "references" => "referenced",
        _ => kind,
    }
}

/// Print workspace status showing per-member status and aggregate totals.
pub fn print_workspace_status(
    workspace_name: &str,
    members: &[crate::commands::status::MemberStatusData],
    total_symbols: usize,
    total_files: usize,
    total_edges: usize,
) {
    println!("Workspace: {workspace_name}");
    println!("{SEPARATOR}");

    for m in members {
        let status_label = if m.status.index_exists {
            if m.status.symbol_count == 0 {
                "empty"
            } else {
                "indexed"
            }
        } else {
            "not indexed"
        };
        let last = m.status.last_indexed_relative.as_deref().unwrap_or("never");
        println!(
            "  {:<16}{:<14}{:>6} files  {:>7} symbols  {:>7} edges  {}",
            m.name,
            status_label,
            format_number(m.status.file_count),
            format_number(m.status.symbol_count),
            format_number(m.status.edge_count),
            last,
        );
    }

    println!("{SEPARATOR}");
    println!(
        "  {:<16}{:<14}{:>6} files  {:>7} symbols  {:>7} edges",
        "Total",
        "",
        format_number(total_files),
        format_number(total_symbols),
        format_number(total_edges),
    );
}

/// Print workspace refs: references tagged with project names.
pub fn print_workspace_refs(
    symbol_name: &str,
    refs: &[crate::core::workspace_graph::WorkspaceRef],
    total: usize,
) {
    println!(
        "{} \u{2014} {} reference{} (workspace)",
        symbol_name,
        total,
        if total == 1 { "" } else { "s" }
    );
    println!("{SEPARATOR}");

    for wr in refs {
        let r = &wr.reference;
        let path = normalize_path(&r.file_path);
        let location = if let Some(line) = r.line {
            format!("{path}:{line}")
        } else {
            path
        };
        let display_text = r.snippet_line.as_deref().unwrap_or(&r.context);
        let truncated_text = truncate_str(display_text.trim(), 70);
        println!("[{:<12}] {:<36}{}", wr.project, location, truncated_text);
    }
}

/// Print workspace find results with project labels.
pub fn print_workspace_find_results(
    query: &str,
    results: &[crate::commands::find::WorkspaceSearchResult],
) {
    println!(
        "find \"{}\" \u{2014} {} result{}",
        query,
        results.len(),
        if results.len() == 1 { "" } else { "s" }
    );
    println!("{SEPARATOR}");

    for r in results {
        let path = normalize_path(&r.result.file_path);
        let line_range = format_line_range(r.result.line_start, r.result.line_end);
        println!(
            "[{:<12}] {:<32}{:<8}  {path}:{line_range}  ({:.2})",
            r.project, r.result.name, r.result.kind, r.result.score
        );
    }
}