git-perf 0.22.0

Track, plot, and statistically validate simple measurements using git-notes for storage
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
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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
use anyhow::Result;
use config::{Config, ConfigError, File, FileFormat};
use std::{
    collections::HashMap,
    env,
    fs::File as StdFile,
    io::{Read, Write},
    path::{Path, PathBuf},
};
use toml_edit::{value, DocumentMut, Item, Table};

use crate::defaults;
use crate::git::git_interop::{get_head_revision, get_repository_root};

// Import the CLI types for dispersion method
use git_perf_cli_types::DispersionMethod;

/// Extension trait to get values with parent table fallback.
///
/// This provides a consistent way to retrieve a value for a given logical name
/// and fall back to the parent table when the specific name is not present.
pub trait ConfigParentFallbackExt {
    /// Returns a string value for `{parent}.{name}.{key}` if available.
    /// Otherwise falls back to `{parent}.{key}` (parent table defaults).
    ///
    /// The `parent` is the parent table name (e.g., "measurement").
    /// The `name` is the specific identifier within that parent.
    fn get_with_parent_fallback(&self, parent: &str, name: &str, key: &str) -> Option<String>;
}

impl ConfigParentFallbackExt for Config {
    fn get_with_parent_fallback(&self, parent: &str, name: &str, key: &str) -> Option<String> {
        // Use table-based navigation instead of building a dot-path key string.
        // The config crate's path expression parser only accepts [a-zA-Z0-9_-] as identifier
        // characters, so dot-path lookup silently fails for measurement names that contain
        // '::' or '/' (e.g. Criterion benchmark names like "bench::group/bench/1::stat").
        if let Ok(mut parent_table) = self.get_table(parent) {
            // Try specific measurement first: parent[name][key]
            if let Some(name_value) = parent_table.remove(name) {
                if let Ok(mut name_table) = name_value.into_table() {
                    if let Some(key_value) = name_table.remove(key) {
                        if let Ok(s) = key_value.into_string() {
                            return Some(s);
                        }
                    }
                }
            }

            // Fallback to parent-level default: parent[key]
            if let Some(key_value) = parent_table.remove(key) {
                if let Ok(s) = key_value.into_string() {
                    return Some(s);
                }
            }
        }

        None
    }
}

/// Get the main repository config path (always in repo root)
fn get_main_config_path() -> Result<PathBuf> {
    // Use git to find the repository root
    let repo_root = get_repository_root().map_err(|e| {
        anyhow::anyhow!(
            "Failed to determine repository root - must be run from within a git repository: {}",
            e
        )
    })?;

    if repo_root.is_empty() {
        return Err(anyhow::anyhow!(
            "Repository root is empty - must be run from within a git repository"
        ));
    }

    Ok(PathBuf::from(repo_root).join(".gitperfconfig"))
}

/// Write config to the main repository directory (always in repo root)
pub fn write_config(conf: &str) -> Result<()> {
    let path = get_main_config_path()?;
    let mut f = StdFile::create(path)?;
    f.write_all(conf.as_bytes())?;
    Ok(())
}

/// Read hierarchical configuration (system -> local override)
pub fn read_hierarchical_config() -> Result<Config, ConfigError> {
    let mut builder = Config::builder();

    // 1. System-wide config (XDG_CONFIG_HOME or ~/.config/git-perf/config.toml)
    if let Ok(xdg_config_home) = env::var("XDG_CONFIG_HOME") {
        let system_config_path = Path::new(&xdg_config_home)
            .join("git-perf")
            .join("config.toml");
        builder = builder.add_source(
            File::from(system_config_path)
                .format(FileFormat::Toml)
                .required(false),
        );
    } else if let Some(home) = dirs_next::home_dir() {
        let system_config_path = home.join(".config").join("git-perf").join("config.toml");
        builder = builder.add_source(
            File::from(system_config_path)
                .format(FileFormat::Toml)
                .required(false),
        );
    }

    // 2. Local config (repository .gitperfconfig) - this overrides system config
    if let Some(local_path) = find_config_path() {
        builder = builder.add_source(
            File::from(local_path)
                .format(FileFormat::Toml)
                .required(false),
        );
    }

    builder.build()
}

fn find_config_path() -> Option<PathBuf> {
    // Use get_main_config_path but handle errors gracefully
    let path = get_main_config_path().ok()?;
    if path.is_file() {
        Some(path)
    } else {
        None
    }
}

fn read_config_from_file<P: AsRef<Path>>(file: P) -> Result<String> {
    let mut conf_str = String::new();
    StdFile::open(file)?.read_to_string(&mut conf_str)?;
    Ok(conf_str)
}

fn read_raw_gitperfconfig() -> Option<String> {
    let path = find_config_path()?;
    read_config_from_file(path).ok()
}

fn read_gitperfconfig_document() -> Option<DocumentMut> {
    read_raw_gitperfconfig()?.parse::<DocumentMut>().ok()
}

fn parse_environment_from_doc(doc: &DocumentMut) -> HashMap<String, Vec<String>> {
    let Some(table) = doc.get("environment").and_then(|item| item.as_table()) else {
        return HashMap::new();
    };
    let mut result = HashMap::new();
    for (key, item) in table.iter() {
        if let Some(s) = item.as_str() {
            result.insert(key.to_string(), vec![s.to_string()]);
        } else if let Some(arr) = item.as_array() {
            let vars: Vec<String> = arr
                .iter()
                .filter_map(|v| v.as_str())
                .map(String::from)
                .collect();
            if !vars.is_empty() {
                result.insert(key.to_string(), vars);
            }
        } else {
            log::warn!(
                "Ignoring unsupported value type for [environment] key '{}'",
                key
            );
        }
    }
    result
}

fn parse_defaults_from_doc(doc: &DocumentMut) -> HashMap<String, String> {
    let Some(table) = doc.get("defaults").and_then(|item| item.as_table()) else {
        return HashMap::new();
    };
    let mut result = HashMap::new();
    for (key, item) in table.iter() {
        if let Some(s) = item.as_str() {
            result.insert(key.to_string(), s.to_string());
        } else {
            log::warn!("Ignoring non-string value for [defaults] key '{}'", key);
        }
    }
    result
}

/// Returns the `[environment]` mapping from `.gitperfconfig`.
///
/// Each key maps to one or more environment variable names to look up at
/// measurement time (first non-empty value wins for multi-source lists).
/// Returns an empty map when the section is absent or the file cannot be parsed.
#[must_use]
pub fn read_environment_config() -> HashMap<String, Vec<String>> {
    read_gitperfconfig_document()
        .map(|doc| parse_environment_from_doc(&doc))
        .unwrap_or_default()
}

/// Returns the `[defaults]` mapping from `.gitperfconfig`.
///
/// Each key maps to a static string value used as a fallback when the
/// corresponding `[environment]` variable is not set.
/// Returns an empty map when the section is absent or the file cannot be parsed.
#[must_use]
pub fn read_defaults_config() -> HashMap<String, String> {
    read_gitperfconfig_document()
        .map(|doc| parse_defaults_from_doc(&doc))
        .unwrap_or_default()
}

fn apply_env_source(result: &mut HashMap<String, String>, key: String, var_names: Vec<String>) {
    for var_name in &var_names {
        if let Ok(val) = std::env::var(var_name) {
            if !val.is_empty() {
                result.insert(key, val);
                break;
            }
        }
    }
}

/// Resolves merged key-value pairs for measurement commands by applying precedence:
///   1. `cli_key_values` — highest priority (from --key-value / --metadata)
///   2. `[environment]` section — env var lookup, first-found-wins for multi-source lists
///   3. `[defaults]` section — static fallback values
///
/// When `skip_env` is true the `[environment]` section is ignored entirely.
/// The config file is read and parsed only once regardless of which sections are present.
#[must_use]
pub fn resolve_key_values(
    cli_key_values: &[(String, String)],
    skip_env: bool,
) -> Vec<(String, String)> {
    let mut result: HashMap<String, String> = HashMap::new();

    // Read and parse the config file exactly once for both sections
    if let Some(doc) = read_gitperfconfig_document() {
        // 3. Base layer: [defaults] static values
        for (key, value) in parse_defaults_from_doc(&doc) {
            result.insert(key, value);
        }

        // 2. [environment] env var lookups (skipped when --skip-env)
        if !skip_env {
            for (key, source) in parse_environment_from_doc(&doc) {
                apply_env_source(&mut result, key, source);
            }
        }
    }

    // 1. CLI args always win — insert last to overwrite everything
    for (key, value) in cli_key_values {
        result.insert(key.clone(), value.clone());
    }

    result.into_iter().collect()
}

#[must_use]
pub fn determine_epoch_from_config(measurement: &str) -> Option<u32> {
    let config = read_hierarchical_config()
        .map_err(|e| {
            // Log the error but don't fail - this is expected when no config exists
            log::debug!("Could not read hierarchical config: {}", e);
        })
        .ok()?;

    // Use parent fallback for measurement epoch
    config
        .get_with_parent_fallback("measurement", measurement, "epoch")
        .and_then(|s| u32::from_str_radix(&s, 16).ok())
}

pub fn bump_epoch_in_conf(measurement: &str, conf_str: &mut String) -> Result<()> {
    let mut conf = conf_str
        .parse::<DocumentMut>()
        .map_err(|e| anyhow::anyhow!("Failed to parse config: {}", e))?;

    let head_revision = get_head_revision()?;

    // Ensure that non-inline tables are written in an empty config file
    if !conf.contains_key("measurement") {
        conf["measurement"] = Item::Table(Table::new());
    }
    if !conf["measurement"]
        .as_table()
        .unwrap()
        .contains_key(measurement)
    {
        conf["measurement"][measurement] = Item::Table(Table::new());
    }

    conf["measurement"][measurement]["epoch"] = value(&head_revision[0..8]);
    *conf_str = conf.to_string();

    Ok(())
}

pub fn bump_epoch(measurement: &str) -> Result<()> {
    // Read existing config from the main config path
    let config_path = get_main_config_path()?;
    let mut conf_str = read_config_from_file(&config_path).unwrap_or_default();

    bump_epoch_in_conf(measurement, &mut conf_str)?;
    write_config(&conf_str)?;
    Ok(())
}

/// Returns the backoff max elapsed seconds from config, or the default if not set.
#[must_use]
pub fn backoff_max_elapsed_seconds() -> u64 {
    match read_hierarchical_config() {
        Ok(config) => {
            if let Ok(seconds) = config.get_int("backoff.max_elapsed_seconds") {
                seconds as u64
            } else {
                defaults::DEFAULT_BACKOFF_MAX_ELAPSED_SECONDS
            }
        }
        Err(_) => defaults::DEFAULT_BACKOFF_MAX_ELAPSED_SECONDS,
    }
}

/// Returns the minimum relative deviation threshold from config, or None if not set.
#[must_use]
pub fn audit_min_relative_deviation(measurement: &str) -> Option<f64> {
    let config = read_hierarchical_config().ok()?;

    if let Some(s) =
        config.get_with_parent_fallback("measurement", measurement, "min_relative_deviation")
    {
        if let Ok(v) = s.parse::<f64>() {
            return Some(v);
        }
    }

    None
}

/// Returns the maximum CoV (Coefficient of Variation = σ/μ × 100%) threshold from
/// config, or None if not set. When tail or head CoV exceeds this value, a warning
/// is emitted in the audit output.
#[must_use]
pub fn audit_max_cov(measurement: &str) -> Option<f64> {
    let config = read_hierarchical_config().ok()?;

    if let Some(s) = config.get_with_parent_fallback("measurement", measurement, "max_cov") {
        if let Ok(v) = s.parse::<f64>() {
            return Some(v);
        }
    }

    None
}

/// Returns the minimum absolute deviation threshold from config, or None if not set.
#[must_use]
pub fn audit_min_absolute_deviation(measurement: &str) -> Option<f64> {
    let config = read_hierarchical_config().ok()?;

    if let Some(s) =
        config.get_with_parent_fallback("measurement", measurement, "min_absolute_deviation")
    {
        if let Ok(v) = s.parse::<f64>() {
            return Some(v);
        }
    }

    None
}

/// Returns the dispersion method from config, or StandardDeviation if not set.
#[must_use]
pub fn audit_dispersion_method(measurement: &str) -> DispersionMethod {
    let Some(config) = read_hierarchical_config().ok() else {
        return DispersionMethod::StandardDeviation;
    };

    if let Some(s) =
        config.get_with_parent_fallback("measurement", measurement, "dispersion_method")
    {
        if let Ok(method) = s.parse::<DispersionMethod>() {
            return method;
        }
    }

    DispersionMethod::StandardDeviation
}

/// Returns the minimum measurements from config, or None if not set.
#[must_use]
pub fn audit_min_measurements(measurement: &str) -> Option<u16> {
    let config = read_hierarchical_config().ok()?;

    if let Some(s) = config.get_with_parent_fallback("measurement", measurement, "min_measurements")
    {
        if let Ok(v) = s.parse::<u16>() {
            return Some(v);
        }
    }

    None
}

/// Returns the aggregate-by reduction function from config, or None if not set.
#[must_use]
pub fn audit_aggregate_by(measurement: &str) -> Option<git_perf_cli_types::ReductionFunc> {
    let config = read_hierarchical_config().ok()?;

    let s = config.get_with_parent_fallback("measurement", measurement, "aggregate_by")?;

    // Parse the string to ReductionFunc
    match s.to_lowercase().as_str() {
        "min" => Some(git_perf_cli_types::ReductionFunc::Min),
        "max" => Some(git_perf_cli_types::ReductionFunc::Max),
        "median" => Some(git_perf_cli_types::ReductionFunc::Median),
        "mean" => Some(git_perf_cli_types::ReductionFunc::Mean),
        _ => None,
    }
}

/// Returns the sigma value from config, or None if not set.
#[must_use]
pub fn audit_sigma(measurement: &str) -> Option<f64> {
    let config = read_hierarchical_config().ok()?;

    if let Some(s) = config.get_with_parent_fallback("measurement", measurement, "sigma") {
        if let Ok(v) = s.parse::<f64>() {
            return Some(v);
        }
    }

    None
}

/// Returns the configured unit for a measurement, or None if not set.
#[must_use]
pub fn measurement_unit(measurement: &str) -> Option<String> {
    let config = read_hierarchical_config().ok()?;
    config.get_with_parent_fallback("measurement", measurement, "unit")
}

/// Returns the report template path from config, or None if not set.
#[must_use]
pub fn report_template_path() -> Option<PathBuf> {
    let config = read_hierarchical_config().ok()?;
    let path_str = config.get_string("report.template_path").ok()?;
    Some(PathBuf::from(path_str))
}

/// Returns the report custom CSS path from config, or None if not set.
#[must_use]
pub fn report_custom_css_path() -> Option<PathBuf> {
    let config = read_hierarchical_config().ok()?;
    let path_str = config.get_string("report.custom_css_path").ok()?;
    Some(PathBuf::from(path_str))
}

/// Returns the report title from config, or None if not set.
#[must_use]
pub fn report_title() -> Option<String> {
    let config = read_hierarchical_config().ok()?;
    config.get_string("report.title").ok()
}

/// Returns the change point configuration for a measurement, applying fallback rules.
///
/// Configuration keys under `[change_point]` or `[change_point."measurement_name"]`:
/// - `enabled`: Enable/disable change point detection (default: true)
/// - `min_data_points`: Minimum data points required (default: 10)
/// - `min_magnitude_pct`: Minimum percentage change to consider significant (default: 5.0)
/// - `confidence_threshold`: Minimum confidence to report a change point (0.0-1.0, default: 0.75)
/// - `penalty`: Penalty factor for PELT algorithm (default: 0.5, lower = more sensitive)
#[must_use]
pub fn change_point_config(measurement: &str) -> crate::change_point::ChangePointConfig {
    let mut config = crate::change_point::ChangePointConfig::default();

    let Ok(file_config) = read_hierarchical_config() else {
        return config;
    };

    // Check if change point detection is disabled globally or per-measurement
    if let Some(enabled_str) =
        file_config.get_with_parent_fallback("change_point", measurement, "enabled")
    {
        if let Ok(enabled) = enabled_str.parse::<bool>() {
            config.enabled = enabled;
        }
    }

    // min_data_points
    if let Some(s) =
        file_config.get_with_parent_fallback("change_point", measurement, "min_data_points")
    {
        if let Ok(v) = s.parse::<usize>() {
            config.min_data_points = v;
        }
    }

    // min_magnitude_pct
    if let Some(s) =
        file_config.get_with_parent_fallback("change_point", measurement, "min_magnitude_pct")
    {
        if let Ok(v) = s.parse::<f64>() {
            config.min_magnitude_pct = v;
        }
    }

    // confidence_threshold
    if let Some(s) =
        file_config.get_with_parent_fallback("change_point", measurement, "confidence_threshold")
    {
        if let Ok(v) = s.parse::<f64>() {
            config.confidence_threshold = v;
        }
    }

    // penalty
    if let Some(s) = file_config.get_with_parent_fallback("change_point", measurement, "penalty") {
        if let Ok(v) = s.parse::<f64>() {
            config.penalty = v;
        }
    }

    config
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_helpers::{
        hermetic_git_env, init_repo, init_repo_with_file, with_isolated_home,
    };
    use std::fs;
    use tempfile::TempDir;

    /// Create a HOME config directory structure and return the config path
    fn create_home_config_dir(home_dir: &Path) -> PathBuf {
        let config_dir = home_dir.join(".config").join("git-perf");
        fs::create_dir_all(&config_dir).unwrap();
        config_dir.join("config.toml")
    }

    #[test]
    fn test_read_epochs() {
        with_isolated_home(|temp_dir| {
            // Create a git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with epochs
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let configfile = r#"[measurement]
# General performance regression
epoch="12344555"

[measurement."something"]
#My comment
epoch="34567898"

[measurement."somethingelse"]
epoch="a3dead"
"#;
            fs::write(&workspace_config_path, configfile).unwrap();

            let epoch = determine_epoch_from_config("something");
            assert_eq!(epoch, Some(0x34567898));

            let epoch = determine_epoch_from_config("somethingelse");
            assert_eq!(epoch, Some(0xa3dead));

            let epoch = determine_epoch_from_config("unspecified");
            assert_eq!(epoch, Some(0x12344555));
        });
    }

    #[test]
    fn test_bump_epochs() {
        with_isolated_home(|temp_dir| {
            // Create a temporary git repository for this test
            env::set_current_dir(temp_dir).unwrap();

            // Set up hermetic git environment
            hermetic_git_env();

            // Initialize git repository with initial commit
            init_repo_with_file(temp_dir);

            let configfile = r#"[measurement."something"]
#My comment
epoch = "34567898"
"#;

            let mut actual = String::from(configfile);
            bump_epoch_in_conf("something", &mut actual).expect("Failed to bump epoch");

            let expected = format!(
                r#"[measurement."something"]
#My comment
epoch = "{}"
"#,
                &get_head_revision().expect("get_head_revision failed")[0..8],
            );

            assert_eq!(actual, expected);
        });
    }

    #[test]
    fn test_bump_new_epoch_and_read_it() {
        with_isolated_home(|temp_dir| {
            // Create a temporary git repository for this test
            env::set_current_dir(temp_dir).unwrap();

            // Set up hermetic git environment
            hermetic_git_env();

            // Initialize git repository with initial commit
            init_repo_with_file(temp_dir);

            let mut conf = String::new();
            bump_epoch_in_conf("mymeasurement", &mut conf).expect("Failed to bump epoch");

            // Write the config to a file and test reading it
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(&config_path, &conf).unwrap();

            let epoch = determine_epoch_from_config("mymeasurement");
            assert!(epoch.is_some());
        });
    }

    #[test]
    fn test_backoff_max_elapsed_seconds() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with explicit value
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = "[backoff]\nmax_elapsed_seconds = 42\n";
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test with explicit value
            assert_eq!(super::backoff_max_elapsed_seconds(), 42);

            // Remove config file and test default
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::backoff_max_elapsed_seconds(), 60);
        });
    }

    #[test]
    fn test_audit_min_relative_deviation() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
min_relative_deviation = 5.0

[measurement."build_time"]
min_relative_deviation = 10.0

[measurement."memory_usage"]
min_relative_deviation = 2.5
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::audit_min_relative_deviation("build_time"),
                Some(10.0)
            );
            assert_eq!(
                super::audit_min_relative_deviation("memory_usage"),
                Some(2.5)
            );
            assert_eq!(
                super::audit_min_relative_deviation("other_measurement"),
                Some(5.0) // Now falls back to parent table
            );

            // Test global (now parent table) setting
            let global_config = r#"
[measurement]
min_relative_deviation = 5.0
"#;
            fs::write(&workspace_config_path, global_config).unwrap();
            assert_eq!(
                super::audit_min_relative_deviation("any_measurement"),
                Some(5.0)
            );

            // Test precedence - measurement-specific overrides global
            let precedence_config = r#"
[measurement]
min_relative_deviation = 5.0

[measurement."build_time"]
min_relative_deviation = 10.0
"#;
            fs::write(&workspace_config_path, precedence_config).unwrap();
            assert_eq!(
                super::audit_min_relative_deviation("build_time"),
                Some(10.0)
            );
            assert_eq!(
                super::audit_min_relative_deviation("other_measurement"),
                Some(5.0)
            );

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_min_relative_deviation("any_measurement"), None);
        });
    }

    #[test]
    fn test_audit_max_cov() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
max_cov = 30.0

[measurement."build_time"]
max_cov = 50.0

[measurement."memory_usage"]
max_cov = 20.0
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            assert_eq!(super::audit_max_cov("build_time"), Some(50.0));
            assert_eq!(super::audit_max_cov("memory_usage"), Some(20.0));
            assert_eq!(super::audit_max_cov("other_measurement"), Some(30.0));

            let global_config = r#"
[measurement]
max_cov = 30.0
"#;
            fs::write(&workspace_config_path, global_config).unwrap();
            assert_eq!(super::audit_max_cov("any_measurement"), Some(30.0));

            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_max_cov("any_measurement"), None);
        });
    }

    #[test]
    fn test_audit_min_absolute_deviation() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
min_absolute_deviation = 5.0

[measurement."build_time"]
min_absolute_deviation = 10.0

[measurement."memory_usage"]
min_absolute_deviation = 2.5
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::audit_min_absolute_deviation("build_time"),
                Some(10.0)
            );
            assert_eq!(
                super::audit_min_absolute_deviation("memory_usage"),
                Some(2.5)
            );
            assert_eq!(
                super::audit_min_absolute_deviation("other_measurement"),
                Some(5.0) // falls back to parent table
            );

            // Test global (parent table) setting
            let global_config = r#"
[measurement]
min_absolute_deviation = 5.0
"#;
            fs::write(&workspace_config_path, global_config).unwrap();
            assert_eq!(
                super::audit_min_absolute_deviation("any_measurement"),
                Some(5.0)
            );

            // Test precedence - measurement-specific overrides global
            let precedence_config = r#"
[measurement]
min_absolute_deviation = 5.0

[measurement."build_time"]
min_absolute_deviation = 10.0
"#;
            fs::write(&workspace_config_path, precedence_config).unwrap();
            assert_eq!(
                super::audit_min_absolute_deviation("build_time"),
                Some(10.0)
            );
            assert_eq!(
                super::audit_min_absolute_deviation("other_measurement"),
                Some(5.0)
            );

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_min_absolute_deviation("any_measurement"), None);
        });
    }

    #[test]
    fn test_audit_dispersion_method() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
dispersion_method = "stddev"

[measurement."build_time"]
dispersion_method = "mad"

[measurement."memory_usage"]
dispersion_method = "stddev"
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::audit_dispersion_method("build_time"),
                git_perf_cli_types::DispersionMethod::MedianAbsoluteDeviation
            );
            assert_eq!(
                super::audit_dispersion_method("memory_usage"),
                git_perf_cli_types::DispersionMethod::StandardDeviation
            );
            assert_eq!(
                super::audit_dispersion_method("other_measurement"),
                git_perf_cli_types::DispersionMethod::StandardDeviation
            );

            // Test global (now parent table) setting
            let global_config = r#"
[measurement]
dispersion_method = "mad"
"#;
            fs::write(&workspace_config_path, global_config).unwrap();
            assert_eq!(
                super::audit_dispersion_method("any_measurement"),
                git_perf_cli_types::DispersionMethod::MedianAbsoluteDeviation
            );

            // Test precedence - measurement-specific overrides global
            let precedence_config = r#"
[measurement]
dispersion_method = "mad"

[measurement."build_time"]
dispersion_method = "stddev"
"#;
            fs::write(&workspace_config_path, precedence_config).unwrap();
            assert_eq!(
                super::audit_dispersion_method("build_time"),
                git_perf_cli_types::DispersionMethod::StandardDeviation
            );
            assert_eq!(
                super::audit_dispersion_method("other_measurement"),
                git_perf_cli_types::DispersionMethod::MedianAbsoluteDeviation
            );

            // Test no config (should return StandardDeviation)
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(
                super::audit_dispersion_method("any_measurement"),
                git_perf_cli_types::DispersionMethod::StandardDeviation
            );
        });
    }

    #[test]
    fn test_bump_epoch_in_conf_creates_proper_tables() {
        // We need to test the production bump_epoch_in_conf function, but it calls get_head_revision()
        // which requires a git repo. Let's temporarily modify the environment to make it work.
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();

            // Set up minimal git environment
            hermetic_git_env();

            init_repo_with_file(temp_dir);

            // Test case 1: Empty config string should create proper table structure
            let mut empty_config = String::new();

            // This calls the actual production function!
            bump_epoch_in_conf("mymeasurement", &mut empty_config).unwrap();

            // Verify that proper table structure is created (not inline tables)
            assert!(empty_config.contains("[measurement]"));
            assert!(empty_config.contains("[measurement.mymeasurement]"));
            assert!(empty_config.contains("epoch ="));
            // Ensure it's NOT using inline table syntax
            assert!(!empty_config.contains("measurement = {"));
            assert!(!empty_config.contains("mymeasurement = {"));

            // Test case 2: Existing config should preserve structure and add new measurement
            let mut existing_config = r#"[measurement]
existing_setting = "value"

[measurement."other"]
epoch = "oldvalue"
"#
            .to_string();

            bump_epoch_in_conf("newmeasurement", &mut existing_config).unwrap();

            // Verify it maintains existing structure and adds new measurement with proper table format
            assert!(existing_config.contains("[measurement.newmeasurement]"));
            assert!(existing_config.contains("existing_setting = \"value\""));
            assert!(existing_config.contains("[measurement.\"other\"]"));
            assert!(!existing_config.contains("newmeasurement = {"));
        });
    }

    #[test]
    fn test_find_config_path_in_git_root() {
        with_isolated_home(|temp_dir| {
            // Create a git repository
            env::set_current_dir(temp_dir).unwrap();

            // Initialize git repository
            init_repo(temp_dir);

            // Create config in git root
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[measurement.\"test\"]\nepoch = \"12345678\"\n",
            )
            .unwrap();

            // Test that find_config_path finds it
            let found_path = find_config_path();
            assert!(found_path.is_some());
            // Canonicalize both paths to handle symlinks (e.g., /var -> /private/var on macOS)
            assert_eq!(
                found_path.unwrap().canonicalize().unwrap(),
                config_path.canonicalize().unwrap()
            );
        });
    }

    #[test]
    fn test_find_config_path_not_found() {
        with_isolated_home(|temp_dir| {
            // Create a git repository but no .gitperfconfig
            env::set_current_dir(temp_dir).unwrap();

            // Initialize git repository
            init_repo(temp_dir);

            // Test that find_config_path returns None when no .gitperfconfig exists
            let found_path = find_config_path();
            assert!(found_path.is_none());
        });
    }

    #[test]
    fn test_hierarchical_config_workspace_overrides_home() {
        with_isolated_home(|temp_dir| {
            // Create a git repository
            env::set_current_dir(temp_dir).unwrap();

            // Initialize git repository
            init_repo(temp_dir);

            // Create home config
            let home_config_path = create_home_config_dir(temp_dir);
            fs::write(
                &home_config_path,
                r#"
[measurement."test"]
backoff_max_elapsed_seconds = 30
audit_min_relative_deviation = 1.0
"#,
            )
            .unwrap();

            // Create workspace config that overrides some values
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &workspace_config_path,
                r#"
[measurement."test"]
backoff_max_elapsed_seconds = 60
"#,
            )
            .unwrap();

            // Set HOME to our temp directory
            env::set_var("HOME", temp_dir);
            env::remove_var("XDG_CONFIG_HOME");

            // Read hierarchical config and verify workspace overrides home
            let config = read_hierarchical_config().unwrap();

            // backoff_max_elapsed_seconds should be overridden by workspace config
            let backoff: i32 = config
                .get("measurement.test.backoff_max_elapsed_seconds")
                .unwrap();
            assert_eq!(backoff, 60);

            // audit_min_relative_deviation should come from home config
            let deviation: f64 = config
                .get("measurement.test.audit_min_relative_deviation")
                .unwrap();
            assert_eq!(deviation, 1.0);
        });
    }

    #[test]
    fn test_determine_epoch_from_config_with_missing_file() {
        // Test that missing config file doesn't panic and returns None
        let temp_dir = TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path()).unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let epoch = determine_epoch_from_config("test_measurement");
        assert!(epoch.is_none());
    }

    #[test]
    fn test_determine_epoch_from_config_with_invalid_toml() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join(".gitperfconfig");
        fs::write(&config_path, "invalid toml content").unwrap();

        fs::create_dir_all(temp_dir.path()).unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let epoch = determine_epoch_from_config("test_measurement");
        assert!(epoch.is_none());
    }

    #[test]
    fn test_write_config_creates_file() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create a subdirectory to test that config is written to repo root
            let subdir = temp_dir.join("a").join("b").join("c");
            fs::create_dir_all(&subdir).unwrap();
            env::set_current_dir(&subdir).unwrap();

            let config_content = "[measurement.\"test\"]\nepoch = \"12345678\"\n";
            write_config(config_content).unwrap();

            // Config should be written to repo root, not subdirectory
            let repo_config_path = temp_dir.join(".gitperfconfig");
            let subdir_config_path = subdir.join(".gitperfconfig");

            assert!(repo_config_path.is_file());
            assert!(!subdir_config_path.is_file());

            let content = fs::read_to_string(&repo_config_path).unwrap();
            assert_eq!(content, config_content);
        });
    }

    #[test]
    fn test_hierarchical_config_system_override() {
        with_isolated_home(|temp_dir| {
            // Create system config (home directory config)
            let system_config_path = create_home_config_dir(temp_dir);
            let system_config = r#"
[measurement]
min_relative_deviation = 5.0
dispersion_method = "mad"

[backoff]
max_elapsed_seconds = 120
"#;
            fs::write(&system_config_path, system_config).unwrap();

            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config that overrides system config
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
min_relative_deviation = 10.0

[measurement."build_time"]
min_relative_deviation = 15.0
dispersion_method = "stddev"
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test hierarchical config reading
            let config = read_hierarchical_config().unwrap();

            // Test that local parent table overrides system config via helper
            use super::ConfigParentFallbackExt;
            assert_eq!(
                config
                    .get_with_parent_fallback(
                        "measurement",
                        "any_measurement",
                        "min_relative_deviation"
                    )
                    .unwrap()
                    .parse::<f64>()
                    .unwrap(),
                10.0
            );
            assert_eq!(
                config
                    .get_with_parent_fallback("measurement", "any_measurement", "dispersion_method")
                    .unwrap(),
                "mad"
            ); // Not overridden in local for parent fallback

            // Test measurement-specific override
            assert_eq!(
                config
                    .get_float("measurement.build_time.min_relative_deviation")
                    .unwrap(),
                15.0
            );
            assert_eq!(
                config
                    .get_string("measurement.build_time.dispersion_method")
                    .unwrap(),
                "stddev"
            );

            // Test that system config is still available for non-overridden values
            assert_eq!(config.get_int("backoff.max_elapsed_seconds").unwrap(), 120);

            // Test the convenience functions
            assert_eq!(audit_min_relative_deviation("build_time"), Some(15.0));
            assert_eq!(
                audit_min_relative_deviation("other_measurement"),
                Some(10.0)
            );
            assert_eq!(
                audit_dispersion_method("build_time"),
                git_perf_cli_types::DispersionMethod::StandardDeviation
            );
            assert_eq!(
                audit_dispersion_method("other_measurement"),
                git_perf_cli_types::DispersionMethod::MedianAbsoluteDeviation
            );
            assert_eq!(backoff_max_elapsed_seconds(), 120);
        });
    }

    #[test]
    fn test_read_config_from_file_missing_file() {
        let temp_dir = TempDir::new().unwrap();
        let nonexistent_file = temp_dir.path().join("does_not_exist.toml");

        // Should return error, not Ok(String::new())
        let result = read_config_from_file(&nonexistent_file);
        assert!(result.is_err());
    }

    #[test]
    fn test_read_config_from_file_valid_content() {
        let temp_dir = TempDir::new().unwrap();
        let config_file = temp_dir.path().join("test_config.toml");
        let expected_content = "[measurement]\nepoch = \"12345678\"\n";

        fs::write(&config_file, expected_content).unwrap();

        let result = read_config_from_file(&config_file);
        assert!(result.is_ok());
        let content = result.unwrap();
        assert_eq!(content, expected_content);

        // This would catch the mutant that returns Ok(String::new())
        assert!(!content.is_empty());
    }

    #[test]
    fn test_audit_min_measurements() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
min_measurements = 5

[measurement."build_time"]
min_measurements = 10

[measurement."memory_usage"]
min_measurements = 3
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(super::audit_min_measurements("build_time"), Some(10));
            assert_eq!(super::audit_min_measurements("memory_usage"), Some(3));
            assert_eq!(super::audit_min_measurements("other_measurement"), Some(5));

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_min_measurements("any_measurement"), None);
        });
    }

    #[test]
    fn test_audit_aggregate_by() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
aggregate_by = "median"

[measurement."build_time"]
aggregate_by = "max"

[measurement."memory_usage"]
aggregate_by = "mean"
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::audit_aggregate_by("build_time"),
                Some(git_perf_cli_types::ReductionFunc::Max)
            );
            assert_eq!(
                super::audit_aggregate_by("memory_usage"),
                Some(git_perf_cli_types::ReductionFunc::Mean)
            );
            assert_eq!(
                super::audit_aggregate_by("other_measurement"),
                Some(git_perf_cli_types::ReductionFunc::Median)
            );

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_aggregate_by("any_measurement"), None);
        });
    }

    #[test]
    fn test_audit_sigma() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific settings
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
sigma = 3.0

[measurement."build_time"]
sigma = 5.5

[measurement."memory_usage"]
sigma = 2.0
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(super::audit_sigma("build_time"), Some(5.5));
            assert_eq!(super::audit_sigma("memory_usage"), Some(2.0));
            assert_eq!(super::audit_sigma("other_measurement"), Some(3.0));

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::audit_sigma("any_measurement"), None);
        });
    }

    #[test]
    fn test_measurement_unit() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with measurement-specific units
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement]
unit = "ms"

[measurement."build_time"]
unit = "ms"

[measurement."memory_usage"]
unit = "bytes"

[measurement."throughput"]
unit = "requests/sec"
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::measurement_unit("build_time"),
                Some("ms".to_string())
            );
            assert_eq!(
                super::measurement_unit("memory_usage"),
                Some("bytes".to_string())
            );
            assert_eq!(
                super::measurement_unit("throughput"),
                Some("requests/sec".to_string())
            );

            // Test fallback to parent table default
            assert_eq!(
                super::measurement_unit("other_measurement"),
                Some("ms".to_string())
            );

            // Test no config
            fs::remove_file(&workspace_config_path).unwrap();
            assert_eq!(super::measurement_unit("any_measurement"), None);
        });
    }

    #[test]
    fn test_measurement_unit_precedence() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config testing precedence
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let precedence_config = r#"
[measurement]
unit = "ms"

[measurement."build_time"]
unit = "seconds"
"#;
            fs::write(&workspace_config_path, precedence_config).unwrap();

            // Measurement-specific should override parent default
            assert_eq!(
                super::measurement_unit("build_time"),
                Some("seconds".to_string())
            );

            // Other measurements should use parent default
            assert_eq!(
                super::measurement_unit("other_measurement"),
                Some("ms".to_string())
            );
        });
    }

    #[test]
    fn test_read_environment_config_single_var() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\ncommit = \"TEST_GITPERF_SHA\"\n",
            )
            .unwrap();
            let cfg = read_environment_config();
            assert_eq!(
                cfg.get("commit"),
                Some(&vec!["TEST_GITPERF_SHA".to_string()])
            );
        });
    }

    #[test]
    fn test_read_environment_config_multi_var() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nrunner_id = [\"GITPERF_R1\", \"GITPERF_R2\"]\n",
            )
            .unwrap();
            let cfg = read_environment_config();
            assert_eq!(
                cfg.get("runner_id"),
                Some(&vec!["GITPERF_R1".to_string(), "GITPERF_R2".to_string()])
            );
        });
    }

    #[test]
    fn test_read_defaults_config() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(&config_path, "[defaults]\nenvironment = \"local\"\n").unwrap();
            let cfg = read_defaults_config();
            assert_eq!(cfg.get("environment"), Some(&"local".to_string()));
        });
    }

    #[test]
    fn test_read_environment_config_missing_section() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(&config_path, "[measurement]\n").unwrap();
            assert!(read_environment_config().is_empty());
        });
    }

    #[test]
    fn test_read_defaults_config_missing_section() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(&config_path, "[measurement]\n").unwrap();
            assert!(read_defaults_config().is_empty());
        });
    }

    #[test]
    fn test_resolve_key_values_cli_wins_over_env() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nfoo = \"GITPERF_TEST_CLI_WINS\"\n",
            )
            .unwrap();
            env::set_var("GITPERF_TEST_CLI_WINS", "from_env");
            let result = resolve_key_values(&[("foo".to_string(), "from_cli".to_string())], false);
            env::remove_var("GITPERF_TEST_CLI_WINS");
            assert!(result.contains(&("foo".to_string(), "from_cli".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_env_wins_over_defaults() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nfoo = \"GITPERF_TEST_ENV_WINS\"\n[defaults]\nfoo = \"from_defaults\"\n",
            )
            .unwrap();
            env::set_var("GITPERF_TEST_ENV_WINS", "from_env");
            let result = resolve_key_values(&[], false);
            env::remove_var("GITPERF_TEST_ENV_WINS");
            assert!(result.contains(&("foo".to_string(), "from_env".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_defaults_when_env_unset() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nfoo = \"GITPERF_TEST_DEFINITELY_NOT_SET_XYZ\"\n[defaults]\nfoo = \"fallback\"\n",
            )
            .unwrap();
            env::remove_var("GITPERF_TEST_DEFINITELY_NOT_SET_XYZ");
            let result = resolve_key_values(&[], false);
            assert!(result.contains(&("foo".to_string(), "fallback".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_multi_source_first_wins() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nrunner_id = [\"GITPERF_MULTI_R1\", \"GITPERF_MULTI_R2\"]\n",
            )
            .unwrap();
            env::set_var("GITPERF_MULTI_R1", "runner1");
            env::set_var("GITPERF_MULTI_R2", "runner2");
            let result = resolve_key_values(&[], false);
            env::remove_var("GITPERF_MULTI_R1");
            env::remove_var("GITPERF_MULTI_R2");
            assert!(result.contains(&("runner_id".to_string(), "runner1".to_string())));
            assert!(!result.contains(&("runner_id".to_string(), "runner2".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_multi_source_fallback() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nrunner_id = [\"GITPERF_FALLBACK_R1\", \"GITPERF_FALLBACK_R2\"]\n",
            )
            .unwrap();
            env::remove_var("GITPERF_FALLBACK_R1");
            env::set_var("GITPERF_FALLBACK_R2", "runner2");
            let result = resolve_key_values(&[], false);
            env::remove_var("GITPERF_FALLBACK_R2");
            assert!(result.contains(&("runner_id".to_string(), "runner2".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_skip_env_uses_defaults() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nfoo = \"GITPERF_TEST_SKIP_ENV\"\n[defaults]\nfoo = \"from_defaults\"\n",
            )
            .unwrap();
            env::set_var("GITPERF_TEST_SKIP_ENV", "from_env");
            let result = resolve_key_values(&[], true);
            env::remove_var("GITPERF_TEST_SKIP_ENV");
            assert!(result.contains(&("foo".to_string(), "from_defaults".to_string())));
            assert!(!result.contains(&("foo".to_string(), "from_env".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_no_config_empty() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let result = resolve_key_values(&[], false);
            assert!(result.is_empty());
        });
    }

    #[test]
    fn test_resolve_key_values_allows_normal_var() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\ncommit = \"GITPERF_TEST_SHA_NORMAL\"\n",
            )
            .unwrap();
            env::set_var("GITPERF_TEST_SHA_NORMAL", "abc123");
            let result = resolve_key_values(&[], false);
            env::remove_var("GITPERF_TEST_SHA_NORMAL");
            assert!(result.contains(&("commit".to_string(), "abc123".to_string())));
        });
    }

    #[test]
    fn test_resolve_key_values_empty_env_var_not_used() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);
            let config_path = temp_dir.join(".gitperfconfig");
            fs::write(
                &config_path,
                "[environment]\nfoo = \"GITPERF_TEST_EMPTY_VAR\"\n[defaults]\nfoo = \"fallback\"\n",
            )
            .unwrap();
            env::set_var("GITPERF_TEST_EMPTY_VAR", "");
            let result = resolve_key_values(&[], false);
            env::remove_var("GITPERF_TEST_EMPTY_VAR");
            assert!(result.contains(&("foo".to_string(), "fallback".to_string())));
        });
    }

    #[test]
    fn test_measurement_unit_no_parent_default() {
        with_isolated_home(|temp_dir| {
            // Create git repository
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            // Create workspace config with only measurement-specific units (no parent default)
            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement."build_time"]
unit = "ms"

[measurement."memory_usage"]
unit = "bytes"
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            // Test measurement-specific settings
            assert_eq!(
                super::measurement_unit("build_time"),
                Some("ms".to_string())
            );
            assert_eq!(
                super::measurement_unit("memory_usage"),
                Some("bytes".to_string())
            );

            // Test measurement without unit (no parent default either)
            assert_eq!(super::measurement_unit("other_measurement"), None);
        });
    }

    #[test]
    fn test_measurement_unit_special_chars_in_name() {
        with_isolated_home(|temp_dir| {
            env::set_current_dir(temp_dir).unwrap();
            init_repo(temp_dir);

            let workspace_config_path = temp_dir.join(".gitperfconfig");
            let local_config = r#"
[measurement."with_colon::name"]
unit = "ns"

[measurement."with/slash"]
unit = "ms"

[measurement."bench::add_measurements/add_measurement/1::median"]
unit = "ns"
min_measurements = 3
"#;
            fs::write(&workspace_config_path, local_config).unwrap();

            assert_eq!(
                super::measurement_unit("with_colon::name"),
                Some("ns".to_string()),
                "double-colon in name"
            );
            assert_eq!(
                super::measurement_unit("with/slash"),
                Some("ms".to_string()),
                "slash in name"
            );
            assert_eq!(
                super::measurement_unit("bench::add_measurements/add_measurement/1::median"),
                Some("ns".to_string()),
                "full benchmark name"
            );
        });
    }
}