beads_rust 0.2.4

Agent-first issue tracker (SQLite + JSONL)
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
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
//! ID generation for issues.
//!
//! Implements classic bd ID format: `<prefix>-<hash>` where hash is
//! base36 lowercase (0-9, a-z) with adaptive length based on DB size.

use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};

pub const MAX_ID_PREFIX_LEN: usize = 64;
pub const MAX_ID_HASH_LEN: usize = 40;
pub const MAX_ID_LENGTH: usize = MAX_ID_PREFIX_LEN + 1 + MAX_ID_HASH_LEN;

/// Default ID generation configuration.
#[derive(Debug, Clone)]
pub struct IdConfig {
    /// Issue ID prefix (e.g., "bd", "`beads_rust`").
    pub prefix: String,
    /// Minimum hash length.
    pub min_hash_length: usize,
    /// Maximum hash length.
    pub max_hash_length: usize,
    /// Maximum collision probability before increasing length.
    pub max_collision_prob: f64,
}

impl Default for IdConfig {
    fn default() -> Self {
        Self {
            prefix: "br".to_string(),
            min_hash_length: 3,
            max_hash_length: 8,
            max_collision_prob: 0.25,
        }
    }
}

impl IdConfig {
    /// Create a new ID config with the given prefix.
    #[must_use]
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            prefix: normalize_prefix(&prefix.into()),
            ..Default::default()
        }
    }
}

/// ID generator that produces unique issue IDs.
#[derive(Debug, Clone)]
pub struct IdGenerator {
    config: IdConfig,
}

impl IdGenerator {
    /// Create a new ID generator with the given config.
    #[must_use]
    pub const fn new(config: IdConfig) -> Self {
        Self { config }
    }

    /// Create a new ID generator with default config.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::new(IdConfig::default())
    }

    /// Get the configured prefix.
    #[must_use]
    pub fn prefix(&self) -> &str {
        &self.config.prefix
    }

    /// Compute the optimal hash length for a given issue count.
    ///
    /// Uses birthday problem approximation to estimate collision probability.
    #[must_use]
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap
    )]
    pub fn optimal_length(&self, issue_count: usize) -> usize {
        let n = issue_count as f64;
        let max_prob = self.config.max_collision_prob;

        for len in self.config.min_hash_length..=self.config.max_hash_length {
            // Base36 has 36^len possible values
            let space = 36_f64.powi(len as i32);
            // Birthday problem: P(collision) ≈ 1 - e^(-n²/2d)
            let prob = 1.0 - (-n * n / (2.0 * space)).exp();
            if prob < max_prob {
                return len;
            }
        }
        self.config.max_hash_length
    }

    /// Generate a candidate ID with the given parameters.
    #[must_use]
    pub fn generate_candidate(
        &self,
        title: &str,
        description: Option<&str>,
        creator: Option<&str>,
        created_at: DateTime<Utc>,
        nonce: u32,
        hash_length: usize,
    ) -> String {
        let seed = generate_id_seed(title, description, creator, created_at, nonce);
        let hash_str = compute_id_hash(&seed, hash_length);
        format!("{}-{hash_str}", self.config.prefix)
    }

    /// Generate an ID, checking for collisions with the provided checker.
    ///
    /// The checker function should return `true` if the ID already exists.
    pub fn generate<F>(
        &self,
        title: &str,
        description: Option<&str>,
        creator: Option<&str>,
        created_at: DateTime<Utc>,
        issue_count: usize,
        exists: F,
    ) -> String
    where
        F: Fn(&str) -> bool,
    {
        let mut length = self.optimal_length(issue_count);

        loop {
            // Try nonces 0..10 at this length
            for nonce in 0..10 {
                let id =
                    self.generate_candidate(title, description, creator, created_at, nonce, length);
                if !exists(&id) {
                    return id;
                }
            }

            // All nonces collided, increase length
            if length < self.config.max_hash_length {
                length += 1;
            } else {
                // Fallback: use full hash with extra entropy
                // Try increasing nonces until we find a free one
                let mut nonce = 0;
                loop {
                    let seed = generate_id_seed(title, description, creator, created_at, nonce);
                    let hash_str = compute_id_hash(&seed, 12);
                    let id = format!("{}-{hash_str}", self.config.prefix);

                    if !exists(&id) {
                        return id;
                    }

                    nonce += 1;

                    // Safety break: if we hit 1000 collisions even with 12-char hashes,
                    // append the nonce to force uniqueness.
                    if nonce > 1000 {
                        let desperate_id = format!("{}-{hash_str}{nonce}", self.config.prefix);
                        if !exists(&desperate_id) {
                            return desperate_id;
                        }
                    }

                    // Hard stop at 2000 to prevent infinite loop if exists() is broken
                    if nonce > 2000 {
                        return format!("{}-{hash_str}{nonce}", self.config.prefix);
                    }
                }
            }
        }
    }
}

/// Generate the seed string for ID generation.
///
/// Inputs are length-prefixed as `len:value` fields so embedded separators in
/// titles or descriptions cannot collide with adjacent fields.
#[must_use]
pub fn generate_id_seed(
    title: &str,
    description: Option<&str>,
    creator: Option<&str>,
    created_at: DateTime<Utc>,
    nonce: u32,
) -> String {
    let timestamp = created_at.timestamp_nanos_opt().unwrap_or(0).to_string();
    let nonce = nonce.to_string();

    let mut seed = String::new();
    append_seed_part(&mut seed, title);
    append_seed_part(&mut seed, description.unwrap_or(""));
    append_seed_part(&mut seed, creator.unwrap_or(""));
    append_seed_part(&mut seed, &timestamp);
    append_seed_part(&mut seed, &nonce);
    seed
}

fn append_seed_part(seed: &mut String, value: &str) {
    use std::fmt::Write;
    write!(seed, "{}:", value.len()).expect("writing to String never fails");
    seed.push_str(value);
}

/// Compute a base36 hash of the input string with a specific length.
///
/// Uses SHA256 to hash the input, then converts the first 8 bytes to a u64,
/// encodes as base36, and truncates to the requested length.
#[must_use]
pub fn compute_id_hash(input: &str, length: usize) -> String {
    let mut hasher = Sha256::new();
    hasher.update(input.as_bytes());
    let result = hasher.finalize();

    // Use first 8 bytes for a 64-bit integer
    let mut num = 0u64;
    for &byte in result.iter().take(8) {
        num = (num << 8) | u64::from(byte);
    }

    let encoded = base36_encode(num);

    // Pad with '0' if too short (unlikely for u64 but possible)
    let mut s = encoded;
    if s.len() < length {
        s = format!("{s:0>length$}");
    }

    // Take the last `length` characters to ensure full entropy from
    // the least significant digits of the base36 encoding.
    let start = s.len().saturating_sub(length);
    s.chars().skip(start).collect()
}

fn base36_encode(mut num: u64) -> String {
    const ALPHABET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
    if num == 0 {
        return "0".to_string();
    }
    let mut chars = Vec::new();
    while num > 0 {
        chars.push(ALPHABET[(num % 36) as usize] as char);
        num /= 36;
    }
    chars.into_iter().rev().collect()
}

// ============================================================================
// Child ID Helpers
// ============================================================================

/// Generate child ID from parent.
///
/// Child IDs have format: `<parent>.<n>` where n is the child number.
#[must_use]
pub fn child_id(parent_id: &str, child_number: u32) -> String {
    format!("{parent_id}.{child_number}")
}

fn issue_id_separator(id: &str) -> Option<usize> {
    id.rfind('-')
}

pub(crate) fn split_prefix_remainder(id: &str) -> Option<(&str, &str)> {
    let dash_pos = issue_id_separator(id)?;
    let (prefix, remainder_with_dash) = id.split_at(dash_pos);
    let remainder = remainder_with_dash.strip_prefix('-')?;
    if prefix.is_empty() || remainder.is_empty() {
        return None;
    }
    Some((prefix, remainder))
}

/// Check if an ID is a child ID (contains a dot after the hash).
#[must_use]
pub fn is_child_id(id: &str) -> bool {
    // Only check after the prefix-hash part
    split_prefix_remainder(id).map_or_else(
        || id.contains('.'),
        |(_, remainder)| remainder.contains('.'),
    )
}

/// Get the depth of a hierarchical ID.
///
/// Top-level IDs have depth 0, first-level children have depth 1, etc.
#[must_use]
pub fn id_depth(id: &str) -> usize {
    // Count dots after the prefix-hash part
    split_prefix_remainder(id).map_or_else(
        || id.matches('.').count(),
        |(_, remainder)| remainder.matches('.').count(),
    )
}

/// Convenience function to generate an ID with default settings.
#[must_use]
pub fn generate_id(
    title: &str,
    description: Option<&str>,
    creator: Option<&str>,
    created_at: DateTime<Utc>,
) -> String {
    let generator = IdGenerator::with_defaults();
    generator.generate(title, description, creator, created_at, 0, |_| false)
}

// ============================================================================
// ID Parsing and Validation
// ============================================================================

use crate::error::{BeadsError, Result};

/// Parsed components of an issue ID.
///
/// Supports both root IDs (`br-abc123`) and hierarchical IDs (`br-abc123.1.2`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedId {
    /// The prefix (e.g., "br").
    pub prefix: String,
    /// The hash portion (e.g., "abc123").
    pub hash: String,
    /// Child path segments if this is a hierarchical ID (e.g., `[1, 2]` for `.1.2`).
    pub child_path: Vec<u32>,
}

impl ParsedId {
    /// Returns true if this is a root (non-hierarchical) ID.
    #[must_use]
    pub fn is_root(&self) -> bool {
        self.child_path.is_empty()
    }

    /// Returns the depth in the hierarchy (0 for root).
    #[must_use]
    pub fn depth(&self) -> usize {
        self.child_path.len()
    }

    /// Get the parent ID if this is a child.
    ///
    /// Returns `None` for root IDs.
    #[must_use]
    pub fn parent(&self) -> Option<String> {
        if self.child_path.is_empty() {
            return None;
        }

        let mut parent_path = self.child_path.clone();
        parent_path.pop();

        if parent_path.is_empty() {
            Some(format!("{}-{}", self.prefix, self.hash))
        } else {
            let path_str = format_child_path(&parent_path);
            Some(format!("{}-{}{}", self.prefix, self.hash, path_str))
        }
    }

    /// Reconstruct the full ID string.
    #[must_use]
    pub fn to_id_string(&self) -> String {
        if self.child_path.is_empty() {
            format!("{}-{}", self.prefix, self.hash)
        } else {
            let path_str = format_child_path(&self.child_path);
            format!("{}-{}{}", self.prefix, self.hash, path_str)
        }
    }

    /// Check if this ID is a child (direct or indirect) of another.
    #[must_use]
    pub fn is_child_of(&self, potential_parent: &str) -> bool {
        let full_id = self.to_id_string();
        full_id.starts_with(potential_parent)
            && full_id.len() > potential_parent.len()
            && full_id[potential_parent.len()..].starts_with('.')
    }
}

fn format_child_path(path: &[u32]) -> String {
    let mut out = String::new();
    for segment in path {
        use std::fmt::Write;
        let _ = write!(out, ".{segment}");
    }
    out
}

/// Parse an issue ID into its components.
///
/// # Errors
///
/// Returns `InvalidId` if the ID format is invalid.
pub fn parse_id(id: &str) -> Result<ParsedId> {
    // Find the prefix-hash separator (supports hyphenated prefixes)
    let Some((prefix, remainder)) = split_prefix_remainder(id) else {
        return Err(BeadsError::InvalidId { id: id.to_string() });
    };

    if prefix.is_empty() || prefix.len() > MAX_ID_PREFIX_LEN {
        return Err(BeadsError::InvalidId { id: id.to_string() });
    }

    if !prefix.chars().all(|c| {
        c.is_ascii_lowercase()
            || c.is_ascii_digit()
            || c == '_'
            || c == '-'
            || c == '.'
            || c == ':'
            || c == '#'
    }) {
        return Err(BeadsError::InvalidId { id: id.to_string() });
    }

    // Split remainder by '.' to get hash and child path
    let parts: Vec<&str> = remainder.split('.').collect();
    let hash = parts[0].to_string();

    if hash.is_empty() || hash.len() > MAX_ID_HASH_LEN {
        return Err(BeadsError::InvalidId { id: id.to_string() });
    }

    // Validate hash is base36 (lowercase alphanumeric)
    if !hash
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
    {
        return Err(BeadsError::InvalidId { id: id.to_string() });
    }

    // Parse child path segments
    let mut child_path = Vec::new();
    for part in parts.iter().skip(1) {
        if part.is_empty() || !part.chars().all(|c| c.is_ascii_digit()) {
            return Err(BeadsError::InvalidId { id: id.to_string() });
        }
        match part.parse::<u32>() {
            Ok(n) => child_path.push(n),
            Err(_) => return Err(BeadsError::InvalidId { id: id.to_string() }),
        }
    }

    Ok(ParsedId {
        prefix: prefix.to_string(),
        hash,
        child_path,
    })
}

/// Validate that an ID has the expected prefix.
///
/// # Arguments
///
/// * `id` - The ID to validate
/// * `expected_prefix` - The primary expected prefix
/// * `allowed_prefixes` - Additional allowed prefixes
///
/// # Errors
///
/// Returns `PrefixMismatch` if the prefix doesn't match expected or allowed.
pub fn validate_prefix(id: &str, expected_prefix: &str, allowed_prefixes: &[String]) -> Result<()> {
    let parsed = parse_id(id)?;

    if parsed.prefix == expected_prefix {
        return Ok(());
    }

    if allowed_prefixes.contains(&parsed.prefix) {
        return Ok(());
    }

    Err(BeadsError::PrefixMismatch {
        expected: expected_prefix.to_string(),
        found: parsed.prefix,
    })
}

/// Normalize an ID to consistent lowercase format.
#[must_use]
pub fn normalize_id(id: &str) -> String {
    id.to_lowercase()
}

/// Normalize a configured issue prefix into a valid runtime form.
///
/// This trims whitespace, lowercases ASCII letters, removes unsupported
/// characters, and clamps the prefix to the maximum supported length. If no
/// usable characters remain, it falls back to `br`.
#[must_use]
pub fn normalize_prefix(prefix: &str) -> String {
    let normalized: String = prefix
        .trim()
        .chars()
        .filter_map(|c| {
            let normalized = c.to_ascii_lowercase();
            (normalized.is_ascii_lowercase()
                || normalized.is_ascii_digit()
                || matches!(normalized, '_' | '-' | '.' | ':' | '#'))
            .then_some(normalized)
        })
        .take(MAX_ID_PREFIX_LEN)
        .collect();

    // Strip trailing separator chars to prevent double-hyphens during ID generation
    let normalized = normalized
        .trim_end_matches(['_', '-', '.', ':', '#'])
        .to_string();

    if normalized.is_empty() {
        "br".to_string()
    } else {
        normalized
    }
}

/// Abbreviate a long auto-derived issue ID prefix.
///
/// If the normalized prefix is short enough (<= 6 chars), it is returned
/// unchanged. Otherwise, multi-word prefixes are abbreviated to their initials
/// and single-word prefixes fall back to their first three alphanumeric chars.
#[must_use]
pub fn abbreviate_prefix(prefix: &str) -> String {
    let normalized = normalize_prefix(prefix);
    if normalized.len() <= 6 {
        return normalized;
    }

    let segments: Vec<&str> = normalized
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|segment| !segment.is_empty())
        .collect();

    if segments.len() > 1 {
        let abbrev: String = segments
            .iter()
            .filter_map(|segment| segment.chars().next())
            .collect();
        if abbrev.len() > 1 {
            return abbrev;
        }
    }

    let fallback: String = normalized
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .take(3)
        .collect();
    if fallback.is_empty() {
        normalized
    } else {
        fallback
    }
}

/// Check if a string looks like a valid issue ID format.
#[must_use]
pub fn is_valid_id_format(id: &str) -> bool {
    parse_id(id).is_ok()
}

// ============================================================================
// ID Resolution
// ============================================================================

/// Configuration for ID resolution.
#[derive(Debug, Clone)]
pub struct ResolverConfig {
    /// Default prefix to use when input lacks one.
    pub default_prefix: String,
    /// Additional allowed prefixes for matching.
    pub allowed_prefixes: Vec<String>,
    /// Whether to allow substring matching on hash portion.
    pub allow_substring_match: bool,
}

impl Default for ResolverConfig {
    fn default() -> Self {
        Self {
            default_prefix: "br".to_string(),
            allowed_prefixes: Vec::new(),
            allow_substring_match: true,
        }
    }
}

impl ResolverConfig {
    /// Create a new resolver config with the given default prefix.
    #[must_use]
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            default_prefix: normalize_prefix(&prefix.into()),
            ..Default::default()
        }
    }
}

/// Resolved ID result from the resolution process.
#[derive(Debug, Clone)]
pub struct ResolvedId {
    /// The full resolved ID.
    pub id: String,
    /// How the ID was matched.
    pub match_type: MatchType,
    /// The original input that was resolved.
    pub original_input: String,
}

/// How an ID was matched during resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchType {
    /// Exact match on full ID.
    Exact,
    /// Matched after prepending the default prefix.
    PrefixNormalized,
    /// Matched via substring on hash portion.
    Substring,
}

/// ID resolver that resolves partial IDs to full IDs.
///
/// Resolution order:
/// 1. Exact ID match
/// 2. Normalize: if missing prefix, prepend `default_prefix-` and retry
/// 3. Substring match on hash portion across all prefixes
/// 4. Ambiguity => error with candidate list
#[derive(Debug, Clone)]
pub struct IdResolver {
    config: ResolverConfig,
}

impl IdResolver {
    /// Create a new ID resolver with the given config.
    #[must_use]
    pub const fn new(config: ResolverConfig) -> Self {
        Self { config }
    }

    /// Create a new ID resolver with default config.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::new(ResolverConfig::default())
    }

    /// Create a new ID resolver with the given default prefix.
    #[must_use]
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self::new(ResolverConfig::with_prefix(prefix))
    }

    /// Get the default prefix.
    #[must_use]
    pub fn default_prefix(&self) -> &str {
        &self.config.default_prefix
    }

    /// Resolve a partial ID to a full ID.
    ///
    /// The `lookup_fn` should return all IDs that match the given pattern.
    /// - For exact match, pass the ID and expect 0 or 1 results.
    /// - For substring match, pass the pattern and expect 0-N results.
    ///
    /// The `exists_fn` should check if an exact ID exists.
    ///
    /// # Errors
    ///
    /// - `IssueNotFound` if no match is found.
    /// - `AmbiguousId` if multiple matches are found.
    ///
    /// # Panics
    ///
    /// This function will not panic under normal operation. The internal
    /// `.expect()` call is guarded by a length check ensuring exactly one match exists.
    pub fn resolve<F, G>(
        &self,
        input: &str,
        exists_fn: F,
        substring_match_fn: G,
    ) -> Result<ResolvedId>
    where
        F: Fn(&str) -> bool,
        G: Fn(&str) -> Vec<String>,
    {
        let input = input.trim();

        if input.is_empty() {
            return Err(BeadsError::InvalidId { id: String::new() });
        }

        // Normalize input to lowercase
        let normalized = normalize_id(input);

        // Step 1: Try exact match
        if exists_fn(&normalized) {
            return Ok(ResolvedId {
                id: normalized,
                match_type: MatchType::Exact,
                original_input: input.to_string(),
            });
        }

        // Step 2: If no dash (missing prefix), prepend default prefix and retry
        if !normalized.contains('-') {
            let with_prefix = format!("{}-{}", self.config.default_prefix, normalized);
            if exists_fn(&with_prefix) {
                return Ok(ResolvedId {
                    id: with_prefix,
                    match_type: MatchType::PrefixNormalized,
                    original_input: input.to_string(),
                });
            }
        }

        // Step 3: Substring match on hash portion
        if self.config.allow_substring_match {
            // Extract the potential hash portion (after dash, or entire input if no dash)
            let (prefix, hash_pattern) = split_prefix_remainder(&normalized)
                .map_or((None, normalized.as_str()), |(p, r)| (Some(p), r));

            if !hash_pattern.is_empty() {
                let mut matches = substring_match_fn(hash_pattern);

                if let Some(p) = prefix {
                    let expected_prefix = format!("{p}-");
                    matches.retain(|id| id.starts_with(&expected_prefix));
                }

                match matches.len() {
                    0 => {
                        // No matches found
                    }
                    1 => {
                        return Ok(ResolvedId {
                            id: matches.into_iter().next().unwrap_or_default(),
                            match_type: MatchType::Substring,
                            original_input: input.to_string(),
                        });
                    }
                    _ => {
                        // Multiple matches - ambiguous
                        return Err(BeadsError::AmbiguousId {
                            partial: input.to_string(),
                            matches,
                        });
                    }
                }
            }
        }

        // Step 4: No match found
        Err(BeadsError::IssueNotFound {
            id: input.to_string(),
        })
    }

    /// Resolve a partial ID while allowing the lookup callbacks to fail.
    ///
    /// This is the same algorithm as [`IdResolver::resolve`], but it preserves
    /// storage/query errors instead of forcing callers to coerce them into
    /// `false` or an empty match set.
    ///
    /// # Errors
    ///
    /// - Propagates any error returned by `exists_fn` or `substring_match_fn`
    /// - `IssueNotFound` if no match is found
    /// - `AmbiguousId` if multiple matches are found
    pub fn resolve_fallible<F, G>(
        &self,
        input: &str,
        exists_fn: F,
        substring_match_fn: G,
    ) -> Result<ResolvedId>
    where
        F: Fn(&str) -> Result<bool>,
        G: Fn(&str) -> Result<Vec<String>>,
    {
        let input = input.trim();

        if input.is_empty() {
            return Err(BeadsError::InvalidId { id: String::new() });
        }

        let normalized = normalize_id(input);

        if exists_fn(&normalized)? {
            return Ok(ResolvedId {
                id: normalized,
                match_type: MatchType::Exact,
                original_input: input.to_string(),
            });
        }

        if !normalized.contains('-') {
            let with_prefix = format!("{}-{}", self.config.default_prefix, normalized);
            if exists_fn(&with_prefix)? {
                return Ok(ResolvedId {
                    id: with_prefix,
                    match_type: MatchType::PrefixNormalized,
                    original_input: input.to_string(),
                });
            }
        }

        if self.config.allow_substring_match {
            let (prefix, hash_pattern) = split_prefix_remainder(&normalized)
                .map_or((None, normalized.as_str()), |(p, r)| (Some(p), r));

            if !hash_pattern.is_empty() {
                let mut matches = substring_match_fn(hash_pattern)?;

                if let Some(p) = prefix {
                    let expected_prefix = format!("{p}-");
                    matches.retain(|id| id.starts_with(&expected_prefix));
                }

                match matches.len() {
                    0 => {}
                    1 => {
                        return Ok(ResolvedId {
                            id: matches.into_iter().next().unwrap_or_default(),
                            match_type: MatchType::Substring,
                            original_input: input.to_string(),
                        });
                    }
                    _ => {
                        return Err(BeadsError::AmbiguousId {
                            partial: input.to_string(),
                            matches,
                        });
                    }
                }
            }
        }

        Err(BeadsError::IssueNotFound {
            id: input.to_string(),
        })
    }

    /// Resolve multiple IDs, returning results for each.
    ///
    /// If any ID fails to resolve, returns the first error.
    ///
    /// # Errors
    ///
    /// Returns the first error encountered if any ID fails to resolve.
    /// See [`IdResolver::resolve`] for the specific error conditions.
    pub fn resolve_all<F, G>(
        &self,
        inputs: &[String],
        exists_fn: F,
        substring_match_fn: G,
    ) -> Result<Vec<ResolvedId>>
    where
        F: Fn(&str) -> bool,
        G: Fn(&str) -> Vec<String>,
    {
        inputs
            .iter()
            .map(|input| self.resolve(input, &exists_fn, &substring_match_fn))
            .collect()
    }

    /// Resolve multiple IDs while preserving lookup callback errors.
    ///
    /// # Errors
    ///
    /// Returns the first callback or resolution error encountered.
    pub fn resolve_all_fallible<F, G>(
        &self,
        inputs: &[String],
        exists_fn: F,
        substring_match_fn: G,
    ) -> Result<Vec<ResolvedId>>
    where
        F: Fn(&str) -> Result<bool>,
        G: Fn(&str) -> Result<Vec<String>>,
    {
        inputs
            .iter()
            .map(|input| self.resolve_fallible(input, &exists_fn, &substring_match_fn))
            .collect()
    }
}

/// Find all issue IDs that contain the given substring in their hash portion.
///
/// This is a helper function for implementing the `substring_match_fn` parameter
/// of `IdResolver::resolve`. The caller provides the list of all known IDs.
#[must_use]
pub fn find_matching_ids(all_ids: &[String], hash_substring: &str) -> Vec<String> {
    // Split search pattern into base hash and optional child path so that
    // searching for "64up6.4" correctly matches "bd-64up6.4" instead of
    // stripping the child suffix from the candidate and failing.
    let (search_base, search_child) = match hash_substring.split_once('.') {
        Some((base, child)) => (base, Some(child)),
        None => (hash_substring, None),
    };

    all_ids
        .iter()
        .filter(|id| {
            split_prefix_remainder(id).is_some_and(|(_, remainder)| {
                let base_hash = remainder.split('.').next().unwrap_or(remainder);
                if !base_hash.contains(search_base) {
                    return false;
                }
                match search_child {
                    Some(child) => remainder
                        .split_once('.')
                        .is_some_and(|(_, candidate_child)| candidate_child == child),
                    None => true,
                }
            })
        })
        .cloned()
        .collect()
}

/// Quick helper to resolve a single ID with default settings.
///
/// This is useful for simple cases where you just need to resolve one ID.
///
/// # Errors
///
/// - `IssueNotFound` if no match is found.
/// - `AmbiguousId` if multiple matches are found.
/// - `InvalidId` if the input is empty.
pub fn resolve_id<F, G>(input: &str, exists_fn: F, substring_match_fn: G) -> Result<String>
where
    F: Fn(&str) -> bool,
    G: Fn(&str) -> Vec<String>,
{
    let resolver = IdResolver::with_defaults();
    resolver
        .resolve(input, exists_fn, substring_match_fn)
        .map(|r| r.id)
}

/// Quick helper to resolve a single ID with fallible lookup callbacks.
///
/// # Errors
///
/// Propagates any lookup error in addition to the usual resolution errors.
pub fn resolve_id_fallible<F, G>(input: &str, exists_fn: F, substring_match_fn: G) -> Result<String>
where
    F: Fn(&str) -> Result<bool>,
    G: Fn(&str) -> Result<Vec<String>>,
{
    let resolver = IdResolver::with_defaults();
    resolver
        .resolve_fallible(input, exists_fn, substring_match_fn)
        .map(|r| r.id)
}

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

    // ========================================================================
    // ID Resolution Tests
    // ========================================================================

    fn mock_db() -> Vec<String> {
        vec![
            "br-abc123".to_string(),
            "br-abd456".to_string(),
            "br-xyz789".to_string(),
            "br-abc123.1".to_string(),  // child
            "other-def111".to_string(), // different prefix
        ]
    }

    fn exists_in_mock(id: &str) -> bool {
        mock_db().contains(&id.to_string())
    }

    fn substring_in_mock(pattern: &str) -> Vec<String> {
        find_matching_ids(&mock_db(), pattern)
    }

    #[test]
    fn test_resolve_exact_match() {
        let resolver = IdResolver::with_defaults();
        let result = resolver
            .resolve("br-abc123", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-abc123");
        assert_eq!(result.match_type, MatchType::Exact);
    }

    #[test]
    fn test_resolve_prefix_normalized() {
        let resolver = IdResolver::with_defaults();
        let result = resolver
            .resolve("abc123", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-abc123");
        assert_eq!(result.match_type, MatchType::PrefixNormalized);
    }

    #[test]
    fn test_resolve_substring_match() {
        let resolver = IdResolver::with_defaults();
        // "xyz" should uniquely match "br-xyz789"
        let result = resolver
            .resolve("xyz", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-xyz789");
        assert_eq!(result.match_type, MatchType::Substring);
    }

    #[test]
    fn test_resolve_ambiguous() {
        let resolver = IdResolver::with_defaults();
        // "ab" matches both "br-abc123" and "br-abd456"
        let result = resolver.resolve("ab", exists_in_mock, substring_in_mock);
        assert!(result.is_err());
        if let Err(BeadsError::AmbiguousId { partial, matches }) = result {
            assert_eq!(partial, "ab");
            assert!(matches.contains(&"br-abc123".to_string()));
            assert!(matches.contains(&"br-abd456".to_string()));
        } else {
            unreachable!("Expected AmbiguousId error");
        }
    }

    #[test]
    fn test_resolve_not_found() {
        let resolver = IdResolver::with_defaults();
        let result = resolver.resolve("nonexistent", exists_in_mock, substring_in_mock);
        assert!(result.is_err());
        if let Err(BeadsError::IssueNotFound { id }) = result {
            assert_eq!(id, "nonexistent");
        } else {
            unreachable!("Expected IssueNotFound error");
        }
    }

    #[test]
    fn test_resolve_child_id() {
        let resolver = IdResolver::with_defaults();
        let result = resolver
            .resolve("br-abc123.1", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-abc123.1");
        assert_eq!(result.match_type, MatchType::Exact);
    }

    #[test]
    fn test_resolve_case_insensitive() {
        let resolver = IdResolver::with_defaults();
        let result = resolver
            .resolve("BR-ABC123", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-abc123");
    }

    #[test]
    fn test_resolve_with_custom_prefix() {
        let custom_db = vec!["proj-aaa111".to_string()];
        let exists = |id: &str| custom_db.contains(&id.to_string());
        let substring = |pattern: &str| find_matching_ids(&custom_db, pattern);

        let resolver = IdResolver::with_prefix("proj");
        let result = resolver.resolve("aaa111", exists, substring).unwrap();
        assert_eq!(result.id, "proj-aaa111");
        assert_eq!(result.match_type, MatchType::PrefixNormalized);
    }

    #[test]
    fn test_resolve_empty_input() {
        let resolver = IdResolver::with_defaults();
        let result = resolver.resolve("", exists_in_mock, substring_in_mock);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_whitespace_trimmed() {
        let resolver = IdResolver::with_defaults();
        let result = resolver
            .resolve("  br-abc123  ", exists_in_mock, substring_in_mock)
            .unwrap();
        assert_eq!(result.id, "br-abc123");
    }

    #[test]
    fn test_resolve_fallible_propagates_lookup_error() {
        let resolver = IdResolver::with_defaults();
        let result = resolver.resolve_fallible(
            "br-abc123",
            |_id| Err(BeadsError::Config("lookup failed".to_string())),
            |_hash| Ok(Vec::new()),
        );
        assert!(matches!(result, Err(BeadsError::Config(message)) if message == "lookup failed"));
    }

    #[test]
    fn test_resolve_all_fallible_propagates_lookup_error() {
        let resolver = IdResolver::with_defaults();
        let inputs = vec!["br-abc123".to_string(), "br-xyz789".to_string()];
        let result = resolver.resolve_all_fallible(
            &inputs,
            |_id| Err(BeadsError::Config("exists lookup failed".to_string())),
            |_hash| Ok(Vec::new()),
        );
        assert!(
            matches!(result, Err(BeadsError::Config(message)) if message == "exists lookup failed")
        );
    }

    #[test]
    fn test_find_matching_ids_substring() {
        let ids = mock_db();
        let matches = find_matching_ids(&ids, "abc");
        assert!(matches.contains(&"br-abc123".to_string()));
        // Note: br-abc123.1 is a child and its base hash contains "abc"
        assert!(matches.contains(&"br-abc123.1".to_string()));
    }

    #[test]
    fn test_find_matching_ids_no_match() {
        let ids = mock_db();
        let matches = find_matching_ids(&ids, "zzz");
        assert!(matches.is_empty());
    }

    // ========================================================================
    // Original Tests
    // ========================================================================

    #[test]
    fn test_base36_encode() {
        assert_eq!(base36_encode(0), "0");
        assert_eq!(base36_encode(10), "a");
        assert_eq!(base36_encode(35), "z");
        assert_eq!(base36_encode(36), "10");
    }

    #[test]
    fn test_compute_id_hash_length() {
        let input = "test input";
        let hash3 = compute_id_hash(input, 3);
        assert_eq!(hash3.len(), 3);

        let hash8 = compute_id_hash(input, 8);
        assert_eq!(hash8.len(), 8);
    }

    #[test]
    fn test_generate_id_seed() {
        let now = Utc::now();
        let seed = generate_id_seed("title", Some("desc"), Some("me"), now, 0);
        assert!(seed.contains("5:title"));
        assert!(seed.contains("4:desc"));
        assert!(seed.contains("2:me"));
        assert!(seed.ends_with("1:0"));
    }

    #[test]
    fn test_parse_id_root() {
        let parsed = parse_id("bd-abc123").unwrap();
        assert_eq!(parsed.prefix, "bd");
        assert_eq!(parsed.hash, "abc123");
        assert!(parsed.child_path.is_empty());
        assert!(parsed.is_root());
        assert_eq!(parsed.depth(), 0);
    }

    #[test]
    fn test_parse_id_hyphenated_prefix() {
        let parsed = parse_id("bead-me-up-3e9").unwrap();
        assert_eq!(parsed.prefix, "bead-me-up");
        assert_eq!(parsed.hash, "3e9");
        assert!(parsed.child_path.is_empty());

        let parsed2 = parse_id("document-intelligence-0sa.2").unwrap();
        assert_eq!(parsed2.prefix, "document-intelligence");
        assert_eq!(parsed2.hash, "0sa");
        assert_eq!(parsed2.child_path, vec![2]);
    }

    #[test]
    fn test_parse_id_hyphenated_prefix_word_like_hash() {
        // "my-proj" is prefix. "abcd" is hash (4 chars, no digits).
        // Previously failed because "abcd" was deemed unlikely hash, causing split at first dash.
        let parsed = parse_id("my-proj-abcd").unwrap();
        assert_eq!(parsed.prefix, "my-proj");
        assert_eq!(parsed.hash, "abcd");
    }

    #[test]
    fn test_parse_id_child() {
        let parsed = parse_id("bd-abc123.1").unwrap();
        assert_eq!(parsed.prefix, "bd");
        assert_eq!(parsed.hash, "abc123");
        assert_eq!(parsed.child_path, vec![1]);
        assert!(!parsed.is_root());
        assert_eq!(parsed.depth(), 1);
    }

    #[test]
    fn test_parse_id_grandchild() {
        let parsed = parse_id("bd-abc123.1.2").unwrap();
        assert_eq!(parsed.child_path, vec![1, 2]);
        assert_eq!(parsed.depth(), 2);
    }

    #[test]
    fn test_parse_id_external_style() {
        let parsed = parse_id("external:jira-123").unwrap();
        assert_eq!(parsed.prefix, "external:jira");
        assert_eq!(parsed.hash, "123");

        let parsed2 = parse_id("ext:github#repo-456").unwrap();
        assert_eq!(parsed2.prefix, "ext:github#repo");
        assert_eq!(parsed2.hash, "456");
    }

    #[test]
    fn test_parse_id_invalid_no_dash() {
        assert!(parse_id("bdabc123").is_err());
    }

    #[test]
    fn test_parse_id_invalid_empty_hash() {
        assert!(parse_id("bd-").is_err());
    }

    #[test]
    fn test_parse_id_invalid_uppercase() {
        assert!(parse_id("bd-ABC123").is_err());
    }

    #[test]
    fn test_parse_id_long_hash() {
        // Fallback generates 12 chars + potential nonce.
        // parse_id used to limit to 8, but now allows up to MAX_ID_HASH_LEN.
        let long_id = "bd-abc123456789";
        let parsed = parse_id(long_id).unwrap();
        assert_eq!(parsed.hash, "abc123456789");
    }

    #[test]
    fn test_parsed_id_parent() {
        let child = parse_id("bd-abc123.1").unwrap();
        assert_eq!(child.parent(), Some("bd-abc123".to_string()));

        let grandchild = parse_id("bd-abc123.1.2").unwrap();
        assert_eq!(grandchild.parent(), Some("bd-abc123.1".to_string()));

        let root = parse_id("bd-abc123").unwrap();
        assert_eq!(root.parent(), None);
    }

    #[test]
    fn test_parsed_id_to_string() {
        let root = parse_id("bd-abc123").unwrap();
        assert_eq!(root.to_id_string(), "bd-abc123");

        let child = parse_id("bd-abc123.1.2").unwrap();
        assert_eq!(child.to_id_string(), "bd-abc123.1.2");
    }

    #[test]
    fn test_parsed_id_is_child_of() {
        let child = parse_id("bd-abc123.1").unwrap();
        assert!(child.is_child_of("bd-abc123"));
        assert!(!child.is_child_of("bd-xyz"));

        let grandchild = parse_id("bd-abc123.1.2").unwrap();
        assert!(grandchild.is_child_of("bd-abc123"));
        assert!(grandchild.is_child_of("bd-abc123.1"));
    }

    #[test]
    fn test_validate_prefix() {
        assert!(validate_prefix("bd-abc123", "bd", &[]).is_ok());
        assert!(validate_prefix("bd-abc123", "other", &["bd".to_string()]).is_ok());
        assert!(validate_prefix("bd-abc123", "other", &[]).is_err());
    }

    #[test]
    fn test_normalize_prefix_sanitizes_and_lowercases() {
        assert_eq!(normalize_prefix("  Project-Name_2!  "), "project-name_2");
        assert_eq!(normalize_prefix("!!!"), "br");
    }

    #[test]
    fn test_abbreviate_prefix_handles_mixed_case_and_underscores() {
        assert_eq!(abbreviate_prefix("My_Project-Name"), "mpn");
        assert_eq!(abbreviate_prefix("superlongname"), "sup");
    }

    #[test]
    fn test_is_valid_id_format() {
        assert!(is_valid_id_format("bd-abc123"));
        assert!(is_valid_id_format("bd-abc123.1.2"));
        assert!(!is_valid_id_format("invalid"));
        assert!(!is_valid_id_format("bd-ABC")); // uppercase
    }

    #[test]
    fn test_id_generator_optimal_length() {
        let id_gen = IdGenerator::with_defaults();

        // Small DB should use minimum length
        assert_eq!(id_gen.optimal_length(0), 3);
        assert_eq!(id_gen.optimal_length(10), 3);

        // Large DB should need more characters
        let len_1000 = id_gen.optimal_length(1000);
        assert!(len_1000 >= 3);
        assert!(len_1000 <= 8);
    }

    #[test]
    fn test_id_generator_generate() {
        let id_gen = IdGenerator::with_defaults();
        let now = Utc::now();

        let id = id_gen.generate(
            "Test Issue",
            Some("Description"),
            Some("user"),
            now,
            0,
            |_| false,
        );

        assert!(id.starts_with("br-"));
        assert!(is_valid_id_format(&id));
    }

    #[test]
    fn test_id_generator_collision_handling() {
        let id_gen = IdGenerator::with_defaults();
        let now = Utc::now();

        let mut generated = std::collections::HashSet::new();

        // Generate first ID
        let id1 = id_gen.generate("Test", None, None, now, 0, |id| generated.contains(id));
        generated.insert(id1.clone());

        // Generate second ID - should get different one due to collision check
        let id2 = id_gen.generate("Test", None, None, now, 0, |id| generated.contains(id));

        assert_ne!(id1, id2);
    }

    #[test]
    fn test_desperate_fallback_id_format() {
        // Simulate the ID produced by the desperate fallback: prefix-hash-nonce
        let prefix = "bd";
        let hash = "abc123456789";
        let nonce = 1001;

        // Ensure the fixed format is valid
        let good_id = format!("{prefix}-{hash}{nonce}");
        assert!(
            parse_id(&good_id).is_ok(),
            "Fixed fallback format should parse correctly"
        );
    }
}