config_rw 2.2.1

配置文件读取与写入
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
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
#[macro_use]
extern crate log;

use fast_able::{SyncHashMap, SyncVec};
use fast_able::unsafe_cell_type::U;
use notify::{Event, RecursiveMode, Watcher};
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use std::env;
use std::path::Path;
use std::sync::{
    Arc,
    atomic::{AtomicBool, AtomicU64, Ordering},
};
use toml_edit::{DocumentMut, Item, Table};

type StdBoxError = Box<dyn std::error::Error + Send + Sync>;
type R<V = ()> = Result<V, StdBoxError>;

/// 配置管理库,支持多个配置文件实例
///
/// # 使用示例
///
/// ```rust
/// use std::sync::LazyLock;
/// use config_rw::ConfigState;
///
/// // 定义多个配置实例
/// static C1: LazyLock<ConfigState> = LazyLock::new(|| {
///     ConfigState::init_config("config1.toml")
/// });
///
/// static C2: LazyLock<ConfigState> = LazyLock::new(|| {
///     ConfigState::init_config("config2.toml")
/// });
///
/// static C3: LazyLock<ConfigState> = LazyLock::new(|| {
///     ConfigState::init_config("config3.toml")
/// });
///
/// // 使用配置
/// fn main() {
///     // 读取配置
///     let host = C1.get_string("database.host").unwrap_or_default();
///     let port = C1.get_i64("database.port").unwrap_or(5432);
///     let enabled = C1.get_bool("database.enabled").unwrap_or(false);
///     
///     // 设置配置
///     C1.set_string("database.host", "localhost".to_string()).unwrap();
///     C1.set_i64("database.port", 3306).unwrap();
///     C1.set_bool("database.enabled", true).unwrap();
///     
///     // 使用不同的配置文件
///     let api_key = C2.get_string("api.key").unwrap_or_default();
///     let log_level = C3.get_string("logging.level").unwrap_or_default();
/// }
/// ```

pub struct ConfigState {
    inner: Arc<ConfigArc>,
}

impl ConfigState {
    /// 初始化配置管理器
    pub fn init_config<P: AsRef<Path>>(config_path: P) -> ConfigState {
        let mut state = ConfigArc::new();

        // 解析命令行参数
        let args: Vec<String> = env::args().collect();
        state.parse_args(args);

        // 设置配置文件路径
        state.set_file_path(config_path);

        let state = Arc::new(state);

        // 初始化文件监听,复制一份 Arc
        if let Err(e) = state.clone().init_file_watcher() {
            warn!("Failed to initialize file watcher: {}", e);
        }

        ConfigState { inner: state }
    }

    /// 获取内部 Arc 引用
    pub fn get_arc(&self) -> Arc<ConfigArc> {
        self.inner.clone()
    }

    /// 设置配置值(带回调支持)
    pub fn set_value(&self, path: &str, value: Value) -> R {
        let changed = ConfigManager::set_config_value(path, value, &self.inner)?;
        if changed {
            // 触发全局 change_callbacks
            for callback in self.inner.change_callbacks.iter() {
                callback(self.inner.clone());
            }
        }
        Ok(())
    }

    /// 设置字符串配置
    pub fn set_string(&self, path: &str, value: String) -> R {
        self.set_value(path, Value::String(value))
    }

    /// 设置整数配置
    pub fn set_i64(&self, path: &str, value: i64) -> R {
        self.set_value(path, Value::Number(serde_json::Number::from(value)))
    }

    /// 设置浮点数配置
    pub fn set_f64(&self, path: &str, value: f64) -> R {
        if let Some(n) = serde_json::Number::from_f64(value) {
            self.set_value(path, Value::Number(n))
        } else {
            Err("Invalid float value".into())
        }
    }

    /// 设置布尔值配置
    pub fn set_bool(&self, path: &str, value: bool) -> R {
        self.set_value(path, Value::Bool(value))
    }
}

impl std::ops::Deref for ConfigState {
    type Target = ConfigArc;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// 值回调的封装类型
type ValueCallback = Box<dyn Fn(Value) + Send + Sync + 'static>;

/// 配置状态结构体,支持多个配置文件实例
pub struct ConfigArc {
    /// 配置文件路径
    file_path: Option<String>,
    /// 命令行参数映射
    args_map: HashMap<String, String>,
    /// 双缓冲配置文档
    doc: [spin::RwLock<DocumentMut>; 2],
    /// 配置变化回调函数(任何配置值发生变化时触发)
    change_callbacks: SyncVec<Box<dyn Fn(Arc<ConfigArc>) + Send + Sync + 'static>>,
    /// 特定键的值变化回调函数(键 -> 回调列表)
    value_callbacks: SyncHashMap<String, Vec<ValueCallback>>,
    /// 当前使用的文档索引
    index: U<usize>,
    /// 文件监听器
    watcher: spin::RwLock<Option<notify::RecommendedWatcher>>,
    /// 标记是否正在程序内部修改文件(避免文件监听器处理自己的变化)
    internal_modification: AtomicBool,
}

impl ConfigArc {
    /// 创建新的配置状态
    fn new() -> Self {
        Self {
            file_path: None,
            args_map: HashMap::new(),
            doc: [
                spin::RwLock::new(DocumentMut::new()),
                spin::RwLock::new(DocumentMut::new()),
            ],
            change_callbacks: SyncVec::new(),
            value_callbacks: SyncHashMap::new(),
            index: 0.into(),
            watcher: spin::RwLock::new(None),
            internal_modification: AtomicBool::new(false),
        }
    }

    /// 解析命令行参数
    /// 支持格式:./xx.exe arg1 arg2=2 arg3="3"
    fn parse_args(&mut self, args: Vec<String>) {
        self.args_map.clear();

        // 跳过程序名(第一个参数)
        for (index, arg) in args.iter().skip(1).enumerate() {
            if arg.contains('=') {
                // 处理 key=value 格式
                let parts: Vec<&str> = arg.splitn(2, '=').collect();
                if parts.len() == 2 {
                    let key = parts[0].trim();
                    let value = parts[1].trim();
                    // 去掉引号
                    let cleaned_value = if (value.starts_with('"') && value.ends_with('"'))
                        || (value.starts_with('\'') && value.ends_with('\''))
                    {
                        &value[1..value.len() - 1]
                    } else {
                        value
                    };
                    self.args_map
                        .insert(key.to_string(), cleaned_value.to_string());
                }
            } else {
                // 处理位置参数,使用索引作为键
                let key = format!("arg{}", index);
                self.args_map.insert(key, arg.clone());
            }
        }

        info!("Parsed {} command line arguments", self.args_map.len());
    }

    /// 设置配置文件路径
    fn set_file_path<P: AsRef<Path>>(&mut self, path: P) {
        // 规范化路径:尝试转换为绝对路径
        let path_ref = path.as_ref();
        let path_str = if path_ref.is_absolute() {
            path_ref.to_string_lossy().to_string()
        } else {
            // 尝试获取绝对路径
            match std::env::current_dir() {
                Ok(cwd) => cwd.join(path_ref).to_string_lossy().to_string(),
                Err(_) => path_ref.to_string_lossy().to_string(),
            }
        };
        self.file_path = Some(path_str);
        info!(
            "Config file path set to: {}",
            self.file_path.as_ref().unwrap()
        );
    }

    /// 获取配置文件路径
    fn get_file_path(&self) -> Option<&String> {
        self.file_path.as_ref()
    }

    /// 获取命令行参数
    fn get_arg(&self, key: &str) -> Option<&String> {
        self.args_map.get(key)
    }

    /// 检查是否有命令行参数
    fn has_arg(&self, key: &str) -> bool {
        self.args_map.contains_key(key)
    }

    /// 初始化文件监听器
    fn init_file_watcher(self: Arc<Self>) -> R {
        let file_path = self.file_path.as_ref().ok_or("No file path specified")?;
        let path = Path::new(file_path);

        // 如果文件不存在,先创建目录和空文件
        if !path.exists() {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(path, "")?;
            warn!("File not found; Created empty config file: {}", file_path);
        }

        // 初始加载配置文件到当前索引
        self.load_config_file()?;

        // 规范化目标路径用于比较
        let canonical_path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        let file_path_clone = file_path.clone();

        // 防抖:同一时间窗口内的多次修改事件只处理最后一次。
        // 这里用递增的 generation 标识“最新事件”,最后一次事件 2 秒后才会真正触发重载。
        let debounce_generation = Arc::new(AtomicU64::new(0));

        // 使用 Weak 引用避免循环引用,否则 Arc<ConfigArc> -> watcher -> 闭包 -> Arc<ConfigArc> 会导致内存泄漏
        let state_weak = Arc::downgrade(&self);
        let debounce_generation_for_watcher = debounce_generation.clone();
        let watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
            // 尝试升级 Weak 引用,如果 ConfigArc 已被释放则直接返回
            let state = match state_weak.upgrade() {
                Some(s) => s,
                None => {
                    // ConfigArc 已被释放,忽略此事件
                    return;
                }
            };

            let event = match res {
                Ok(v) => v,
                Err(e) => {
                    error!("File watch error: {e:?}");
                    return;
                }
            };

            debug!("File change event: {:?}", event);

            // 检查是否是我们监听的文件(使用规范化路径比较)
            let is_target_file = event.paths.iter().any(|p| {
                // 尝试规范化事件路径进行比较
                let event_canonical = std::fs::canonicalize(p).unwrap_or_else(|_| p.clone());
                event_canonical == canonical_path || p.file_name() == canonical_path.file_name()
            });

            if !is_target_file {
                return;
            }

            // 检查是否是写入/修改事件
            let is_modify_event = matches!(
                event.kind,
                notify::EventKind::Modify(_)
                    | notify::EventKind::Create(notify::event::CreateKind::File)
            );

            if !is_modify_event {
                return;
            }

            // 检查是否是程序内部修改,如果是则忽略
            if state.internal_modification.load(Ordering::Acquire) {
                debug!("Ignoring file change event - internal modification");
                return;
            }

            // 2 秒防抖:记录最新事件 generation,并在后台线程等待窗口结束后只处理最后一次。
            let my_generation = debounce_generation_for_watcher.fetch_add(1, Ordering::AcqRel) + 1;
            let state_for_thread = state.clone();
            let file_path_for_thread = file_path_clone.clone();
            let debounce_generation_for_thread = debounce_generation_for_watcher.clone();

            std::thread::spawn(move || {
                std::thread::sleep(std::time::Duration::from_secs(2));

                // 不是最后一次事件 -> 取消
                if debounce_generation_for_thread.load(Ordering::Acquire) != my_generation {
                    return;
                }

                // 再次确认不是程序内部写入(窗口内可能发生 set_* 写入)
                if state_for_thread
                    .internal_modification
                    .load(Ordering::Acquire)
                {
                    debug!("Debounced reload cancelled - internal modification");
                    return;
                }

                // 加载配置到另一个缓冲区
                let old_index = state_for_thread.index.load();
                let new_index = 1 - old_index;

                match ConfigManager::load_document(&file_path_for_thread) {
                    Ok(new_doc) => {
                        // 获取旧文档用于比较
                        let old_doc = {
                            let doc_lock = state_for_thread.doc[old_index].read();
                            doc_lock.clone()
                        };

                        {
                            let mut doc_lock = state_for_thread.doc[new_index].write();
                            *doc_lock = new_doc.clone();
                        }

                        state_for_thread.index.store(new_index);

                        // 检测变化并触发回调(包括 change_callbacks 和 value_callbacks)
                        state_for_thread.detect_and_trigger_changes(&old_doc, &new_doc);

                        info!(
                            "Config file reloaded from external change (debounced), switched to buffer {}",
                            new_index
                        );
                    }
                    Err(e) => {
                        error!("Failed to reload config file (debounced): {}", e);
                    }
                }
            });
        })?;

        // 监听配置文件
        {
            let mut watcher_guard = self.watcher.write();
            if let Some(ref mut w) = watcher_guard.take() {
                // 如果已经有监听器,先停止它
                let _ = w.unwatch(path);
            }

            // 监听配置文件
            let mut new_watcher = watcher;
            new_watcher.watch(
                path.parent().unwrap_or_else(|| path),
                RecursiveMode::NonRecursive,
            )?;
            *watcher_guard = Some(new_watcher);
        }

        info!("File watcher initialized for: {}", file_path);
        Ok(())
    }

    /// 加载配置文件到当前缓冲区
    fn load_config_file(&self) -> R {
        let file_path = self.file_path.as_ref().ok_or("No file path specified")?;
        let current_index = self.index.load();

        match ConfigManager::load_document(file_path) {
            Ok(document) => {
                let mut doc_lock = self.doc[current_index].write();
                *doc_lock = document;
                info!("Config file loaded into buffer {}", current_index);
                Ok(())
            }
            Err(e) => {
                warn!("Failed to load config file '{}': {}", file_path, e);
                Err(e)
            }
        }
    }

    /// 获取当前使用的配置文档
    fn get_current_doc(&self) -> spin::RwLockReadGuard<'_, DocumentMut> {
        let current_index = self.index.load();
        self.doc[current_index].read()
    }

    /// 获取当前使用的配置文档(可写)
    fn get_current_doc_mut(&self) -> spin::RwLockWriteGuard<'_, DocumentMut> {
        let current_index = self.index.load();
        self.doc[current_index].write()
    }

    /// 添加配置变化回调函数(任何配置值发生变化时自动触发)
    ///
    /// 当配置文件被内部或外部修改,且至少有一个值发生实际变化时,回调会被调用。
    ///
    /// # Example
    /// ```ignore
    /// CONFIG.add_change_callback(|config| {
    ///     let new_val = config.get_string("key").unwrap_or_default();
    ///     println!("Config changed: {}", new_val);
    /// });
    /// ```
    pub fn add_change_callback<F>(&self, callback: F)
    where
        F: Fn(Arc<ConfigArc>) + Send + Sync + 'static,
    {
        self.change_callbacks.push(Box::new(callback));
        info!("Config change callback added");
    }

    /// 添加特定键的值变化回调函数(泛型版本)
    ///
    /// 当指定键的值发生变化时(包括内部和外部修改),回调会被调用。
    /// 第一次添加回调时会立即以当前值触发一次回调。
    /// 如果值被删除、为空或无法反序列化为目标类型,回调将收到 `None`。
    ///
    /// # 泛型支持
    /// 回调接收 `Option<T>` 类型,T 必须实现 `DeserializeOwned` trait。
    /// 支持的类型包括:
    /// - `String` - 字符串
    /// - `i64`, `i32`, `u64`, `u32` 等 - 整数
    /// - `f64`, `f32` - 浮点数
    /// - `bool` - 布尔值
    /// - 任何实现了 `serde::Deserialize` 的自定义类型
    ///
    /// # Example
    /// ```ignore
    /// // 监听字符串值
    /// CONFIG.add_callback_value("database.host", |v: Option<String>| {
    ///     if let Some(host) = v {
    ///         println!("Host changed to: {}", host);
    ///     } else {
    ///         println!("Host was deleted or is null");
    ///     }
    /// });
    ///
    /// // 监听整数值
    /// CONFIG.add_callback_value("database.port", |v: Option<i64>| {
    ///     if let Some(port) = v {
    ///         println!("Port changed to: {}", port);
    ///     }
    /// });
    ///
    /// // 监听布尔值
    /// CONFIG.add_callback_value("database.enabled", |v: Option<bool>| {
    ///     if let Some(enabled) = v {
    ///         println!("Enabled changed to: {}", enabled);
    ///     }
    /// });
    ///
    /// // 监听自定义结构体
    /// #[derive(Deserialize)]
    /// struct DatabaseConfig {
    ///     host: String,
    ///     port: i64,
    /// }
    /// CONFIG.add_callback_value("database", |v: Option<DatabaseConfig>| {
    ///     if let Some(config) = v {
    ///         println!("Database config: {}:{}", config.host, config.port);
    ///     }
    /// });
    /// ```
    pub fn add_callback_value<T, F>(&self, key: &str, callback: F)
    where
        T: DeserializeOwned + 'static,
        F: Fn(Option<T>) + Send + Sync + 'static,
    {
        // 获取当前值并立即触发一次回调
        let current_value = self.get_value(key);
        let typed_value: Option<T> = serde_json::from_value(current_value).ok();
        callback(typed_value);

        // 包装回调,将 Value 转换为 Option<T>
        let wrapped_callback = move |value: Value| {
            let typed_value: Option<T> = serde_json::from_value(value).ok();
            callback(typed_value);
        };

        // 添加到回调列表
        self.value_callbacks
            .get_or_insert_with(key.to_string(), Vec::new)
            .push(Box::new(wrapped_callback));
        info!("Value callback added for key: {}", key);
    }

    /// 触发值变化回调(带旧值比较)
    /// old_values: 更新前所有监听路径的旧值快照
    fn trigger_value_callbacks_with_diff(&self, old_values: &HashMap<String, Value>) {
        for registered_key in self.value_callbacks.keys() {
            let new_value = self.get_value(&registered_key);
            let old_value = old_values.get(&*registered_key).cloned().unwrap_or(Value::Null);

            // 只有值真正变化时才触发回调
            if new_value != old_value {
                if let Some(cbs) = self.value_callbacks.get(&*registered_key) {
                    for cb in cbs.iter() {
                        cb(new_value.clone());
                    }
                }
            }
        }
    }

    /// 获取所有监听路径的当前值快照
    fn snapshot_callback_values(&self) -> HashMap<String, Value> {
        let mut snapshot = HashMap::new();
        for key in self.value_callbacks.keys() {
            snapshot.insert(key.clone(), self.get_value(&key));
        }
        snapshot
    }

    /// 比较两个文档,检测值变化并触发回调(内部使用)
    fn detect_and_trigger_changes(self: &Arc<Self>, old_doc: &DocumentMut, new_doc: &DocumentMut) {
        let callbacks = &self.value_callbacks;
        let mut any_changed = false;

        // 检查所有已注册的键
        for key in callbacks.keys() {
            let old_value = ConfigManager::get_config_value(old_doc, key).unwrap_or(Value::Null);
            let new_value = ConfigManager::get_config_value(new_doc, key).unwrap_or(Value::Null);

            if old_value != new_value {
                any_changed = true;
                // 触发该键的值回调
                if let Some(cbs) = callbacks.get(key) {
                    for cb in cbs.iter() {
                        cb(new_value.clone());
                    }
                }
            }
        }

        // 检查整个文档是否有任何变化(用于 change_callbacks)
        if !any_changed {
            // 如果没有注册的键发生变化,检查整个文档
            any_changed = Self::documents_differ(old_doc, new_doc);
        }

        // 如果有任何变化,触发 change_callbacks
        if any_changed {
            for callback in self.change_callbacks.iter() {
                callback(self.clone());
            }
        }
    }

    /// 比较两个文档是否有差异
    fn documents_differ(old_doc: &DocumentMut, new_doc: &DocumentMut) -> bool {
        old_doc.to_string() != new_doc.to_string()
    }

    /// 获取当前使用的缓冲区索引
    pub fn get_current_buffer_index(&self) -> usize {
        self.index.load()
    }

    /// 获取配置值 (返回 JSON Value)
    pub fn get_value(&self, path: &str) -> Value {
        // 1. 首先检查命令行参数
        if let Some(value) = self.get_arg(path) {
            // 尝试解析为 JSON,如果失败则返回字符串
            if let Ok(json_value) = serde_json::from_str::<Value>(value) {
                return json_value;
            } else {
                return Value::String(value.clone());
            }
        }

        // 2. 然后检查配置文件(使用双缓冲)
        if self.get_file_path().is_some() {
            let document = self.get_current_doc();
            if let Some(config_value) = ConfigManager::get_config_value(&document, path) {
                return config_value; // 直接返回 JSON 值,不转换为字符串
            }
        }

        // 3. 最后检查环境变量
        let env_key = path.to_uppercase().replace('.', "_");
        if let Ok(env_value) = env::var(&env_key) {
            // 尝试解析为 JSON,如果失败则返回字符串
            if let Ok(json_value) = serde_json::from_str::<Value>(&env_value) {
                return json_value;
            } else {
                return Value::String(env_value);
            }
        }

        Value::Null
    }

    /// 设置配置值(内部使用,不触发全局 change_callbacks)
    /// 注意:如果需要触发全局 change_callbacks,请使用 ConfigState 的方法
    pub fn set_value(&self, path: &str, value: Value) -> R {
        ConfigManager::set_config_value(path, value, self)?;
        Ok(())
    }

    /// 获取字符串配置
    pub fn get_string(&self, path: &str) -> Option<String> {
        ConfigManager::get_value_with_priority(path, self)
    }

    /// 获取整数配置
    pub fn get_i64(&self, path: &str) -> Option<i64> {
        if let Some(value) = ConfigManager::get_value_with_priority(path, self) {
            ConfigManager::string_to_i64(&value)
        } else {
            None
        }
    }

    /// 获取浮点数配置
    pub fn get_f64(&self, path: &str) -> Option<f64> {
        if let Some(value) = ConfigManager::get_value_with_priority(path, self) {
            ConfigManager::string_to_f64(&value)
        } else {
            None
        }
    }

    /// 获取布尔值配置
    pub fn get_bool(&self, path: &str) -> Option<bool> {
        if let Some(value) = ConfigManager::get_value_with_priority(path, self) {
            ConfigManager::string_to_bool(&value)
        } else {
            None
        }
    }

    /// 设置字符串配置
    pub fn set_string(&self, path: &str, value: String) -> R {
        self.set_value(path, Value::String(value))
    }

    /// 设置整数配置
    pub fn set_i64(&self, path: &str, value: i64) -> R {
        self.set_value(path, Value::Number(serde_json::Number::from(value)))
    }

    /// 设置浮点数配置
    pub fn set_f64(&self, path: &str, value: f64) -> R {
        if let Some(n) = serde_json::Number::from_f64(value) {
            self.set_value(path, Value::Number(n))
        } else {
            Err("Invalid float value".into())
        }
    }

    /// 设置布尔值配置
    pub fn set_bool(&self, path: &str, value: bool) -> R {
        self.set_value(path, Value::Bool(value))
    }
}

impl ConfigArc {
    pub fn unload_watch(&self) {
        #[cfg(debug_assertions)]
        println!("File watcher stopped file_path: {:?}", self.file_path);

        // 停止文件监听器
        let mut watcher_guard = self.watcher.write();
        if let Some(ref mut w) = watcher_guard.take() {
            if let Some(file_path) = &self.file_path {
                let path = Path::new(file_path);
                let _ = w.unwatch(path.parent().unwrap_or_else(|| path));

                #[cfg(debug_assertions)]
                println!("File watcher stopped for: {}", file_path);
            }
        }
        info!("ConfigArc dropped, file watcher stopped");
    }
}

impl Drop for ConfigArc {
    fn drop(&mut self) {
        self.unload_watch();
    }
}

/// 配置管理器工具类,提供无状态的配置文件操作
struct ConfigManager;

impl ConfigManager {
    /// 从文件加载配置文档
    fn load_document(file_path: &str) -> R<DocumentMut> {
        let path = Path::new(file_path);

        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let document = content
                .parse::<DocumentMut>()
                .map_err(|e| format!("Failed to parse TOML file '{}': {}", file_path, e))?;
            Ok(document)
        } else {
            // 如果文件不存在,返回空文档
            Ok(DocumentMut::new())
        }
    }

    /// 保存配置文档到文件
    fn save_document(file_path: &str, document: &DocumentMut) -> R {
        // 确保目录存在
        if let Some(parent) = Path::new(file_path).parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(file_path, document.to_string())?;
        info!("Config saved to file: {}", file_path);
        Ok(())
    }

    /// 按优先级获取配置值:命令行参数 > 配置文件 > 环境变量
    fn get_value_with_priority(path: &str, state: &ConfigArc) -> Option<String> {
        // 1. 首先检查命令行参数
        if let Some(value) = state.get_arg(path) {
            return Some(value.clone());
        }

        // 2. 然后检查配置文件(使用双缓冲)
        if state.get_file_path().is_some() {
            let document = state.get_current_doc();
            if let Some(config_value) = Self::get_config_value(&document, path) {
                if let Some(string_value) = Self::json_value_to_string(&config_value) {
                    return Some(string_value);
                }
            }
        }

        // 3. 最后检查环境变量
        if let Ok(env_value) = env::var(path.to_uppercase().replace('.', "_")) {
            return Some(env_value);
        }

        None
    }

    /// 从配置文件获取值
    fn get_config_value(document: &DocumentMut, path: &str) -> Option<Value> {
        let keys: Vec<&str> = path.split('.').collect();
        let mut current = document.as_table();

        for (i, key) in keys.iter().enumerate() {
            if i == keys.len() - 1 {
                // 最后一个键,获取值
                if let Some(item) = current.get(key) {
                    return Self::item_to_json_value(item);
                }
            } else {
                // 中间键,继续导航
                if let Some(Item::Table(table)) = current.get(key) {
                    current = table;
                } else {
                    return None;
                }
            }
        }
        None
    }

    /// 将 JSON 值转换为字符串
    fn json_value_to_string(value: &Value) -> Option<String> {
        match value {
            Value::String(s) => Some(s.clone()),
            Value::Number(n) => Some(n.to_string()),
            Value::Bool(b) => Some(b.to_string()),
            _ => None,
        }
    }

    /// 字符串转换为 i64
    fn string_to_i64(s: &str) -> Option<i64> {
        s.parse::<i64>().ok()
    }

    /// 字符串转换为 f64
    fn string_to_f64(s: &str) -> Option<f64> {
        s.parse::<f64>().ok()
    }

    /// 字符串转换为 bool
    fn string_to_bool(s: &str) -> Option<bool> {
        match s.to_lowercase().as_str() {
            "true" | "1" | "yes" | "on" => Some(true),
            "false" | "0" | "no" | "off" => Some(false),
            _ => None,
        }
    }

    /// 设置配置值(原子操作:读取->修改->写入)
    /// 返回 Ok(true) 表示值发生了变化,Ok(false) 表示值没有变化
    fn set_config_value(path: &str, value: Value, state: &ConfigArc) -> R<bool> {
        // 检查配置来源,如果来自命令行或环境变量则报错

        // 1. 检查是否来自命令行参数
        if state.has_arg(path) {
            return Err("当前为命令行参数, 不能保存".into());
        }

        // 2. 检查是否来自环境变量
        let env_key = path.to_uppercase().replace('.', "_");
        if env::var(&env_key).is_ok() {
            // 还需要确认配置文件中没有这个值
            if state.get_file_path().is_some() {
                let document = state.get_current_doc();
                if Self::get_config_value(&document, path).is_none() {
                    return Err("当前为环境变量参数, 不能保存".into());
                }
            }
        }

        // 获取文件路径
        let file_path = state.get_file_path().ok_or("No file path specified")?;

        // 获取所有监听路径的旧值快照
        let old_values = state.snapshot_callback_values();

        // 原子操作:读取->修改->写入
        let mut document = state.get_current_doc_mut();

        let keys: Vec<&str> = path.split('.').collect();

        // 先转换 JSON 值到 TOML
        let toml_value = Self::json_value_to_toml(&value)?;

        let mut current = document.as_table_mut();

        // 导航到目标位置,创建中间表格
        for (i, key) in keys.iter().enumerate() {
            if i == keys.len() - 1 {
                // 最后一个键,设置值
                current.insert(key, toml_value);
                info!("Config value set: {} = {:?}", path, value);

                // 标记为内部修改
                state.internal_modification.store(true, Ordering::Release);
                debug!("Set internal_modification flag to true before saving");

                // 立即保存到文件
                let save_result = Self::save_document(file_path, &document);

                // 等待一小段时间确保文件监听器有机会处理(但应该被忽略)
                std::thread::sleep(std::time::Duration::from_millis(10));

                // 清除内部修改标志
                state.internal_modification.store(false, Ordering::Release);
                debug!("Set internal_modification flag to false after saving");

                save_result?;

                // 释放文档锁
                drop(document);

                // 触发值变化回调(自动比较新旧值)
                state.trigger_value_callbacks_with_diff(&old_values);

                return Ok(true);
            } else {
                // 中间键,创建或获取表格
                if !current.contains_key(key) {
                    current.insert(key, Item::Table(Table::new()));
                }

                if let Some(Item::Table(table)) = current.get_mut(key) {
                    current = table;
                } else {
                    return Err(format!("Key '{}' in path '{}' is not a table", key, path).into());
                }
            }
        }

        Err("Failed to set value".into())
    }

    /// 转换 toml_edit::Item 到 serde_json::Value
    fn item_to_json_value(item: &Item) -> Option<Value> {
        match item {
            Item::Value(value) => match value {
                toml_edit::Value::String(s) => Some(Value::String(s.value().to_string())),
                toml_edit::Value::Integer(i) => {
                    Some(Value::Number(serde_json::Number::from(*i.value())))
                }
                toml_edit::Value::Float(f) => {
                    if let Some(n) = serde_json::Number::from_f64(*f.value()) {
                        Some(Value::Number(n))
                    } else {
                        None
                    }
                }
                toml_edit::Value::Boolean(b) => Some(Value::Bool(*b.value())),
                toml_edit::Value::Array(arr) => {
                    let mut json_array = Vec::new();
                    for item in arr.iter() {
                        if let Some(json_val) = Self::item_to_json_value(&Item::Value(item.clone()))
                        {
                            json_array.push(json_val);
                        }
                    }
                    Some(Value::Array(json_array))
                }
                toml_edit::Value::InlineTable(table) => {
                    let mut json_obj = serde_json::Map::new();
                    for (key, value) in table.iter() {
                        if let Some(json_val) =
                            Self::item_to_json_value(&Item::Value(value.clone()))
                        {
                            json_obj.insert(key.to_string(), json_val);
                        }
                    }
                    Some(Value::Object(json_obj))
                }
                _ => None,
            },
            Item::Table(table) => {
                let mut json_obj = serde_json::Map::new();
                for (key, item) in table.iter() {
                    if let Some(json_val) = Self::item_to_json_value(item) {
                        json_obj.insert(key.to_string(), json_val);
                    }
                }
                Some(Value::Object(json_obj))
            }
            _ => None,
        }
    }

    /// 转换 serde_json::Value 到 toml_edit::Item
    fn json_value_to_toml(value: &Value) -> R<Item> {
        match value {
            Value::String(s) => {
                let string_value = toml_edit::Value::String(toml_edit::Formatted::new(s.clone()));
                Ok(Item::Value(string_value))
            }
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    let int_value = toml_edit::Value::Integer(toml_edit::Formatted::new(i));
                    Ok(Item::Value(int_value))
                } else if let Some(f) = n.as_f64() {
                    let float_value = toml_edit::Value::Float(toml_edit::Formatted::new(f));
                    Ok(Item::Value(float_value))
                } else {
                    Err("Invalid number format".into())
                }
            }
            Value::Bool(b) => {
                let bool_value = toml_edit::Value::Boolean(toml_edit::Formatted::new(*b));
                Ok(Item::Value(bool_value))
            }
            Value::Array(arr) => {
                let mut toml_array = toml_edit::Array::new();
                for item in arr {
                    if let Item::Value(toml_val) = Self::json_value_to_toml(item)? {
                        toml_array.push(toml_val);
                    }
                }
                Ok(Item::Value(toml_edit::Value::Array(toml_array)))
            }
            Value::Object(obj) => {
                let mut toml_table = Table::new();
                for (key, val) in obj {
                    toml_table.insert(key, Self::json_value_to_toml(val)?);
                }
                Ok(Item::Table(toml_table))
            }
            Value::Null => Err("TOML does not support null values".into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_config_basic_operations() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("basic_test_config_unique.toml");

        // 创建测试配置文件
        let config_content = r#"
# 这是一个测试配置文件
[database]
host = "localhost"
port = 5432
enabled = true

[app]
name = "test_app"
version = "1.0.0"

[app.features]
logging = true
metrics = false
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 测试读取配置
        assert_eq!(
            state.get_string("database.host"),
            Some("localhost".to_string())
        );
        assert_eq!(state.get_i64("database.port"), Some(5432));
        assert_eq!(state.get_bool("database.enabled"), Some(true));

        // 测试设置配置
        state
            .set_string("database.host", "127.0.0.1".to_string())
            .unwrap();
        state.set_i64("database.port", 3306).unwrap();

        // 验证设置是否生效
        println!(
            "After setting: host={:?}, port={:?}",
            state.get_string("database.host"),
            state.get_i64("database.port")
        );
        assert_eq!(
            state.get_string("database.host"),
            Some("127.0.0.1".to_string())
        );
        assert_eq!(state.get_i64("database.port"), Some(3306));

        // 验证文件是否更新
        let saved_content = fs::read_to_string(&config_path).unwrap();
        assert!(saved_content.contains("127.0.0.1"));
        assert!(saved_content.contains("3306"));

        // 验证注释是否保留
        assert!(saved_content.contains("# 这是一个测试配置文件"));
    }

    #[test]
    fn test_nested_config() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("nested_config_test_unique.toml");

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 设置嵌套配置
        state.set_string("a.b.c", "deep_value".to_string()).unwrap();
        state.set_i64("x.y.z", 42).unwrap();

        // 验证嵌套配置
        assert_eq!(state.get_string("a.b.c"), Some("deep_value".to_string()));
        assert_eq!(state.get_i64("x.y.z"), Some(42));

        // 验证文件内容
        let saved_content = fs::read_to_string(&config_path).unwrap();
        assert!(saved_content.contains("deep_value"));
        assert!(saved_content.contains("42"));
    }

    #[test]
    fn test_command_line_args() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("args_test_config_unique.toml");

        // 创建测试配置文件
        let config_content = r#"
[database]
host = "localhost"
port = 5432
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态并模拟命令行参数
        let test_args = vec![
            "program_name".to_string(),
            "database.host=127.0.0.1".to_string(),
            "database.port=3306".to_string(),
            "debug=true".to_string(),
        ];

        let mut state = ConfigArc::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);

        // 命令行参数应该覆盖配置文件
        assert_eq!(
            state.get_string("database.host"),
            Some("127.0.0.1".to_string())
        );
        assert_eq!(state.get_i64("database.port"), Some(3306));
        assert_eq!(state.get_bool("debug"), Some(true));
    }

    #[test]
    fn test_type_conversions() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("type_test_config_unique.toml");

        // 创建配置状态并模拟命令行参数
        let test_args = vec![
            "program_name".to_string(),
            "int_val=42".to_string(),
            "float_val=3.14".to_string(),
            "bool_val=true".to_string(),
            "str_val=hello".to_string(),
        ];

        let mut state = ConfigArc::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);

        // 测试类型转换
        assert_eq!(state.get_i64("int_val"), Some(42));
        assert_eq!(state.get_f64("float_val"), Some(3.14));
        assert_eq!(state.get_bool("bool_val"), Some(true));
        assert_eq!(state.get_string("str_val"), Some("hello".to_string()));
    }

    #[test]
    fn test_source_protection() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("source_test_config_unique.toml");

        // 创建测试配置文件
        let config_content = r#"
[database]
host = "localhost"
port = 5432
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态并模拟命令行参数
        let test_args = vec!["program_name".to_string(), "cmd_arg=from_cmd".to_string()];

        // 设置环境变量
        unsafe {
            env::set_var("ENV_VAR", "from_env");
        }

        let mut state = ConfigArc::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);

        // 初始化文件监听器以加载配置文件
        let state = Arc::new(state);
        if let Err(e) = state.clone().init_file_watcher() {
            warn!("Failed to initialize file watcher: {}", e);
        }

        // 验证读取值
        assert_eq!(state.get_string("cmd_arg"), Some("from_cmd".to_string()));
        assert_eq!(state.get_string("ENV_VAR"), Some("from_env".to_string()));
        assert_eq!(
            state.get_string("database.host"),
            Some("localhost".to_string())
        );

        // 尝试设置命令行参数 - 应该报错
        let result = state.set_string("cmd_arg", "modified".to_string());
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "当前为命令行参数, 不能保存"
        );

        // 尝试设置环境变量 - 应该报错
        let result = state.set_string("ENV_VAR", "modified".to_string());
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "当前为环境变量参数, 不能保存"
        );

        // 设置配置文件中的值 - 应该成功
        let result = state.set_string("database.host", "127.0.0.1".to_string());
        assert!(result.is_ok());

        // 验证配置文件值被修改
        assert_eq!(
            state.get_string("database.host"),
            Some("127.0.0.1".to_string())
        );

        // 设置新的配置值 - 应该成功
        let result = state.set_string("new_config", "new_value".to_string());
        assert!(result.is_ok());
        assert_eq!(
            state.get_string("new_config"),
            Some("new_value".to_string())
        );

        // 清理环境变量
        unsafe {
            env::remove_var("ENV_VAR");
        }
    }

    #[test]
    fn test_file_watcher_and_callback() {
        use std::sync::{Arc, Mutex};
        use std::time::Duration;

        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("watch_test_config.toml");

        // 创建初始配置文件
        let initial_content = r#"
[app]
name = "test_app"
version = "1.0.0"
"#;
        fs::write(&config_path, initial_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 设置回调计数器
        let callback_count = Arc::new(Mutex::new(0));
        let callback_count_clone = callback_count.clone();

        // 添加回调函数(新签名:Fn(Arc<ConfigArc>))
        state.add_change_callback(move |_state| {
            let mut count = callback_count_clone.lock().unwrap();
            *count += 1;
            println!("Config changed! Callback count: {}", *count);
        });

        // 验证初始值
        assert_eq!(state.get_string("app.name"), Some("test_app".to_string()));
        assert_eq!(state.get_string("app.version"), Some("1.0.0".to_string()));

        // 修改配置文件(模拟外部程序修改)
        let modified_content = r#"
[app]
name = "modified_app"
version = "2.0.0"
debug = true
"#;
        fs::write(&config_path, modified_content).unwrap();

        // 等待文件监听器处理变化(回调现在会自动触发)
        std::thread::sleep(Duration::from_millis(500));

        // 验证配置是否更新
        println!(
            "Config after first change: name={:?}, version={:?}, debug={:?}",
            state.get_string("app.name"),
            state.get_string("app.version"),
            state.get_bool("app.debug")
        );

        // 再次修改配置文件
        let second_modified_content = r#"
[app]
name = "final_app"
version = "3.0.0"
debug = false
count = 42
"#;
        fs::write(&config_path, second_modified_content).unwrap();

        // 等待文件监听器处理变化(回调会自动触发)
        std::thread::sleep(Duration::from_millis(500));

        // 测试通过程序设置方法写入(现在应该触发回调,因为值发生了变化)
        let count_before_set = *callback_count.lock().unwrap();
        state
            .set_string("app.name", "callback_test".to_string())
            .unwrap();
        let count_after_set = *callback_count.lock().unwrap();

        // 验证程序内部修改现在也会触发回调(如果值发生了变化)
        assert_eq!(
            count_before_set + 1, count_after_set,
            "Programmatic changes should trigger callback when value changes"
        );

        // 设置相同的值不应该触发回调
        let count_before_same_set = *callback_count.lock().unwrap();
        state
            .set_string("app.name", "callback_test".to_string())
            .unwrap();
        let count_after_same_set = *callback_count.lock().unwrap();
        assert_eq!(
            count_before_same_set, count_after_same_set,
            "Setting same value should NOT trigger callback"
        );

        // 验证设置成功
        assert_eq!(
            state.get_string("app.name"),
            Some("callback_test".to_string())
        );

        // 验证配置文件已更新
        let saved_content = fs::read_to_string(&config_path).unwrap();
        assert!(saved_content.contains("callback_test"));

        // 验证回调被调用
        let final_count = *callback_count.lock().unwrap();
        println!("Test completed. Final callback count: {}", final_count);

        // 回调应该被触发过多次
        assert!(
            final_count >= 1,
            "Callback should have been called at least once"
        );
    }

    #[test]
    fn test_dual_buffer_switching() {
        use std::time::Duration;

        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("dual_buffer_test.toml");

        // 创建初始配置文件
        let initial_content = r#"
[test]
value = "initial"
"#;
        fs::write(&config_path, initial_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 验证初始值
        assert_eq!(state.get_string("test.value"), Some("initial".to_string()));

        // 检查当前索引
        let initial_index = state.index.load();
        println!("Initial buffer index: {}", initial_index);

        // 测试双缓冲机制通过程序设置值
        println!("Testing dual buffer mechanism through programmatic changes...");

        // 通过程序设置值应该直接更新当前缓冲区
        state
            .set_string("test.value", "programmatic_change".to_string())
            .unwrap();
        assert_eq!(
            state.get_string("test.value"),
            Some("programmatic_change".to_string())
        );

        // 验证设置后缓冲区索引没有变化(因为是直接修改当前缓冲区)
        let after_set_index = state.index.load();
        println!("After programmatic set: buffer index = {}", after_set_index);
        assert_eq!(initial_index, after_set_index);

        // 测试文件监听器(可能需要更长时间)
        println!("Testing file watcher mechanism...");
        let watch_test_content = r#"
[test]
value = "watch_test"
watcher_active = true
"#;
        fs::write(&config_path, watch_test_content).unwrap();

        // 等待足够长的时间让文件监听器处理
        std::thread::sleep(Duration::from_millis(1000));

        // 打印结果而不是断言,因为文件监听器可能不会立即生效
        println!(
            "After file write: value={:?}, watcher_active={:?}",
            state.get_string("test.value"),
            state.get_bool("test.watcher_active")
        );

        let final_index = state.index.load();
        println!("Final buffer index: {}", final_index);
    }

    #[test]
    fn test_simple_set_get() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("simple_test.toml");

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 设置一个值
        state
            .set_string("test.key", "test_value".to_string())
            .unwrap();

        // 立即读取
        let result = state.get_string("test.key");
        println!("Set 'test_value', got: {:?}", result);
        assert_eq!(result, Some("test_value".to_string()));

        // 设置一个数字
        state.set_i64("test.number", 42).unwrap();

        // 立即读取
        let result = state.get_i64("test.number");
        println!("Set 42, got: {:?}", result);
        assert_eq!(result, Some(42));

        // 检查文件是否正确保存
        let file_content = std::fs::read_to_string(&config_path).unwrap();
        println!("File content:\n{}", file_content);
        assert!(file_content.contains("test_value"));
        assert!(file_content.contains("42"));
    }

    #[test]
    fn test_concurrent_file_operations() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("concurrent_test_config_unique.toml");

        // 创建测试配置文件
        let config_content = r#"
[test]
counter = 0
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 验证初始值
        assert_eq!(state.get_i64("test.counter"), Some(0));

        // 模拟外部程序修改文件
        let external_content = r#"
[test]
counter = 100
external_value = "added_by_external"
"#;
        fs::write(&config_path, external_content).unwrap();

        // 等待文件监听器处理变化(需要等待超过2秒的防抖延迟)
        std::thread::sleep(std::time::Duration::from_secs(3));

        // 读取时应该获取到外部修改的值
        assert_eq!(state.get_i64("test.counter"), Some(100));
        assert_eq!(
            state.get_string("test.external_value"),
            Some("added_by_external".to_string())
        );

        // 写入新值时应该基于当前文件内容
        state.set_i64("test.counter", 200).unwrap();

        // 验证写入后的文件内容
        let final_content = fs::read_to_string(&config_path).unwrap();
        assert!(final_content.contains("200"));
        assert!(final_content.contains("added_by_external"));

        // 验证读取结果
        assert_eq!(state.get_i64("test.counter"), Some(200));
        assert_eq!(
            state.get_string("test.external_value"),
            Some("added_by_external".to_string())
        );
    }

    #[test]
    fn test_buffer_consistency() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("buffer_test.toml");

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 检查初始索引
        let initial_index = state.get_current_buffer_index();
        println!("Initial buffer index: {}", initial_index);

        // 设置一个值
        println!("Setting test.value = 'before'");
        state
            .set_string("test.value", "before".to_string())
            .unwrap();

        // 检查设置后的索引
        let after_set_index = state.get_current_buffer_index();
        println!("After set buffer index: {}", after_set_index);

        // 立即读取
        let result = state.get_string("test.value");
        println!("Immediate read result: {:?}", result);

        // 再次检查索引
        let after_read_index = state.get_current_buffer_index();
        println!("After read buffer index: {}", after_read_index);

        // 验证一致性
        assert_eq!(
            initial_index, after_set_index,
            "Index should not change after set"
        );
        assert_eq!(
            after_set_index, after_read_index,
            "Index should not change after read"
        );
        assert_eq!(
            result,
            Some("before".to_string()),
            "Should read back the value we just set"
        );

        // 再次设置不同的值
        println!("Setting test.value = 'after'");
        state.set_string("test.value", "after".to_string()).unwrap();

        // 立即读取
        let result2 = state.get_string("test.value");
        println!("Second read result: {:?}", result2);

        assert_eq!(
            result2,
            Some("after".to_string()),
            "Should read back the second value"
        );
    }

    #[test]
    fn test_preloaded_config_consistency() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("preloaded_test.toml");

        // 创建测试配置文件
        let config_content = r#"
[database]
host = "original_host"
port = 5432
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态实例(这会加载配置文件)
        let state = ConfigState::init_config(&config_path);

        // 检查初始索引
        let initial_index = state.get_current_buffer_index();
        println!("Initial buffer index: {}", initial_index);

        // 读取预加载的配置
        let original_host = state.get_string("database.host");
        let original_port = state.get_i64("database.port");
        println!(
            "Original host: {:?}, port: {:?}",
            original_host, original_port
        );

        // 设置新值
        println!("Setting database.host = 'new_host'");
        state
            .set_string("database.host", "new_host".to_string())
            .unwrap();

        println!("Setting database.port = 3306");
        state.set_i64("database.port", 3306).unwrap();

        // 检查设置后的索引
        let after_set_index = state.get_current_buffer_index();
        println!("After set buffer index: {}", after_set_index);

        // 立即读取
        let new_host = state.get_string("database.host");
        let new_port = state.get_i64("database.port");
        println!("New host: {:?}, port: {:?}", new_host, new_port);

        // 验证一致性
        assert_eq!(
            initial_index, after_set_index,
            "Index should not change after set"
        );
        assert_eq!(
            original_host,
            Some("original_host".to_string()),
            "Should read original host"
        );
        assert_eq!(original_port, Some(5432), "Should read original port");
        assert_eq!(
            new_host,
            Some("new_host".to_string()),
            "Should read new host"
        );
        assert_eq!(new_port, Some(3306), "Should read new port");
    }

    #[test]
    fn test_auto_callback_on_external_change() {
        use std::sync::{Arc, Mutex};
        use std::time::Duration;

        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("auto_callback_test.toml");

        // 创建初始配置文件
        let initial_content = r#"
[app]
name = "initial_app"
version = "1.0.0"
"#;
        fs::write(&config_path, initial_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 设置回调计数器
        let callback_count = Arc::new(Mutex::new(0));
        let callback_count_clone = callback_count.clone();

        // 添加回调函数(现在会自动触发,无需手动轮询)
        state.add_change_callback(move |_state| {
            let mut count = callback_count_clone.lock().unwrap();
            *count += 1;
            println!("Auto callback triggered! Count: {}", *count);
        });

        // 模拟外部文件修改
        let modified_content = r#"
[app]
name = "externally_modified"
version = "2.0.0"
"#;
        fs::write(&config_path, modified_content).unwrap();

        // 等待文件监听器处理变化并自动触发回调(需要等待超过2秒的防抖延迟)
        std::thread::sleep(Duration::from_secs(3));

        // 验证配置已更新
        assert_eq!(
            state.get_string("app.name"),
            Some("externally_modified".to_string())
        );

        // 验证回调被自动执行
        let final_callback_count = *callback_count.lock().unwrap();
        println!("Final callback count: {}", final_callback_count);

        // 回调应该被自动触发
        assert!(
            final_callback_count >= 1,
            "Callback should have been auto-triggered by external file change"
        );
    }

    #[test]
    fn test_add_callback_value() {
        use std::sync::{Arc, Mutex};

        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("value_callback_test.toml");

        // 创建测试配置文件
        let config_content = r#"
[database]
host = "localhost"
port = 5432
enabled = true
"#;
        fs::write(&config_path, config_content).unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 记录回调接收到的值
        let host_values: Arc<Mutex<Vec<Option<String>>>> = Arc::new(Mutex::new(Vec::new()));
        let port_values: Arc<Mutex<Vec<Option<i64>>>> = Arc::new(Mutex::new(Vec::new()));
        let enabled_values: Arc<Mutex<Vec<Option<bool>>>> = Arc::new(Mutex::new(Vec::new()));

        // 测试字符串值回调(泛型版本)
        let host_values_clone = host_values.clone();
        state.add_callback_value("database.host", move |v: Option<String>| {
            let mut values = host_values_clone.lock().unwrap();
            println!("Host callback: {:?}", v);
            values.push(v);
        });

        // 测试整数值回调(泛型版本)
        let port_values_clone = port_values.clone();
        state.add_callback_value("database.port", move |v: Option<i64>| {
            let mut values = port_values_clone.lock().unwrap();
            println!("Port callback: {:?}", v);
            values.push(v);
        });

        // 测试布尔值回调(泛型版本)
        let enabled_values_clone = enabled_values.clone();
        state.add_callback_value("database.enabled", move |v: Option<bool>| {
            let mut values = enabled_values_clone.lock().unwrap();
            println!("Enabled callback: {:?}", v);
            values.push(v);
        });

        // 验证添加回调时立即触发了一次
        {
            let values = host_values.lock().unwrap();
            assert_eq!(values.len(), 1, "Callback should be triggered immediately when added");
            assert_eq!(values[0], Some("localhost".to_string()));
        }
        {
            let values = port_values.lock().unwrap();
            assert_eq!(values.len(), 1);
            assert_eq!(values[0], Some(5432));
        }
        {
            let values = enabled_values.lock().unwrap();
            assert_eq!(values.len(), 1);
            assert_eq!(values[0], Some(true));
        }

        // 修改值,验证回调被触发
        state.set_string("database.host", "192.168.1.1".to_string()).unwrap();
        {
            let values = host_values.lock().unwrap();
            assert_eq!(values.len(), 2, "Callback should be triggered on value change");
            assert_eq!(values[1], Some("192.168.1.1".to_string()));
        }

        state.set_i64("database.port", 3306).unwrap();
        {
            let values = port_values.lock().unwrap();
            assert_eq!(values.len(), 2);
            assert_eq!(values[1], Some(3306));
        }

        state.set_bool("database.enabled", false).unwrap();
        {
            let values = enabled_values.lock().unwrap();
            assert_eq!(values.len(), 2);
            assert_eq!(values[1], Some(false));
        }

        // 设置相同的值,不应该触发回调
        state.set_string("database.host", "192.168.1.1".to_string()).unwrap();
        {
            let values = host_values.lock().unwrap();
            assert_eq!(values.len(), 2, "Callback should NOT be triggered when value is the same");
        }

        println!("Test completed successfully!");
    }

    #[test]
    fn test_value_callback_with_null() {
        use std::sync::{Arc, Mutex};

        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("null_value_callback_test.toml");

        // 创建空配置文件
        fs::write(&config_path, "").unwrap();

        // 创建配置状态实例
        let state = ConfigState::init_config(&config_path);

        // 记录回调接收到的值(使用 Option<String> 泛型)
        let values: Arc<Mutex<Vec<Option<String>>>> = Arc::new(Mutex::new(Vec::new()));
        let values_clone = values.clone();

        // 添加对不存在键的回调(泛型版本)
        state.add_callback_value("nonexistent.key", move |v: Option<String>| {
            let mut vals = values_clone.lock().unwrap();
            println!("Nonexistent key callback: {:?}", v);
            vals.push(v);
        });

        // 验证初始回调收到 None(因为键不存在)
        {
            let vals = values.lock().unwrap();
            assert_eq!(vals.len(), 1);
            assert!(vals[0].is_none(), "Should receive None for nonexistent key");
        }

        // 设置值
        state.set_string("nonexistent.key", "now_exists".to_string()).unwrap();
        {
            let vals = values.lock().unwrap();
            assert_eq!(vals.len(), 2);
            assert_eq!(vals[1], Some("now_exists".to_string()));
        }

        println!("Null value callback test completed!");
    }
}