face-core 0.1.0

Core grouping, clustering, and paging primitives for the face CLI.
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! §4.5 auto-strategy selection and §4.5 fallback grouping-field pick.
//!
//! [`auto_strategy`] inspects an axis field's value distribution across
//! the items list and picks one of the §5.2 / §5.3 strategies:
//!
//! - [`Strategy::Exact`] for enum-detected fields (cardinality ≤ 20 OR
//!   ≤ √N, top values cover ≥ 80%) and small-cardinality integer enums.
//! - [`Strategy::Prefix`] for path-like strings (≥ 50% contain a path
//!   separator (`/`, `::`, or `.`) AND share at least one 2-segment
//!   prefix on that separator).
//! - [`Strategy::Top`] for free-form strings as the catchall.
//! - [`Strategy::Bands`] for continuous numeric fields.
//!
//! [`pick_grouping_field`] is used when the user supplied no `--by` and
//! no score was detected: scan all top-level string fields for a
//! "discriminating" choice, with a small canonical preference list
//! (`data.path.text`, `path`, `file`, `module`, `kind`, `status`, `type`).

use serde_json::Value;

use crate::{FaceError, Strategy};

/// Auto-strategy: enum cardinality ceiling per §4.5.
const ENUM_MAX_CARDINALITY: usize = 20;

/// Auto-strategy: top-values coverage threshold for the enum heuristic.
const ENUM_COVERAGE_THRESHOLD: f64 = 0.80;

/// Auto-strategy: path-like detection threshold (≥ 50% contain a path
/// separator (`/`, `::`, or `.`)).
const PATH_LIKE_SLASH_RATIO: f64 = 0.50;

/// Recognized path separators, in tie-break priority order.
///
/// When multiple separators tie at the same value-coverage ratio, the
/// earlier entry wins: `/` beats `::` beats `.`. Filesystem paths are
/// most common, namespace-style `::` is less ambiguous than `.` (which
/// can also appear in file extensions and decimal numbers), so `.` is
/// the lowest-priority candidate.
pub(crate) const PATH_SEPARATORS: &[&str] = &["/", "::", "."];

/// Auto-strategy: enum-numeric ceiling (small integer enums treated as
/// categorical per §5.1).
const ENUM_NUMERIC_MAX_CARDINALITY: usize = 20;

/// Auto-strategy: default `Top { n }` value when picking the catchall.
const DEFAULT_TOP_N: u32 = 10;

/// Auto-strategy: default band count for continuous numeric fields.
const DEFAULT_BAND_COUNT: u8 = 5;

/// Canonical names preferred when picking a grouping field with no
/// explicit `--by`. Earlier entries win; matched case-insensitively.
const GROUPING_PREFERENCE: &[&str] = &[
    "data.path.text",
    "path",
    "file",
    "module",
    "kind",
    "status",
    "type",
];

/// Tunable inputs for §4.5 strategy and grouping-field detection.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct StrategyDetectionOptions {
    /// Maximum distinct values that may still be treated as enum-like.
    pub enum_max_cardinality: usize,
    /// Top-value coverage threshold for enum-like string detection.
    pub enum_coverage_threshold: f64,
    /// Minimum ratio of values containing a path separator (`/`, `::`,
    /// or `.`) before a string field is considered path-like. The name
    /// is preserved for backwards compatibility.
    pub path_like_slash_ratio: f64,
    /// Canonical field names preferred when auto-picking a grouping field.
    pub group_preference: Vec<String>,
    /// Default band count for continuous numeric fields.
    pub default_bands: u8,
}

impl Default for StrategyDetectionOptions {
    fn default() -> Self {
        Self {
            enum_max_cardinality: ENUM_MAX_CARDINALITY,
            enum_coverage_threshold: ENUM_COVERAGE_THRESHOLD,
            path_like_slash_ratio: PATH_LIKE_SLASH_RATIO,
            group_preference: GROUPING_PREFERENCE
                .iter()
                .map(|field| (*field).to_string())
                .collect(),
            default_bands: DEFAULT_BAND_COUNT,
        }
    }
}

/// Auto-pick a strategy for a given axis field, given the items list.
///
/// Implements §4.5 of `docs/design.md`. The function inspects the
/// distribution of values at `field` across `items` and routes:
///
/// - `Strategy::Exact` for enum-detected fields (cardinality ≤ 20 OR
///   ≤ √N, top values cover ≥ 80%) and small-cardinality integer enums.
/// - `Strategy::Prefix { depth: None }` for path-like strings (≥ 50%
///   contain a recognized path separator (`/`, `::`, or `.`) AND share
///   at least one 2-segment prefix on that separator).
/// - `Strategy::Top { n: 10 }` for free-form strings as the catchall.
/// - `Strategy::Bands { count: 5 }` for continuous numeric.
///
/// The caller wraps the returned [`Strategy`] in an [`crate::Axis`] and
/// sets `auto: true`.
///
/// # Errors
///
/// Currently never returns an error — auto-strategy always falls back
/// to `Top { n: 10 }` for ambiguous string distributions. The `Result`
/// shape is reserved for future structural validation (e.g. surfacing a
/// path-resolution failure on a non-existent field).
///
/// # Examples
///
/// ```
/// use face_core::detect::auto_strategy;
/// use face_core::Strategy;
/// use serde_json::json;
///
/// let items = vec![
///     json!({"kind": "bug"}),
///     json!({"kind": "bug"}),
///     json!({"kind": "feat"}),
/// ];
/// assert_eq!(auto_strategy("kind", &items).unwrap(), Strategy::Exact);
/// ```
pub fn auto_strategy(field: &str, items: &[Value]) -> Result<Strategy, FaceError> {
    auto_strategy_with_options(field, items, &StrategyDetectionOptions::default())
}

/// Auto-pick a strategy with caller-supplied heuristic thresholds.
pub fn auto_strategy_with_options(
    field: &str,
    items: &[Value],
    options: &StrategyDetectionOptions,
) -> Result<Strategy, FaceError> {
    let resolved = resolve_field_values(field, items);

    if resolved.is_empty() {
        // No values resolved — fall back to the catchall. Strategies
        // downstream will produce empty clusters; that's the right
        // signal for "field doesn't exist anywhere".
        return Ok(Strategy::Top { n: DEFAULT_TOP_N });
    }

    let kind = classify_distribution(&resolved);
    let strategy = match kind {
        DistributionKind::Numeric => pick_numeric_strategy(&resolved, options),
        DistributionKind::String => pick_string_strategy(&resolved, options),
        DistributionKind::Bool => Strategy::Exact,
        DistributionKind::Mixed => Strategy::Top { n: DEFAULT_TOP_N },
    };
    Ok(strategy)
}

/// Pick the most-discriminating string field when no explicit `--by`
/// was given AND no score was detected (§4.5 fallback).
///
/// Heuristic: collect every string leaf field, then build a
/// candidate pool from two qualifying paths. (1) the cardinality
/// window `[2, records/3]`, the legacy enum-like check; and (2) the
/// path-like fallback — high-cardinality fields whose values share a
/// recognized separator (`/`, `::`, or `.`) and at least one 2-segment
/// prefix on that separator. A field passing either qualifies. Across
/// the combined pool, canonical names (`path`, `file`, `module`,
/// `kind`, `status`, `type`) win in declared order; with no canonical
/// match, the highest-cardinality candidate wins (alphabetical
/// tiebreak). Returns `None` if neither path qualifies any field — the
/// caller errors with [`FaceError::AmbiguousDetection`].
///
/// # Examples
///
/// ```
/// use face_core::detect::pick_grouping_field;
/// use serde_json::json;
///
/// let items = vec![
///     json!({"file": "a.rs", "kind": "bug"}),
///     json!({"file": "b.rs", "kind": "bug"}),
///     json!({"file": "a.rs", "kind": "feat"}),
/// ];
/// assert_eq!(pick_grouping_field(&items).as_deref(), Some("file"));
/// ```
pub fn pick_grouping_field(items: &[Value]) -> Option<String> {
    pick_grouping_field_with_options(items, &StrategyDetectionOptions::default())
}

/// Pick the fallback grouping field with caller-supplied preferences.
///
/// See [`pick_grouping_field`] for the heuristic; this sibling only
/// exposes the tunable `options` knobs (cardinality window, path-like
/// ratio, canonical preference list).
pub fn pick_grouping_field_with_options(
    items: &[Value],
    options: &StrategyDetectionOptions,
) -> Option<String> {
    if items.is_empty() {
        return None;
    }

    let candidates = collect_string_candidates(items);
    let cardinality_ceiling = (items.len() / 3).max(2);

    // Two qualifying paths into the candidate pool:
    //   1. Cardinality window [2, records/3] — the legacy enum-like
    //      check.
    //   2. Path-like — high-cardinality strings whose prefix split
    //      collapses cardinality back into a useful range.
    // A field passing either qualifies. Canonical-name preference and
    // the highest-cardinality tiebreak are then applied across the
    // combined pool, so a canonical-named cardinality-window field
    // (e.g. `kind`) still wins over a non-canonical path-like field
    // (e.g. `locator`) when both are present.
    let mut qualified: Vec<(String, usize)> = candidates
        .iter()
        .filter(|(_, card)| *card >= 2 && *card <= cardinality_ceiling)
        .cloned()
        .collect();

    for (name, card) in &candidates {
        if qualified.iter().any(|(n, _)| n == name) {
            continue;
        }
        if is_path_like_field(items, name, options.path_like_slash_ratio) {
            qualified.push((name.clone(), *card));
        }
    }

    if qualified.is_empty() {
        return None;
    }

    pick_with_canonical_preference(&qualified, &options.group_preference)
}

/// Apply the canonical-preference + max-cardinality tiebreak rule to a
/// pre-filtered candidate list. Returns the chosen field name.
fn pick_with_canonical_preference(
    candidates: &[(String, usize)],
    preference: &[String],
) -> Option<String> {
    // Prefer canonical names in declared order.
    for canonical in preference {
        if let Some((name, _)) = candidates
            .iter()
            .find(|(name, _)| name.eq_ignore_ascii_case(canonical))
        {
            return Some(name.clone());
        }
    }

    // No canonical match — pick the highest-cardinality candidate.
    // Ties broken by field name (alphabetical) for determinism.
    candidates
        .iter()
        .max_by(|(a_name, a_card), (b_name, b_card)| {
            a_card.cmp(b_card).then_with(|| b_name.cmp(a_name))
        })
        .map(|(name, _)| name.clone())
}

/// Returns `true` when `field` resolves to enough path-like string
/// values to qualify for [`Strategy::Prefix`] under the same threshold
/// the auto-strategy uses.
fn is_path_like_field(items: &[Value], field: &str, min_ratio: f64) -> bool {
    let resolved = resolve_field_values(field, items);
    if resolved.is_empty() {
        return false;
    }
    let Some(sep) = dominant_path_separator(&resolved, min_ratio) else {
        return false;
    };
    shares_two_segment_prefix(&resolved, sep)
}

/// Collect every string-valued leaf field path with its cardinality.
///
/// A field is considered a candidate only when **every** observed value
/// at that key is either a string or absent (a single integer at that
/// key disqualifies it — we want pure strings to keep the pick clean).
fn collect_string_candidates(items: &[Value]) -> Vec<(String, usize)> {
    use std::collections::BTreeMap;

    // BTreeMap so the iteration order is deterministic.
    let mut per_field: BTreeMap<String, FieldStats> = BTreeMap::new();

    for item in items {
        collect_string_candidate_paths(item, "", &mut per_field);
    }

    let mut out = Vec::new();
    for (name, stats) in per_field {
        if stats.disqualified || stats.string_count == 0 {
            continue;
        }
        out.push((name, stats.distinct.len()));
    }
    out.sort();
    out
}

fn collect_string_candidate_paths(
    value: &Value,
    prefix: &str,
    per_field: &mut std::collections::BTreeMap<String, FieldStats>,
) {
    match value {
        Value::Object(map) => {
            for (key, value) in map {
                let path = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{prefix}.{key}")
                };
                collect_string_candidate_paths(value, &path, per_field);
            }
        }
        Value::String(s) if !prefix.is_empty() => {
            let entry = per_field.entry(prefix.to_string()).or_default();
            entry.string_count += 1;
            entry.distinct.insert(s.clone());
        }
        Value::Null => {
            // Absent / null — do not disqualify; just ignore.
        }
        _ if !prefix.is_empty() => {
            per_field
                .entry(prefix.to_string())
                .or_default()
                .disqualified = true;
        }
        _ => {}
    }
}

#[derive(Default)]
struct FieldStats {
    string_count: usize,
    distinct: std::collections::BTreeSet<String>,
    disqualified: bool,
}

/// Resolved values at the requested path, in input order. Records
/// whose path doesn't resolve are omitted.
fn resolve_field_values(field: &str, items: &[Value]) -> Vec<Value> {
    items
        .iter()
        .filter_map(|item| crate::path::resolve(item, field).ok().cloned())
        .collect()
}

/// Top-level distribution classification.
enum DistributionKind {
    Numeric,
    String,
    Bool,
    Mixed,
}

fn classify_distribution(values: &[Value]) -> DistributionKind {
    let mut numeric = 0;
    let mut string = 0;
    let mut boolean = 0;
    let mut other = 0;
    for v in values {
        match v {
            Value::Number(_) => numeric += 1,
            Value::String(_) => string += 1,
            Value::Bool(_) => boolean += 1,
            _ => other += 1,
        }
    }
    let total = values.len();
    if numeric == total {
        DistributionKind::Numeric
    } else if string == total {
        DistributionKind::String
    } else if boolean == total {
        DistributionKind::Bool
    } else {
        // Allow a small minority of nulls / misses but still classify
        // as the dominant kind.
        if numeric > string && numeric > boolean && numeric + other >= total / 2 {
            DistributionKind::Numeric
        } else if string > numeric && string > boolean {
            DistributionKind::String
        } else {
            DistributionKind::Mixed
        }
    }
}

/// Numeric path: small-cardinality integer enums become Exact;
/// continuous numerics get Bands (§5.2 default).
fn pick_numeric_strategy(values: &[Value], options: &StrategyDetectionOptions) -> Strategy {
    // Pull integer-valued numbers out for the enum-numeric heuristic.
    let mut all_integer = true;
    let mut distinct = std::collections::BTreeSet::new();
    for v in values {
        let n = match v {
            Value::Number(n) => n,
            _ => {
                all_integer = false;
                break;
            }
        };
        let f = match n.as_f64() {
            Some(f) => f,
            None => {
                all_integer = false;
                break;
            }
        };
        if !f.is_finite() || f.fract() != 0.0 {
            all_integer = false;
            break;
        }
        // Use the i128-or-fallback string form for distinct counting.
        // `n.as_i64()` covers most integer JSON numbers; otherwise fall
        // back to the f64 bit pattern.
        if let Some(i) = n.as_i64() {
            distinct.insert(i.to_string());
        } else {
            distinct.insert(format!("{f}"));
        }
    }

    if all_integer && distinct.len() <= ENUM_NUMERIC_MAX_CARDINALITY {
        return Strategy::Exact;
    }

    Strategy::Bands {
        count: options.default_bands,
    }
}

/// String path: enum → exact, path-like → prefix, else top.
fn pick_string_strategy(values: &[Value], options: &StrategyDetectionOptions) -> Strategy {
    use std::collections::BTreeMap;

    let mut frequencies: BTreeMap<String, usize> = BTreeMap::new();
    for v in values {
        if let Value::String(s) = v {
            *frequencies.entry(s.clone()).or_insert(0) += 1;
        }
    }

    let total = values.len();
    let cardinality = frequencies.len();
    if cardinality == 0 {
        return Strategy::Top { n: DEFAULT_TOP_N };
    }

    // Enum heuristic: cardinality ≤ configured ceiling OR ≤ √N, top
    // values cover the configured threshold.
    // We additionally require cardinality < total — when every value is
    // unique the field isn't enum-like even if the small-N case lets
    // both sides of the OR pass. The §5.3 path-like check below should
    // get a chance on degenerate "all unique" string fields.
    let sqrt_n = (total as f64).sqrt().ceil() as usize;
    let cardinality_ok = (cardinality <= options.enum_max_cardinality || cardinality <= sqrt_n)
        && cardinality < total;

    if cardinality_ok {
        let mut counts: Vec<usize> = frequencies.values().copied().collect();
        counts.sort_by(|a, b| b.cmp(a));
        let take = counts.len().min(options.enum_max_cardinality);
        let top_sum: usize = counts.iter().take(take).sum();
        let coverage = top_sum as f64 / total as f64;
        if coverage >= options.enum_coverage_threshold {
            return Strategy::Exact;
        }
    }

    // Path-like heuristic: ≥ 50% contain a recognized separator AND
    // share at least one 2-segment prefix on that separator.
    if let Some(sep) = dominant_path_separator(values, options.path_like_slash_ratio)
        && shares_two_segment_prefix(values, sep)
    {
        return Strategy::Prefix { depth: None };
    }

    Strategy::Top { n: DEFAULT_TOP_N }
}

/// Returns the dominant path separator across the string values in
/// `values`, or `None` if no recognized separator covers at least
/// `min_ratio` of them.
///
/// Recognized separators are `/`, `::`, and `.`. The separator that
/// appears in the highest fraction of string values wins; ties resolve
/// in [`PATH_SEPARATORS`] declaration order (`/` > `::` > `.`).
///
/// Non-string values are ignored for the count (matches the legacy
/// slash-only check). The denominator is the total length of `values`,
/// which keeps the threshold meaningful when strings are mixed with
/// nulls or other shapes.
pub(crate) fn dominant_path_separator(values: &[Value], min_ratio: f64) -> Option<&'static str> {
    if values.is_empty() {
        return None;
    }
    let total = values.len() as f64;
    let mut best: Option<(&'static str, usize)> = None;
    for &sep in PATH_SEPARATORS {
        let count = values
            .iter()
            .filter(|v| matches!(v, Value::String(s) if s.contains(sep)))
            .count();
        let ratio = count as f64 / total;
        if ratio < min_ratio {
            continue;
        }
        match best {
            // Strictly greater coverage — replace.
            Some((_, current)) if count > current => best = Some((sep, count)),
            // Equal coverage — earlier separator (already stored) wins.
            Some(_) => {}
            None => best = Some((sep, count)),
        }
    }
    best.map(|(sep, _)| sep)
}

/// Returns `true` when at least two of the string values share the same
/// first two `sep`-separated segments (e.g. `src/cli/main.rs` and
/// `src/cli/lib.rs` share `src/cli` for `/`; `Foo::Bar::baz` and
/// `Foo::Bar::qux` share `Foo::Bar` for `::`).
fn shares_two_segment_prefix(values: &[Value], sep: &str) -> bool {
    use std::collections::BTreeMap;
    let mut prefix_counts: BTreeMap<String, usize> = BTreeMap::new();
    for v in values {
        let Value::String(s) = v else {
            continue;
        };
        let mut parts = s.split(sep);
        let (Some(a), Some(b)) = (parts.next(), parts.next()) else {
            continue;
        };
        if a.is_empty() && b.is_empty() {
            continue;
        }
        let prefix = format!("{a}{sep}{b}");
        *prefix_counts.entry(prefix).or_insert(0) += 1;
    }
    prefix_counts.values().any(|&c| c >= 2)
}

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

    #[test]
    fn small_cardinality_string_is_exact() {
        let items = vec![
            json!({"kind": "bug"}),
            json!({"kind": "bug"}),
            json!({"kind": "feat"}),
            json!({"kind": "feat"}),
            json!({"kind": "bug"}),
        ];
        assert_eq!(auto_strategy("kind", &items).unwrap(), Strategy::Exact);
    }

    #[test]
    fn path_like_strings_become_prefix() {
        let items = vec![
            json!({"file": "src/cli/main.rs"}),
            json!({"file": "src/cli/lib.rs"}),
            json!({"file": "src/core/util.rs"}),
            json!({"file": "src/core/api.rs"}),
            json!({"file": "src/format/human.rs"}),
            json!({"file": "src/format/json.rs"}),
        ];
        assert_eq!(
            auto_strategy("file", &items).unwrap(),
            Strategy::Prefix { depth: None }
        );
    }

    #[test]
    fn free_form_strings_fall_back_to_top() {
        // Many distinct values with no shared prefixes → Top.
        let items: Vec<Value> = (0..50)
            .map(|i| json!({"msg": format!("totally-unique-message-{i}-with-words")}))
            .collect();
        match auto_strategy("msg", &items).unwrap() {
            Strategy::Top { n } => assert_eq!(n, DEFAULT_TOP_N),
            other => panic!("expected Top, got {other:?}"),
        }
    }

    #[test]
    fn continuous_numeric_becomes_bands() {
        let items: Vec<Value> = (0..50)
            .map(|i| json!({"score": (i as f64) * 0.013}))
            .collect();
        match auto_strategy("score", &items).unwrap() {
            Strategy::Bands { count } => assert_eq!(count, DEFAULT_BAND_COUNT),
            other => panic!("expected Bands, got {other:?}"),
        }
    }

    #[test]
    fn small_integer_numeric_becomes_exact() {
        // Severity-style: small integer enum.
        let items: Vec<Value> = [0, 1, 2, 1, 0, 2, 3]
            .iter()
            .map(|s| json!({"sev": *s}))
            .collect();
        assert_eq!(auto_strategy("sev", &items).unwrap(), Strategy::Exact);
    }

    #[test]
    fn empty_items_returns_top_fallback() {
        assert!(matches!(
            auto_strategy("anything", &[]).unwrap(),
            Strategy::Top { .. }
        ));
    }

    #[test]
    fn pick_grouping_field_prefers_canonical_name() {
        let items = vec![
            json!({"kind": "bug",  "id": "x1"}),
            json!({"kind": "bug",  "id": "x2"}),
            json!({"kind": "feat", "id": "x3"}),
        ];
        // `kind` is canonical, `id` is high-cardinality (above
        // records/3=1). Pick `kind`.
        assert_eq!(pick_grouping_field(&items).as_deref(), Some("kind"));
    }

    #[test]
    fn pick_grouping_field_filters_out_high_cardinality() {
        let items: Vec<Value> = (0..30)
            .map(|i| json!({"id": format!("x{i}"), "kind": "same"}))
            .collect();
        // `id` is too high-cardinality (30 > 30/3 = 10), `kind` has
        // cardinality 1 (< 2). Neither qualifies → None.
        assert_eq!(pick_grouping_field(&items), None);
    }

    #[test]
    fn pick_grouping_field_picks_canonical_over_alphabetical() {
        // 12 records: alpha cardinality 3, kind cardinality 3.
        // records/3 = 4 → both qualify. `kind` is canonical so it
        // beats alpha despite the alphabetical order.
        let alpha_vals = ["a", "b", "c"];
        let kind_vals = ["x", "y", "z"];
        let items: Vec<Value> = (0..12)
            .map(|i| json!({"alpha": alpha_vals[i % 3], "kind": kind_vals[i % 3]}))
            .collect();
        assert_eq!(pick_grouping_field(&items).as_deref(), Some("kind"));
    }

    #[test]
    fn pick_grouping_field_falls_back_to_max_cardinality() {
        // 12 records, no canonical-named fields. alpha cardinality 4,
        // beta cardinality 2. records/3 = 4 → both qualify. alpha wins
        // on cardinality.
        let alpha_vals = ["a", "b", "c", "d"];
        let beta_vals = ["x", "y"];
        let items: Vec<Value> = (0..12)
            .map(|i| json!({"alpha": alpha_vals[i % 4], "beta": beta_vals[i % 2]}))
            .collect();
        assert_eq!(pick_grouping_field(&items).as_deref(), Some("alpha"));
    }

    #[test]
    fn double_colon_paths_become_prefix() {
        // Rust/C++ namespace style: `Module::Submodule::Symbol`.
        let items = vec![
            json!({"locator": "Foo::A::x"}),
            json!({"locator": "Foo::A::y"}),
            json!({"locator": "Foo::B::x"}),
            json!({"locator": "Bar::A::x"}),
        ];
        assert_eq!(
            auto_strategy("locator", &items).unwrap(),
            Strategy::Prefix { depth: None }
        );
    }

    #[test]
    fn dotted_namespace_becomes_prefix() {
        // Java/JS-style: `com.example.foo.Bar`.
        let items = vec![
            json!({"path": "com.example.foo.Bar"}),
            json!({"path": "com.example.foo.Baz"}),
            json!({"path": "com.example.bar.Qux"}),
            json!({"path": "com.example.bar.Quux"}),
        ];
        assert_eq!(
            auto_strategy("path", &items).unwrap(),
            Strategy::Prefix { depth: None }
        );
    }

    #[test]
    fn file_extensions_alone_do_not_trigger_prefix() {
        // Bare `Foo.swift` / `Bar.kt` / `Qux.rs` — every value contains
        // `.` but none share a 2-segment prefix on `.`. Should fall
        // through to Top, not be misclassified as Prefix.
        let items: Vec<Value> = (0..30)
            .map(|i| json!({"name": format!("Symbol{i}.swift")}))
            .collect();
        match auto_strategy("name", &items).unwrap() {
            Strategy::Top { .. } => {}
            other => panic!("expected Top, got {other:?}"),
        }
    }

    #[test]
    fn dominant_separator_picks_highest_coverage() {
        // Mixed input: `/` covers 4/5, `::` covers 1/5.
        let values: Vec<Value> = vec![
            json!("a/b/c"),
            json!("a/b/d"),
            json!("x/y/z"),
            json!("x/y/w"),
            json!("Foo::Bar::baz"),
        ];
        assert_eq!(dominant_path_separator(&values, 0.5), Some("/"));
    }

    #[test]
    fn pick_grouping_field_picks_path_like_at_high_cardinality() {
        // 30 records with a high-cardinality `locator` field that is
        // path-like (uses `::`), plus a tiny `kind` enum. Cardinality
        // window would normally exclude `locator` (29 > 30/3=10), but
        // the path-like scan should still pick it because the
        // prefix-split makes it a useful grouping.
        let mut items: Vec<Value> = Vec::new();
        for i in 0..30 {
            // Three modules: Share (10), Lib (10), App (10).
            // Each has many distinct symbols → high cardinality
            // overall, low cardinality after prefix split.
            let module = match i % 3 {
                0 => "Share",
                1 => "Lib",
                _ => "App",
            };
            items.push(json!({
                "locator": format!("{module}::View::sym{i}"),
                "kind": "function",
            }));
        }
        assert_eq!(
            pick_grouping_field(&items).as_deref(),
            Some("locator"),
            "high-cardinality path-like field should win over a 1-cardinality enum",
        );
    }

    #[test]
    fn pick_grouping_field_discovers_rg_nested_path() {
        let items = vec![
            json!({"type": "begin", "data": {"path": {"text": "Modules/Share/A.swift"}}}),
            json!({"type": "match", "data": {"path": {"text": "Modules/Share/A.swift"}, "lines": {"text": "let viewModel = AViewModel()"}}}),
            json!({"type": "end", "data": {"path": {"text": "Modules/Share/A.swift"}}}),
            json!({"type": "begin", "data": {"path": {"text": "Modules/Room/B.swift"}}}),
            json!({"type": "match", "data": {"path": {"text": "Modules/Room/B.swift"}, "lines": {"text": "let viewModel = BViewModel()"}}}),
            json!({"type": "end", "data": {"path": {"text": "Modules/Room/B.swift"}}}),
            json!({"type": "summary", "data": {"elapsed_total": {"secs": 0, "nanos": 1}}}),
        ];
        assert_eq!(
            pick_grouping_field(&items).as_deref(),
            Some("data.path.text"),
            "rg JSONL should auto-group by file path, not record `type`",
        );
    }

    #[test]
    fn pick_grouping_field_disqualifies_mixed_type_field() {
        let items = vec![
            json!({"mixed": "string-value"}),
            json!({"mixed": 42}),
            json!({"mixed": "another"}),
            json!({"kind": "ok"}),
            json!({"kind": "ok"}),
            json!({"kind": "no"}),
        ];
        // `mixed` has a non-string value → disqualified.
        // `kind` is canonical and qualifies.
        assert_eq!(pick_grouping_field(&items).as_deref(), Some("kind"));
    }
}