spicex 0.1.0

A complete configuration solution for Rust applications, inspired by Viper
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
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
//! Core Spice configuration management struct and implementation.

use crate::default_layer::DefaultConfigLayer;
use crate::error::{ConfigError, ConfigResult};
use crate::file_layer::FileConfigLayer;
use crate::layer::{utils, ConfigLayer, LayerPriority};
use crate::value::ConfigValue;
use crate::watcher::FileWatcher;
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::sync::mpsc;

/// Represents a component of a configuration key path.
#[derive(Debug, Clone, PartialEq)]
enum KeyPart {
    /// A string key for object access
    Key(String),
    /// A numeric index for array access
    Index(usize),
}

/// The main Spice configuration manager.
///
/// This struct manages configuration from multiple sources with a clear precedence hierarchy.
pub struct Spice {
    /// Configuration layers ordered by precedence (highest first)
    layers: Vec<Box<dyn ConfigLayer>>,

    /// Configuration file search paths
    config_paths: Vec<PathBuf>,

    /// Configuration file name (without extension)
    config_name: String,

    /// Environment variable prefix
    env_prefix: Option<String>,

    /// Key delimiter for nested access
    key_delimiter: String,

    /// Whether to automatically bind environment variables
    automatic_env: bool,

    /// File watcher for configuration file changes
    watcher: Option<FileWatcher>,

    /// List of configuration files being watched
    watched_config_files: Vec<PathBuf>,

    /// Channel receiver for reload signals from file watcher
    reload_receiver: Option<mpsc::Receiver<()>>,

    /// Flag to track if auto-reload callback is registered
    auto_reload_registered: bool,
}

impl Spice {
    /// Creates a new Spice instance with default settings.
    pub fn new() -> Self {
        Self {
            layers: Vec::new(),
            config_paths: Vec::new(),
            config_name: String::new(),
            env_prefix: None,
            key_delimiter: ".".to_string(),
            automatic_env: false,
            watcher: None,
            watched_config_files: Vec::new(),
            reload_receiver: None,
            auto_reload_registered: false,
        }
    }

    /// Adds a configuration layer to the Spice instance.
    /// Layers are automatically sorted by priority after addition.
    ///
    /// # Arguments
    /// * `layer` - The configuration layer to add
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, FileConfigLayer};
    /// use std::path::PathBuf;
    ///
    /// let mut spice = Spice::new();
    /// // Note: FileConfigLayer creation will be available after file layer implementation
    /// ```
    pub fn add_layer(&mut self, layer: Box<dyn ConfigLayer>) {
        self.layers.push(layer);
        utils::sort_layers_by_priority(&mut self.layers);
    }

    /// Removes all layers with the specified priority.
    ///
    /// # Arguments
    /// * `priority` - The priority level of layers to remove
    ///
    /// # Returns
    /// The number of layers removed
    pub fn remove_layers_by_priority(&mut self, priority: LayerPriority) -> usize {
        let initial_len = self.layers.len();
        self.layers.retain(|layer| layer.priority() != priority);
        initial_len - self.layers.len()
    }

    /// Returns the number of configuration layers currently registered.
    pub fn layer_count(&self) -> usize {
        self.layers.len()
    }

    /// Returns a list of all layer source names and their priorities.
    pub fn layer_info(&self) -> Vec<(String, LayerPriority)> {
        self.layers
            .iter()
            .map(|layer| (layer.source_name().to_string(), layer.priority()))
            .collect()
    }

    /// Clears all configuration layers.
    pub fn clear_layers(&mut self) {
        self.layers.clear();
    }

    /// Sets the configuration file name (without extension).
    ///
    /// # Arguments
    /// * `name` - The configuration file name
    pub fn set_config_name(&mut self, name: impl Into<String>) {
        self.config_name = name.into();
    }

    /// Gets the current configuration file name.
    pub fn config_name(&self) -> &str {
        &self.config_name
    }

    /// Adds a path to search for configuration files.
    ///
    /// # Arguments
    /// * `path` - The path to add to the search list
    pub fn add_config_path(&mut self, path: impl Into<PathBuf>) {
        self.config_paths.push(path.into());
    }

    /// Gets all configuration search paths.
    pub fn config_paths(&self) -> &[PathBuf] {
        &self.config_paths
    }

    /// Searches for configuration files in the configured search paths.
    /// Returns the first configuration file found that matches the configured name.
    ///
    /// # Returns
    /// * `ConfigResult<Option<PathBuf>>` - The path to the found configuration file, or None if not found
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    /// use std::path::PathBuf;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.add_config_path("./configs");
    /// spice.add_config_path("/etc/myapp");
    ///
    /// // This will search for config.json, config.yaml, config.toml, config.ini
    /// // in ./configs and /etc/myapp directories
    /// if let Some(config_file) = spice.find_config_file().unwrap() {
    ///     println!("Found config file: {}", config_file.display());
    /// }
    /// ```
    pub fn find_config_file(&self) -> ConfigResult<Option<PathBuf>> {
        if self.config_name.is_empty() {
            return Ok(None);
        }

        let supported_extensions = ["json", "yaml", "yml", "toml", "ini"];

        // Search in configured paths first
        for search_path in &self.config_paths {
            for extension in &supported_extensions {
                let config_file = search_path.join(format!("{}.{}", self.config_name, extension));
                if config_file.exists() && config_file.is_file() {
                    return Ok(Some(config_file));
                }
            }
        }

        // If no paths configured or file not found, search in standard locations
        if self.config_paths.is_empty() {
            let standard_paths = self.get_standard_config_paths()?;
            for search_path in standard_paths {
                for extension in &supported_extensions {
                    let config_file =
                        search_path.join(format!("{}.{}", self.config_name, extension));
                    if config_file.exists() && config_file.is_file() {
                        return Ok(Some(config_file));
                    }
                }
            }
        }

        Ok(None)
    }

    /// Gets standard configuration directory paths based on the operating system.
    ///
    /// # Returns
    /// * `ConfigResult<Vec<PathBuf>>` - List of standard configuration directories
    fn get_standard_config_paths(&self) -> ConfigResult<Vec<PathBuf>> {
        let mut paths = Vec::new();

        // Current directory (highest priority)
        paths.push(PathBuf::from("."));

        // User's home directory
        if let Some(home_dir) = dirs::home_dir() {
            paths.push(home_dir.join(".config"));
            paths.push(home_dir);
        }

        // System-wide configuration directories
        #[cfg(unix)]
        {
            paths.push(PathBuf::from("/etc"));
            paths.push(PathBuf::from("/usr/local/etc"));
        }

        #[cfg(windows)]
        {
            if let Ok(program_data) = env::var("PROGRAMDATA") {
                paths.push(PathBuf::from(program_data));
            }
            if let Ok(app_data) = env::var("APPDATA") {
                paths.push(PathBuf::from(app_data));
            }
        }

        Ok(paths)
    }

    /// Searches for all configuration files with the given name in search paths.
    /// Returns all matching files found, ordered by search path priority.
    ///
    /// # Returns
    /// * `ConfigResult<Vec<PathBuf>>` - List of all found configuration files
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.add_config_path("./configs");
    /// spice.add_config_path("/etc/myapp");
    ///
    /// let all_configs = spice.find_all_config_files().unwrap();
    /// for config_file in all_configs {
    ///     println!("Found config: {}", config_file.display());
    /// }
    /// ```
    pub fn find_all_config_files(&self) -> ConfigResult<Vec<PathBuf>> {
        if self.config_name.is_empty() {
            return Ok(Vec::new());
        }

        let mut found_files = Vec::new();
        let supported_extensions = ["json", "yaml", "yml", "toml", "ini"];

        // Search in configured paths first
        let search_paths = if self.config_paths.is_empty() {
            self.get_standard_config_paths()?
        } else {
            self.config_paths.clone()
        };

        for search_path in search_paths {
            for extension in &supported_extensions {
                let config_file = search_path.join(format!("{}.{}", self.config_name, extension));
                if config_file.exists() && config_file.is_file() {
                    found_files.push(config_file);
                }
            }
        }

        Ok(found_files)
    }

    /// Automatically discovers and loads a configuration file.
    /// This method searches for configuration files using the configured name and paths,
    /// then loads the first file found.
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if a file was found and loaded, or an error
    ///
    /// # Errors
    /// * `ConfigError::KeyNotFound` - If no configuration file is found
    /// * `ConfigError::Io` - If the file cannot be read
    /// * `ConfigError::Parse` - If the file content cannot be parsed
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.add_config_path("./configs");
    ///
    /// // This will automatically find and load the first config file found
    /// match spice.read_in_config() {
    ///     Ok(()) => println!("Configuration loaded successfully"),
    ///     Err(e) => println!("Failed to load configuration: {}", e),
    /// }
    /// ```
    pub fn read_in_config(&mut self) -> ConfigResult<()> {
        let config_file = self.find_config_file()?.ok_or_else(|| {
            ConfigError::key_not_found(format!("configuration file '{}'", self.config_name))
        })?;

        self.load_config_file(config_file)
    }

    /// Loads a specific configuration file and adds it as a configuration layer.
    ///
    /// # Arguments
    /// * `config_file` - Path to the configuration file to load
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the file was loaded, or an error
    pub fn load_config_file<P: AsRef<Path>>(&mut self, config_file: P) -> ConfigResult<()> {
        let file_layer = FileConfigLayer::new(config_file)?;
        self.add_layer(Box::new(file_layer));
        Ok(())
    }

    /// Merges multiple configuration files into the current configuration.
    /// This method finds all configuration files with the configured name and merges them
    /// in order of discovery (first found has highest precedence).
    ///
    /// # Returns
    /// * `ConfigResult<usize>` - The number of configuration files merged
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.add_config_path("./configs");
    /// spice.add_config_path("/etc/myapp");
    ///
    /// // This will find and merge all config files found in search paths
    /// let merged_count = spice.merge_in_config().unwrap();
    /// println!("Merged {} configuration files", merged_count);
    /// ```
    pub fn merge_in_config(&mut self) -> ConfigResult<usize> {
        let config_files = self.find_all_config_files()?;
        let count = config_files.len();

        for config_file in config_files {
            self.load_config_file(config_file)?;
        }

        Ok(count)
    }

    /// Sets the configuration file path explicitly and loads it.
    /// This method bypasses the search mechanism and loads a specific file.
    ///
    /// # Arguments
    /// * `config_file` - Path to the configuration file
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the file was loaded, or an error
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_file("./my-config.json").unwrap();
    /// ```
    pub fn set_config_file<P: AsRef<Path>>(&mut self, config_file: P) -> ConfigResult<()> {
        self.load_config_file(config_file)
    }

    /// Sets the environment variable prefix.
    ///
    /// # Arguments
    /// * `prefix` - The prefix to use for environment variables
    pub fn set_env_prefix(&mut self, prefix: impl Into<String>) {
        self.env_prefix = Some(prefix.into());
    }

    /// Gets the current environment variable prefix.
    pub fn env_prefix(&self) -> Option<&str> {
        self.env_prefix.as_deref()
    }

    /// Sets whether to automatically bind environment variables.
    ///
    /// # Arguments
    /// * `automatic` - Whether to enable automatic environment variable binding
    pub fn set_automatic_env(&mut self, automatic: bool) {
        self.automatic_env = automatic;
    }

    /// Gets whether automatic environment variable binding is enabled.
    pub fn is_automatic_env(&self) -> bool {
        self.automatic_env
    }

    /// Binds command line flags to the configuration.
    /// This method adds a FlagConfigLayer with the provided clap ArgMatches.
    ///
    /// # Arguments
    /// * `matches` - The parsed command line arguments from clap
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    /// use clap::{Arg, Command};
    ///
    /// let app = Command::new("myapp")
    ///     .arg(Arg::new("host")
    ///         .long("host")
    ///         .value_name("HOST"));
    ///
    /// let args = vec!["myapp", "--host", "localhost"];
    /// let matches = app.try_get_matches_from(args).unwrap();
    ///
    /// let mut spice = Spice::new();
    /// spice.bind_flags(matches);
    /// ```
    #[cfg(feature = "cli")]
    pub fn bind_flags(&mut self, matches: clap::ArgMatches) {
        use crate::cli::FlagConfigLayer;
        let flag_layer = FlagConfigLayer::new(matches);
        self.add_layer(Box::new(flag_layer));
    }

    /// Binds command line flags with custom flag-to-key mappings.
    ///
    /// # Arguments
    /// * `matches` - The parsed command line arguments from clap
    /// * `mappings` - HashMap mapping flag names to configuration keys
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    /// use clap::{Arg, Command};
    /// use std::collections::HashMap;
    ///
    /// let app = Command::new("myapp")
    ///     .arg(Arg::new("db_host")
    ///         .long("db-host")
    ///         .value_name("HOST"));
    ///
    /// let args = vec!["myapp", "--db-host", "localhost"];
    /// let matches = app.try_get_matches_from(args).unwrap();
    ///
    /// let mut mappings = HashMap::new();
    /// mappings.insert("db_host".to_string(), "database.host".to_string());
    ///
    /// let mut spice = Spice::new();
    /// spice.bind_flags_with_mappings(matches, mappings);
    /// ```
    #[cfg(feature = "cli")]
    pub fn bind_flags_with_mappings(
        &mut self,
        matches: clap::ArgMatches,
        mappings: std::collections::HashMap<String, String>,
    ) {
        use crate::cli::FlagConfigLayer;
        let flag_layer = FlagConfigLayer::with_mappings(matches, mappings);
        self.add_layer(Box::new(flag_layer));
    }

    /// Binds a specific flag to a configuration key.
    /// This is useful when you want to bind individual flags after the initial setup.
    ///
    /// # Arguments
    /// * `flag_name` - The name of the command line flag
    /// * `config_key` - The configuration key to bind to
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Ok if successful, error if no flag layer exists
    ///
    /// # Example
    /// ```
    /// use spice::Spice;
    /// use clap::{Arg, Command};
    ///
    /// let app = Command::new("myapp")
    ///     .arg(Arg::new("verbose")
    ///         .long("verbose")
    ///         .action(clap::ArgAction::SetTrue));
    ///
    /// let args = vec!["myapp", "--verbose"];
    /// let matches = app.try_get_matches_from(args).unwrap();
    ///
    /// let mut spice = Spice::new();
    /// spice.bind_flags(matches);
    /// spice.bind_flag("verbose", "logging.verbose").unwrap();
    /// ```
    #[cfg(feature = "cli")]
    pub fn bind_flag(
        &mut self,
        flag_name: impl Into<String>,
        config_key: impl Into<String>,
    ) -> ConfigResult<()> {
        use crate::cli::FlagConfigLayer;

        // Find the flag layer and add the mapping
        for layer in &mut self.layers {
            if layer.priority() == LayerPriority::Flags {
                if let Some(flag_layer) = layer.as_any_mut().downcast_mut::<FlagConfigLayer>() {
                    flag_layer.add_flag_mapping(flag_name, config_key);
                    return Ok(());
                }
            }
        }

        Err(ConfigError::unsupported_operation(
            "No flag configuration layer found. Call bind_flags() first.",
        ))
    }

    /// Sets the key delimiter for nested access.
    ///
    /// # Arguments
    /// * `delimiter` - The delimiter to use (default is ".")
    pub fn set_key_delimiter(&mut self, delimiter: impl Into<String>) {
        self.key_delimiter = delimiter.into();
    }

    /// Gets the current key delimiter.
    pub fn key_delimiter(&self) -> &str {
        &self.key_delimiter
    }

    /// Gets a configuration value by key, searching through all layers by precedence.
    /// Supports dot notation for nested access (e.g., "database.host") and array indexing (e.g., "servers.0.host").
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve, supporting dot notation for nested access
    ///
    /// # Returns
    /// * `ConfigResult<Option<ConfigValue>>` - The configuration value if found, None if not found
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    ///
    /// let spice = Spice::new();
    /// // After adding layers with configuration data
    /// // let value = spice.get("database.host").unwrap();
    /// // let array_value = spice.get("servers.0.host").unwrap();
    /// ```
    pub fn get(&self, key: &str) -> ConfigResult<Option<ConfigValue>> {
        // First try to get the exact key from layers
        if let Some(value) = utils::merge_value_from_layers(&self.layers, key)? {
            return Ok(Some(value));
        }

        // If not found and key contains delimiter, try nested access
        if key.contains(&self.key_delimiter) {
            self.get_nested(key)
        } else {
            Ok(None)
        }
    }

    /// Gets a nested configuration value using dot notation.
    /// This method handles nested object access and array indexing.
    ///
    /// # Arguments
    /// * `key` - The nested key path (e.g., "database.host", "servers.0.port")
    ///
    /// # Returns
    /// * `ConfigResult<Option<ConfigValue>>` - The nested value if found
    fn get_nested(&self, key: &str) -> ConfigResult<Option<ConfigValue>> {
        let key_parts = self.parse_key(key);

        // Try to find a root key that matches the beginning of our path
        for i in (1..=key_parts.len()).rev() {
            let root_key = self.key_parts_to_string(&key_parts[..i]);

            if let Some(root_value) = utils::merge_value_from_layers(&self.layers, &root_key)? {
                if i == key_parts.len() {
                    // Exact match
                    return Ok(Some(root_value));
                } else {
                    // Need to traverse deeper
                    let remaining_path = &key_parts[i..];
                    return Ok(self.traverse_nested_value(&root_value, remaining_path));
                }
            }
        }

        Ok(None)
    }

    /// Parses a key into its component parts, handling array indices.
    ///
    /// # Arguments
    /// * `key` - The key to parse
    ///
    /// # Returns
    /// * `Vec<KeyPart>` - The parsed key components
    fn parse_key(&self, key: &str) -> Vec<KeyPart> {
        key.split(&self.key_delimiter)
            .map(|part| {
                // Check if this part is an array index
                if let Ok(index) = part.parse::<usize>() {
                    KeyPart::Index(index)
                } else {
                    KeyPart::Key(part.to_string())
                }
            })
            .collect()
    }

    /// Traverses a nested ConfigValue using the provided path.
    ///
    /// # Arguments
    /// * `value` - The root value to traverse
    /// * `path` - The remaining path components
    ///
    /// # Returns
    /// * `Option<ConfigValue>` - The value at the end of the path, if found
    fn traverse_nested_value(&self, value: &ConfigValue, path: &[KeyPart]) -> Option<ConfigValue> {
        if path.is_empty() {
            return Some(value.clone());
        }

        match (&path[0], value) {
            (KeyPart::Key(key), ConfigValue::Object(obj)) => {
                if let Some(nested_value) = obj.get(key) {
                    self.traverse_nested_value(nested_value, &path[1..])
                } else {
                    None
                }
            }
            (KeyPart::Index(index), ConfigValue::Array(arr)) => {
                if *index < arr.len() {
                    self.traverse_nested_value(&arr[*index], &path[1..])
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Converts a slice of KeyPart back to a string key.
    ///
    /// # Arguments
    /// * `parts` - The key parts to convert
    ///
    /// # Returns
    /// * `String` - The reconstructed key string
    fn key_parts_to_string(&self, parts: &[KeyPart]) -> String {
        parts
            .iter()
            .map(|part| match part {
                KeyPart::Key(key) => key.clone(),
                KeyPart::Index(index) => index.to_string(),
            })
            .collect::<Vec<String>>()
            .join(&self.key_delimiter)
    }

    /// Sets a configuration value explicitly (highest precedence).
    /// This creates or updates an explicit layer with the highest precedence.
    ///
    /// # Arguments
    /// * `key` - The configuration key to set
    /// * `value` - The configuration value to set
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    ///
    /// let mut spice = Spice::new();
    /// spice.set("database.host", ConfigValue::from("localhost")).unwrap();
    /// ```
    pub fn set(&mut self, key: &str, value: ConfigValue) -> ConfigResult<()> {
        // Find or create an explicit layer
        let explicit_layer_index = self
            .layers
            .iter()
            .position(|layer| layer.priority() == LayerPriority::Explicit);

        match explicit_layer_index {
            Some(index) => {
                // Update existing explicit layer
                let layer = &mut self.layers[index];
                layer.set(key, value)?;
            }
            None => {
                // Create new explicit layer
                let mut explicit_layer = ExplicitConfigLayer::new();
                explicit_layer.set(key, value)?;
                self.add_layer(Box::new(explicit_layer));
            }
        }

        Ok(())
    }

    /// Sets a default configuration value.
    /// Default values have the lowest precedence and will only be used if no other
    /// configuration source provides a value for the same key.
    ///
    /// # Arguments
    /// * `key` - The configuration key to set a default for
    /// * `value` - The default configuration value
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    ///
    /// let mut spice = Spice::new();
    /// spice.set_default("database.host", ConfigValue::from("localhost")).unwrap();
    /// spice.set_default("database.port", ConfigValue::from(5432i64)).unwrap();
    ///
    /// // These defaults will be used unless overridden by other configuration sources
    /// assert_eq!(spice.get_string("database.host").unwrap(), Some("localhost".to_string()));
    /// ```
    pub fn set_default(&mut self, key: &str, value: ConfigValue) -> ConfigResult<()> {
        // Find or create a default layer
        let default_layer_index = self
            .layers
            .iter()
            .position(|layer| layer.priority() == LayerPriority::Defaults);

        match default_layer_index {
            Some(index) => {
                // Update existing default layer
                let layer = &mut self.layers[index];
                layer.set(key, value)?;
            }
            None => {
                // Create new default layer
                let mut default_layer = DefaultConfigLayer::new();
                default_layer.set(key, value)?;
                self.add_layer(Box::new(default_layer));
            }
        }

        Ok(())
    }

    /// Sets multiple default configuration values at once.
    /// This is more efficient than calling set_default multiple times.
    ///
    /// # Arguments
    /// * `defaults` - A HashMap containing the default key-value pairs
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    /// use std::collections::HashMap;
    ///
    /// let mut spice = Spice::new();
    /// let mut defaults = HashMap::new();
    /// defaults.insert("database.host".to_string(), ConfigValue::from("localhost"));
    /// defaults.insert("database.port".to_string(), ConfigValue::from(5432i64));
    /// defaults.insert("database.ssl".to_string(), ConfigValue::from(false));
    /// defaults.insert("server.timeout".to_string(), ConfigValue::from(30i64));
    ///
    /// spice.set_defaults(defaults).unwrap();
    ///
    /// // All defaults are now available
    /// assert_eq!(spice.get_string("database.host").unwrap(), Some("localhost".to_string()));
    /// assert_eq!(spice.get_i64("database.port").unwrap(), Some(5432));
    /// ```
    pub fn set_defaults(&mut self, defaults: HashMap<String, ConfigValue>) -> ConfigResult<()> {
        // Find or create a default layer
        let default_layer_index = self
            .layers
            .iter()
            .position(|layer| layer.priority() == LayerPriority::Defaults);

        match default_layer_index {
            Some(index) => {
                // Update existing default layer
                let layer = &mut self.layers[index];
                for (key, value) in defaults {
                    layer.set(&key, value)?;
                }
            }
            None => {
                // Create new default layer with all defaults
                let default_layer = DefaultConfigLayer::with_defaults(defaults);
                self.add_layer(Box::new(default_layer));
            }
        }

        Ok(())
    }

    /// Gets a configuration value as a string.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<String>>` - The string value if found and convertible
    pub fn get_string(&self, key: &str) -> ConfigResult<Option<String>> {
        match self.get(key)? {
            Some(value) => Ok(Some(value.coerce_to_string())),
            None => Ok(None),
        }
    }

    /// Gets a configuration value as an integer.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<i64>>` - The integer value if found and convertible
    pub fn get_int(&self, key: &str) -> ConfigResult<Option<i64>> {
        match self.get(key)? {
            Some(value) => match value.as_i64() {
                Some(i) => Ok(Some(i)),
                None => Err(ConfigError::type_conversion(value.type_name(), "integer")),
            },
            None => Ok(None),
        }
    }

    /// Gets a configuration value as a 64-bit integer.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<i64>>` - The i64 value if found and convertible
    pub fn get_i64(&self, key: &str) -> ConfigResult<Option<i64>> {
        self.get_int(key)
    }

    /// Gets a configuration value as a 32-bit integer.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<i32>>` - The i32 value if found and convertible
    pub fn get_i32(&self, key: &str) -> ConfigResult<Option<i32>> {
        match self.get_int(key)? {
            Some(i) => {
                if i >= i32::MIN as i64 && i <= i32::MAX as i64 {
                    Ok(Some(i as i32))
                } else {
                    Err(ConfigError::type_conversion("i64", "i32"))
                }
            }
            None => Ok(None),
        }
    }

    /// Gets a configuration value as a floating point number.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<f64>>` - The float value if found and convertible
    pub fn get_float(&self, key: &str) -> ConfigResult<Option<f64>> {
        match self.get(key)? {
            Some(value) => match value.as_f64() {
                Some(f) => Ok(Some(f)),
                None => Err(ConfigError::type_conversion(value.type_name(), "float")),
            },
            None => Ok(None),
        }
    }

    /// Gets a configuration value as a 64-bit floating point number.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<f64>>` - The f64 value if found and convertible
    pub fn get_f64(&self, key: &str) -> ConfigResult<Option<f64>> {
        self.get_float(key)
    }

    /// Gets a configuration value as a 32-bit floating point number.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<f32>>` - The f32 value if found and convertible
    pub fn get_f32(&self, key: &str) -> ConfigResult<Option<f32>> {
        match self.get_float(key)? {
            Some(f) => {
                if f.is_finite() && f >= f32::MIN as f64 && f <= f32::MAX as f64 {
                    Ok(Some(f as f32))
                } else {
                    Err(ConfigError::type_conversion("f64", "f32"))
                }
            }
            None => Ok(None),
        }
    }

    /// Gets a configuration value as a boolean.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<bool>>` - The boolean value if found and convertible
    pub fn get_bool(&self, key: &str) -> ConfigResult<Option<bool>> {
        match self.get(key)? {
            Some(value) => match value.coerce_to_bool() {
                Some(b) => Ok(Some(b)),
                None => Err(ConfigError::type_conversion(value.type_name(), "boolean")),
            },
            None => Ok(None),
        }
    }

    /// Gets a configuration value as an array.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<Vec<ConfigValue>>>` - The array value if found and convertible
    pub fn get_array(&self, key: &str) -> ConfigResult<Option<Vec<ConfigValue>>> {
        match self.get(key)? {
            Some(value) => match value.as_array() {
                Some(arr) => Ok(Some(arr.clone())),
                None => Err(ConfigError::type_conversion(value.type_name(), "array")),
            },
            None => Ok(None),
        }
    }

    /// Gets a configuration value as an object/map.
    ///
    /// # Arguments
    /// * `key` - The configuration key to retrieve
    ///
    /// # Returns
    /// * `ConfigResult<Option<HashMap<String, ConfigValue>>>` - The object value if found and convertible
    pub fn get_object(
        &self,
        key: &str,
    ) -> ConfigResult<Option<std::collections::HashMap<String, ConfigValue>>> {
        match self.get(key)? {
            Some(value) => match value.as_object() {
                Some(obj) => Ok(Some(obj.clone())),
                None => Err(ConfigError::type_conversion(value.type_name(), "object")),
            },
            None => Ok(None),
        }
    }

    /// Checks if a configuration key exists in any layer.
    ///
    /// # Arguments
    /// * `key` - The configuration key to check
    ///
    /// # Returns
    /// * `bool` - True if the key exists, false otherwise
    pub fn is_set(&self, key: &str) -> bool {
        self.get(key).unwrap_or(None).is_some()
    }

    /// Gets all configuration keys from all layers.
    ///
    /// # Returns
    /// * `Vec<String>` - All unique configuration keys
    pub fn all_keys(&self) -> Vec<String> {
        utils::collect_all_keys(&self.layers)
    }

    /// Creates a nested configuration structure from flat keys.
    /// This method takes a flat map of keys (like "database.host") and converts them
    /// into a nested structure suitable for serialization.
    ///
    /// # Arguments
    /// * `flat_settings` - A flat map of configuration keys and values
    ///
    /// # Returns
    /// * `HashMap<String, ConfigValue>` - A nested configuration structure
    ///
    /// This is an internal method used by serialization functions.
    fn expand_nested_keys(
        &self,
        flat_settings: HashMap<String, ConfigValue>,
    ) -> HashMap<String, ConfigValue> {
        let mut result = HashMap::new();

        for (key, value) in flat_settings {
            self.insert_nested_value(&mut result, &key, value);
        }

        result
    }

    /// Inserts a value into a nested structure using dot notation.
    ///
    /// # Arguments
    /// * `target` - The target map to insert into
    /// * `key` - The dot-separated key path
    /// * `value` - The value to insert
    fn insert_nested_value(
        &self,
        target: &mut HashMap<String, ConfigValue>,
        key: &str,
        value: ConfigValue,
    ) {
        let parts: Vec<&str> = key.split(&self.key_delimiter).collect();

        if parts.len() == 1 {
            // Simple key, insert directly
            target.insert(key.to_string(), value);
            return;
        }

        // Recursively create nested structure
        self.insert_nested_value_recursive(target, &parts, 0, value);
    }

    fn insert_nested_value_recursive(
        &self,
        current: &mut HashMap<String, ConfigValue>,
        parts: &[&str],
        index: usize,
        value: ConfigValue,
    ) {
        if index >= parts.len() {
            return;
        }

        let part = parts[index];

        if index == parts.len() - 1 {
            // Last part, insert the value
            current.insert(part.to_string(), value);
        } else {
            // Intermediate part, ensure we have an object
            let entry = current
                .entry(part.to_string())
                .or_insert_with(|| ConfigValue::Object(HashMap::new()));

            match entry {
                ConfigValue::Object(ref mut obj) => {
                    self.insert_nested_value_recursive(obj, parts, index + 1, value);
                }
                _ => {
                    // Overwrite non-object with object
                    *entry = ConfigValue::Object(HashMap::new());
                    if let ConfigValue::Object(ref mut obj) = entry {
                        self.insert_nested_value_recursive(obj, parts, index + 1, value);
                    }
                }
            }
        }
    }

    /// Gets all configuration settings as a merged map.
    ///
    /// # Returns
    /// * `ConfigResult<HashMap<String, ConfigValue>>` - All configuration settings merged by precedence
    pub fn all_settings(&self) -> ConfigResult<HashMap<String, ConfigValue>> {
        let flat_settings = utils::merge_all_layers(&self.layers)?;
        Ok(self.expand_nested_keys(flat_settings))
    }

    /// Gets all configuration settings optimized for serialization.
    /// This method performs enhanced merging and handles complex nested structures
    /// to ensure proper serialization to various formats.
    ///
    /// # Returns
    /// * `ConfigResult<HashMap<String, ConfigValue>>` - All configuration settings optimized for serialization
    pub fn all_settings_for_serialization(&self) -> ConfigResult<HashMap<String, ConfigValue>> {
        // Get flat settings from all layers with proper precedence
        let flat_settings = utils::merge_all_layers(&self.layers)?;

        // Expand nested keys and handle format-specific considerations
        let mut expanded = self.expand_nested_keys(flat_settings);

        // Perform additional processing for serialization compatibility
        self.optimize_for_serialization(&mut expanded);

        Ok(expanded)
    }

    /// Optimizes configuration data for serialization by handling edge cases
    /// and ensuring compatibility with different output formats.
    fn optimize_for_serialization(&self, settings: &mut HashMap<String, ConfigValue>) {
        // Recursively process all values
        for (_, value) in settings.iter_mut() {
            self.optimize_config_value_for_serialization(value);
        }
    }

    /// Recursively optimizes a ConfigValue for serialization.
    fn optimize_config_value_for_serialization(&self, value: &mut ConfigValue) {
        match value {
            ConfigValue::Object(obj) => {
                // Recursively optimize nested objects
                for (_, nested_value) in obj.iter_mut() {
                    self.optimize_config_value_for_serialization(nested_value);
                }
            }
            ConfigValue::Array(arr) => {
                // Recursively optimize array elements
                for element in arr.iter_mut() {
                    self.optimize_config_value_for_serialization(element);
                }
            }
            ConfigValue::Float(f) => {
                // Handle special float values that might not serialize well
                if f.is_nan() || f.is_infinite() {
                    *value = ConfigValue::String(f.to_string());
                }
            }
            _ => {
                // Other types are fine as-is
            }
        }
    }

    /// Writes the current configuration to a file.
    /// The file format is determined by the file extension.
    ///
    /// # Arguments
    /// * `filename` - The path to the file to write
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the file was written, or an error
    ///
    /// # Errors
    /// * `ConfigError::UnsupportedFormat` - If the file extension is not supported
    /// * `ConfigError::Io` - If the file cannot be written
    /// * `ConfigError::Serialization` - If the configuration cannot be serialized
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set("app.name", "my-app".into()).unwrap();
    /// spice.set("app.port", 8080i64.into()).unwrap();
    ///
    /// // Write to JSON file
    /// spice.write_config("config.json").unwrap();
    /// ```
    pub fn write_config<P: AsRef<Path>>(&self, filename: P) -> ConfigResult<()> {
        let path = filename.as_ref();

        // Get file extension to determine format
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .ok_or(ConfigError::UnsupportedFormat)?;

        // Get all current settings with enhanced merging
        let settings = self.all_settings_for_serialization()?;

        // Get the appropriate parser and serialize with enhanced error handling
        let parser = crate::parser::detect_parser_by_extension(extension).map_err(|e| {
            ConfigError::Serialization(format!(
                "Failed to detect parser for extension '{extension}': {e}"
            ))
        })?;

        let content = parser.serialize(&settings).map_err(|e| {
            ConfigError::Serialization(format!(
                "Failed to serialize configuration to {}: {}",
                extension.to_uppercase(),
                e
            ))
        })?;

        // Create parent directories if they don't exist
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                ConfigError::Io(std::io::Error::new(
                    e.kind(),
                    format!(
                        "Failed to create parent directories for '{}': {}",
                        path.display(),
                        e
                    ),
                ))
            })?;
        }

        // Write to file with enhanced error handling
        std::fs::write(path, content).map_err(|e| {
            ConfigError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to write configuration to '{}': {}",
                    path.display(),
                    e
                ),
            ))
        })?;

        Ok(())
    }

    /// Writes the current configuration to a file in a specific format.
    /// This method allows you to specify the format explicitly, regardless of file extension.
    ///
    /// # Arguments
    /// * `filename` - The path to the file to write
    /// * `format` - The format to use for serialization ("json", "yaml", "toml", "ini")
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the file was written, or an error
    ///
    /// # Errors
    /// * `ConfigError::UnsupportedFormat` - If the format is not supported
    /// * `ConfigError::Io` - If the file cannot be written
    /// * `ConfigError::Serialization` - If the configuration cannot be serialized
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set("app.name", "my-app".into()).unwrap();
    /// spice.set("app.port", 8080i64.into()).unwrap();
    ///
    /// // Write as YAML regardless of file extension
    /// spice.write_config_as("config.txt", "yaml").unwrap();
    /// ```
    pub fn write_config_as<P: AsRef<Path>>(&self, filename: P, format: &str) -> ConfigResult<()> {
        let path = filename.as_ref();

        // Get all current settings with enhanced merging and serialization optimization
        let settings = self.all_settings_for_serialization()?;

        // Get the appropriate parser and serialize with enhanced error handling
        let parser = crate::parser::detect_parser_by_extension(format).map_err(|e| {
            ConfigError::Serialization(format!(
                "Failed to detect parser for format '{format}': {e}"
            ))
        })?;

        let content = parser.serialize(&settings).map_err(|e| {
            ConfigError::Serialization(format!(
                "Failed to serialize configuration to {}: {}",
                format.to_uppercase(),
                e
            ))
        })?;

        // Create parent directories if they don't exist
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    ConfigError::Io(std::io::Error::new(
                        e.kind(),
                        format!(
                            "Failed to create parent directories for '{}': {}",
                            path.display(),
                            e
                        ),
                    ))
                })?;
            }
        }

        // Write to file with enhanced error handling
        std::fs::write(path, content).map_err(|e| {
            ConfigError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to write configuration to '{}': {}",
                    path.display(),
                    e
                ),
            ))
        })?;

        Ok(())
    }

    /// Safely writes the current configuration to a file, preventing overwriting existing files.
    /// This method will fail if the target file already exists.
    ///
    /// # Arguments
    /// * `filename` - The path to the file to write
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the file was written, or an error
    ///
    /// # Errors
    /// * `ConfigError::Io` - If the file already exists or cannot be written
    /// * `ConfigError::UnsupportedFormat` - If the file extension is not supported
    /// * `ConfigError::Serialization` - If the configuration cannot be serialized
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set("app.name", "my-app".into()).unwrap();
    ///
    /// // This will fail if config.json already exists
    /// match spice.safe_write_config("config.json") {
    ///     Ok(()) => println!("Configuration written successfully"),
    ///     Err(e) => println!("Failed to write config: {}", e),
    /// }
    /// ```
    pub fn safe_write_config<P: AsRef<Path>>(&self, filename: P) -> ConfigResult<()> {
        let path = filename.as_ref();

        // Check if file already exists
        if path.exists() {
            return Err(ConfigError::Io(std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                format!("File '{}' already exists", path.display()),
            )));
        }

        // Use regular write_config if file doesn't exist
        self.write_config(path)
    }

    /// Creates a sub-configuration focused on a specific key prefix.
    /// This allows working with a subsection of the configuration as if it were the root.
    ///
    /// # Arguments
    /// * `key` - The key prefix to focus on (e.g., "database" to work with database.* keys)
    ///
    /// # Returns
    /// * `ConfigResult<Option<Spice>>` - A new Spice instance focused on the subsection, or None if the key doesn't exist
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    /// use std::collections::HashMap;
    ///
    /// let mut spice = Spice::new();
    /// let mut db_config = HashMap::new();
    /// db_config.insert("host".to_string(), ConfigValue::from("localhost"));
    /// db_config.insert("port".to_string(), ConfigValue::from(5432i64));
    /// spice.set("database", ConfigValue::Object(db_config)).unwrap();
    ///
    /// // Create a sub-configuration for database settings
    /// if let Some(db_viper) = spice.sub("database").unwrap() {
    ///     // Now you can access "host" directly instead of "database.host"
    ///     let host = db_viper.get_string("host").unwrap();
    ///     assert_eq!(host, Some("localhost".to_string()));
    /// }
    /// ```
    pub fn sub(&self, key: &str) -> ConfigResult<Option<Spice>> {
        // Get the value at the specified key
        match self.get(key)? {
            Some(ConfigValue::Object(obj)) => {
                // Create a new Spice instance with the object data
                let mut sub_viper = Spice::new();
                sub_viper.key_delimiter = self.key_delimiter.clone();

                // Create a sub-configuration layer with the object data
                let sub_layer = SubConfigLayer::new(key, obj);
                sub_viper.add_layer(Box::new(sub_layer));

                Ok(Some(sub_viper))
            }
            Some(_) => {
                // The key exists but is not an object, so we can't create a sub-configuration
                Ok(None)
            }
            None => {
                // The key doesn't exist
                Ok(None)
            }
        }
    }

    /// Unmarshals the entire configuration into a struct that implements Deserialize.
    /// This method uses serde to deserialize the merged configuration from all layers
    /// into the target struct type.
    ///
    /// # Type Parameters
    /// * `T` - The target struct type that implements serde::Deserialize
    ///
    /// # Returns
    /// * `ConfigResult<T>` - The deserialized struct or an error if deserialization fails
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    /// use serde::Deserialize;
    /// use std::collections::HashMap;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct DatabaseConfig {
    ///     host: String,
    ///     port: u16,
    ///     #[serde(default)]
    ///     ssl: bool,
    /// }
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct AppConfig {
    ///     database: DatabaseConfig,
    ///     debug: bool,
    /// }
    ///
    /// let mut spice = Spice::new();
    /// let mut db_config = HashMap::new();
    /// db_config.insert("host".to_string(), ConfigValue::from("localhost"));
    /// db_config.insert("port".to_string(), ConfigValue::from(5432i64));
    /// spice.set("database", ConfigValue::Object(db_config)).unwrap();
    /// spice.set("debug", ConfigValue::from(true)).unwrap();
    ///
    /// let config: AppConfig = spice.unmarshal().unwrap();
    /// assert_eq!(config.database.host, "localhost");
    /// assert_eq!(config.database.port, 5432);
    /// assert_eq!(config.debug, true);
    /// ```
    pub fn unmarshal<T>(&self) -> ConfigResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        // Get all settings merged from all layers
        let all_settings = self.all_settings()?;

        // Convert the HashMap<String, ConfigValue> to a ConfigValue::Object
        let config_value = ConfigValue::Object(all_settings);

        // Use serde to deserialize the ConfigValue into the target type
        serde_json::from_value(serde_json::to_value(config_value)?).map_err(|e| {
            ConfigError::deserialization(format!("Failed to unmarshal configuration: {e}"))
        })
    }

    /// Unmarshals a specific configuration key into a struct that implements Deserialize.
    /// This method allows deserializing only a portion of the configuration.
    ///
    /// # Arguments
    /// * `key` - The configuration key to unmarshal (supports dot notation for nested access)
    ///
    /// # Type Parameters
    /// * `T` - The target struct type that implements serde::Deserialize
    ///
    /// # Returns
    /// * `ConfigResult<T>` - The deserialized struct or an error if the key doesn't exist or deserialization fails
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue};
    /// use serde::Deserialize;
    /// use std::collections::HashMap;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct DatabaseConfig {
    ///     host: String,
    ///     port: u16,
    ///     #[serde(default)]
    ///     ssl: bool,
    /// }
    ///
    /// let mut spice = Spice::new();
    /// let mut db_config = HashMap::new();
    /// db_config.insert("host".to_string(), ConfigValue::from("localhost"));
    /// db_config.insert("port".to_string(), ConfigValue::from(5432i64));
    /// spice.set("database", ConfigValue::Object(db_config)).unwrap();
    ///
    /// let db_config: DatabaseConfig = spice.unmarshal_key("database").unwrap();
    /// assert_eq!(db_config.host, "localhost");
    /// assert_eq!(db_config.port, 5432);
    /// assert_eq!(db_config.ssl, false); // default value
    /// ```
    pub fn unmarshal_key<T>(&self, key: &str) -> ConfigResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        // Get the value at the specified key
        let config_value = self
            .get(key)?
            .ok_or_else(|| ConfigError::key_not_found(key))?;

        // Use serde to deserialize the ConfigValue into the target type
        serde_json::from_value(serde_json::to_value(config_value)?).map_err(|e| {
            ConfigError::deserialization(format!("Failed to unmarshal key '{key}': {e}"))
        })
    }

    /// Unmarshals the entire configuration into a struct with validation.
    /// This method deserializes the configuration and then validates it using the provided validator function.
    ///
    /// # Arguments
    /// * `validator` - A function that validates the deserialized struct and returns a Result
    ///
    /// # Type Parameters
    /// * `T` - The target struct type that implements serde::Deserialize
    ///
    /// # Returns
    /// * `ConfigResult<T>` - The validated deserialized struct or an error if deserialization or validation fails
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue, ConfigError};
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct ServerConfig {
    ///     host: String,
    ///     port: u16,
    /// }
    ///
    /// impl ServerConfig {
    ///     fn validate(&self) -> Result<(), String> {
    ///         if self.port == 0 {
    ///             return Err("Port cannot be zero".to_string());
    ///         }
    ///         if self.host.is_empty() {
    ///             return Err("Host cannot be empty".to_string());
    ///         }
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let mut spice = Spice::new();
    /// spice.set("host", ConfigValue::from("localhost")).unwrap();
    /// spice.set("port", ConfigValue::from(8080i64)).unwrap();
    ///
    /// let config: ServerConfig = spice.unmarshal_with_validation(|config: &ServerConfig| {
    ///     config.validate().map_err(|e| ConfigError::invalid_value(e))
    /// }).unwrap();
    /// ```
    pub fn unmarshal_with_validation<T, F>(&self, validator: F) -> ConfigResult<T>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(&T) -> ConfigResult<()>,
    {
        let config: T = self.unmarshal()?;
        validator(&config)?;
        Ok(config)
    }

    /// Unmarshals a specific configuration key into a struct with validation.
    /// This method deserializes a specific configuration section and then validates it.
    ///
    /// # Arguments
    /// * `key` - The configuration key to unmarshal (supports dot notation for nested access)
    /// * `validator` - A function that validates the deserialized struct and returns a Result
    ///
    /// # Type Parameters
    /// * `T` - The target struct type that implements serde::Deserialize
    ///
    /// # Returns
    /// * `ConfigResult<T>` - The validated deserialized struct or an error if deserialization or validation fails
    ///
    /// # Example
    /// ```
    /// use spice::{Spice, ConfigValue, ConfigError};
    /// use serde::Deserialize;
    /// use std::collections::HashMap;
    ///
    /// #[derive(Deserialize, Debug, PartialEq)]
    /// struct DatabaseConfig {
    ///     host: String,
    ///     port: u16,
    /// }
    ///
    /// impl DatabaseConfig {
    ///     fn validate(&self) -> Result<(), String> {
    ///         if self.port < 1024 {
    ///             return Err("Port should be >= 1024 for non-privileged access".to_string());
    ///         }
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let mut spice = Spice::new();
    /// let mut db_config = HashMap::new();
    /// db_config.insert("host".to_string(), ConfigValue::from("localhost"));
    /// db_config.insert("port".to_string(), ConfigValue::from(5432i64));
    /// spice.set("database", ConfigValue::Object(db_config)).unwrap();
    ///
    /// let config: DatabaseConfig = spice.unmarshal_key_with_validation("database", |config: &DatabaseConfig| {
    ///     config.validate().map_err(|e| ConfigError::invalid_value(e))
    /// }).unwrap();
    /// ```
    pub fn unmarshal_key_with_validation<T, F>(&self, key: &str, validator: F) -> ConfigResult<T>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(&T) -> ConfigResult<()>,
    {
        let config: T = self.unmarshal_key(key)?;
        validator(&config)?;
        Ok(config)
    }

    /// Enables automatic reloading of configuration files when they change.
    /// This method sets up file system watching for all currently loaded configuration files
    /// and will automatically reload them when changes are detected.
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if file watching was enabled, or an error
    ///
    /// # Errors
    /// * `ConfigError::FileWatch` - If file watching cannot be initialized
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.read_in_config().unwrap();
    ///
    /// // Enable automatic reloading when config files change
    /// spice.watch_config().unwrap();
    ///
    /// // Configuration will now automatically reload when files change
    /// ```
    pub fn watch_config(&mut self) -> ConfigResult<()> {
        // Collect all file paths from FileConfigLayer instances
        let mut config_files = Vec::new();

        for layer in &self.layers {
            if let Some(file_layer) = layer.as_any().downcast_ref::<FileConfigLayer>() {
                config_files.push(file_layer.file_path().to_path_buf());
            }
        }

        if config_files.is_empty() {
            return Err(ConfigError::FileWatch(
                "No configuration files to watch. Load a configuration file first.".to_string(),
            ));
        }

        // Create file watcher if it doesn't exist
        if self.watcher.is_none() {
            self.watcher = Some(FileWatcher::new_empty()?);
        }

        let watcher = self.watcher.as_mut().unwrap();

        // Watch all configuration files
        for config_file in &config_files {
            if !watcher.watched_files().contains(config_file) {
                watcher.watch_file(config_file)?;
            }
        }

        // Store the list of watched files
        self.watched_config_files = config_files;

        // Start watching in background
        watcher.start_watching()?;

        Ok(())
    }

    /// Registers a callback to be called when configuration files change.
    /// This method allows you to register custom handlers that will be called
    /// whenever a watched configuration file is modified.
    ///
    /// # Arguments
    /// * `callback` - A function to call when configuration changes are detected
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if the callback was registered, or an error
    ///
    /// # Errors
    /// * `ConfigError::FileWatch` - If file watching is not enabled or callback registration fails
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    /// use std::sync::{Arc, Mutex};
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.read_in_config().unwrap();
    /// spice.watch_config().unwrap();
    ///
    /// let reload_count = Arc::new(Mutex::new(0));
    /// let reload_count_clone = Arc::clone(&reload_count);
    ///
    /// spice.on_config_change(move || {
    ///     let mut count = reload_count_clone.lock().unwrap();
    ///     *count += 1;
    ///     println!("Configuration reloaded {} times", *count);
    /// }).unwrap();
    /// ```
    pub fn on_config_change<F>(&mut self, callback: F) -> ConfigResult<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        if self.watcher.is_none() {
            return Err(ConfigError::FileWatch(
                "File watching is not enabled. Call watch_config() first.".to_string(),
            ));
        }

        // First register the automatic reload callback
        self.register_auto_reload_callback()?;

        // Then register the user's callback
        if let Some(watcher) = &mut self.watcher {
            watcher.on_config_change(callback)?;
        }

        Ok(())
    }

    /// Registers an internal callback for automatic configuration reloading.
    /// This method sets up the automatic reloading functionality that refreshes
    /// configuration layers when file changes are detected.
    fn register_auto_reload_callback(&mut self) -> ConfigResult<()> {
        if self.auto_reload_registered {
            return Ok(()); // Already registered
        }

        // Create a channel for reload signals
        let (reload_sender, reload_receiver) = mpsc::channel();
        self.reload_receiver = Some(reload_receiver);

        // Register a callback that sends reload signals
        if let Some(watcher) = &mut self.watcher {
            watcher.on_config_change(move || {
                // Send reload signal (ignore errors if receiver is dropped)
                let _ = reload_sender.send(());
            })?;
        }

        self.auto_reload_registered = true;
        Ok(())
    }

    /// Stops watching configuration files for changes.
    /// This method disables automatic reloading and stops the file watching background thread.
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.read_in_config().unwrap();
    /// spice.watch_config().unwrap();
    ///
    /// // Later, stop watching
    /// spice.stop_watching();
    /// ```
    pub fn stop_watching(&mut self) {
        if let Some(watcher) = &mut self.watcher {
            watcher.stop_watching();
        }
        self.watched_config_files.clear();
    }

    /// Returns whether configuration file watching is currently active.
    ///
    /// # Returns
    /// * `bool` - True if file watching is active, false otherwise
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// assert!(!spice.is_watching());
    ///
    /// spice.set_config_name("config");
    /// spice.read_in_config().unwrap();
    /// spice.watch_config().unwrap();
    /// assert!(spice.is_watching());
    /// ```
    pub fn is_watching(&self) -> bool {
        self.watcher.as_ref().is_some_and(|w| w.is_watching())
    }

    /// Returns the list of configuration files currently being watched.
    ///
    /// # Returns
    /// * `&[PathBuf]` - Slice of paths to watched configuration files
    ///
    /// # Example
    /// ```no_run
    /// use spice::Spice;
    ///
    /// let mut spice = Spice::new();
    /// spice.set_config_name("config");
    /// spice.read_in_config().unwrap();
    /// spice.watch_config().unwrap();
    ///
    /// let watched_files = spice.watched_config_files();
    /// println!("Watching {} configuration files", watched_files.len());
    /// ```
    pub fn watched_config_files(&self) -> &[PathBuf] {
        &self.watched_config_files
    }

    /// Processes pending reload signals from file watchers.
    /// This method should be called periodically to handle automatic reloading.
    /// It's automatically called by other methods that access configuration values.
    ///
    /// # Returns
    /// * `ConfigResult<bool>` - True if configuration was reloaded, false if no reload was needed
    ///
    /// # Errors
    /// * `ConfigError::Io` - If configuration files cannot be read during reload
    /// * `ConfigError::Parse` - If configuration files cannot be parsed during reload
    pub fn process_reload_signals(&mut self) -> ConfigResult<bool> {
        if let Some(receiver) = &self.reload_receiver {
            // Check for reload signals without blocking
            match receiver.try_recv() {
                Ok(()) => {
                    // Reload signal received, refresh file layers
                    self.reload_file_layers()?;
                    Ok(true)
                }
                Err(mpsc::TryRecvError::Empty) => {
                    // No signals pending
                    Ok(false)
                }
                Err(mpsc::TryRecvError::Disconnected) => {
                    // Channel disconnected, disable auto-reload
                    self.reload_receiver = None;
                    self.auto_reload_registered = false;
                    Ok(false)
                }
            }
        } else {
            Ok(false)
        }
    }

    /// Reloads all file-based configuration layers.
    /// This method refreshes the content of all FileConfigLayer instances
    /// while preserving their position in the layer hierarchy.
    ///
    /// # Returns
    /// * `ConfigResult<()>` - Success if all layers were reloaded, or an error
    ///
    /// # Errors
    /// * `ConfigError::Io` - If any configuration file cannot be read
    /// * `ConfigError::Parse` - If any configuration file cannot be parsed
    fn reload_file_layers(&mut self) -> ConfigResult<()> {
        let mut reload_errors = Vec::new();

        // Reload each file layer
        for layer in &mut self.layers {
            if let Some(file_layer) = layer.as_any_mut().downcast_mut::<FileConfigLayer>() {
                if let Err(e) = file_layer.reload() {
                    // Collect errors but continue trying to reload other layers
                    reload_errors.push((file_layer.file_path().to_string_lossy().to_string(), e));
                }
            }
        }

        // If there were any errors, report the first one
        // In a production system, you might want to handle this differently
        if let Some((file_path, error)) = reload_errors.first() {
            return Err(ConfigError::FileWatch(format!(
                "Failed to reload configuration file '{file_path}': {error}"
            )));
        }

        Ok(())
    }
}

/// Explicit configuration layer for values set directly via set() method.
struct ExplicitConfigLayer {
    data: std::collections::HashMap<String, ConfigValue>,
}

impl ExplicitConfigLayer {
    fn new() -> Self {
        Self {
            data: std::collections::HashMap::new(),
        }
    }
}

impl ConfigLayer for ExplicitConfigLayer {
    fn get(&self, key: &str) -> ConfigResult<Option<ConfigValue>> {
        Ok(self.data.get(key).cloned())
    }

    fn set(&mut self, key: &str, value: ConfigValue) -> ConfigResult<()> {
        self.data.insert(key.to_string(), value);
        Ok(())
    }

    fn keys(&self) -> Vec<String> {
        self.data.keys().cloned().collect()
    }

    fn source_name(&self) -> &str {
        "explicit"
    }

    fn priority(&self) -> LayerPriority {
        LayerPriority::Explicit
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Sub-configuration layer for focused access to a configuration subsection.
struct SubConfigLayer {
    data: std::collections::HashMap<String, ConfigValue>,
    source_key: String,
}

impl SubConfigLayer {
    fn new(source_key: &str, obj: std::collections::HashMap<String, ConfigValue>) -> Self {
        Self {
            data: obj,
            source_key: source_key.to_string(),
        }
    }
}

impl ConfigLayer for SubConfigLayer {
    fn get(&self, key: &str) -> ConfigResult<Option<ConfigValue>> {
        Ok(self.data.get(key).cloned())
    }

    fn set(&mut self, key: &str, value: ConfigValue) -> ConfigResult<()> {
        self.data.insert(key.to_string(), value);
        Ok(())
    }

    fn keys(&self) -> Vec<String> {
        self.data.keys().cloned().collect()
    }

    fn source_name(&self) -> &str {
        &self.source_key
    }

    fn priority(&self) -> LayerPriority {
        LayerPriority::Explicit
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

impl Default for Spice {
    fn default() -> Self {
        Self::new()
    }
}

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

    // Mock implementation for testing
    struct MockConfigLayer {
        data: HashMap<String, ConfigValue>,
        priority: LayerPriority,
        name: String,
    }

    impl MockConfigLayer {
        fn new(name: &str, priority: LayerPriority) -> Self {
            Self {
                data: HashMap::new(),
                priority,
                name: name.to_string(),
            }
        }

        fn with_value(mut self, key: &str, value: ConfigValue) -> Self {
            self.data.insert(key.to_string(), value);
            self
        }
    }

    impl ConfigLayer for MockConfigLayer {
        fn get(&self, key: &str) -> ConfigResult<Option<ConfigValue>> {
            Ok(self.data.get(key).cloned())
        }

        fn set(&mut self, key: &str, value: ConfigValue) -> ConfigResult<()> {
            self.data.insert(key.to_string(), value);
            Ok(())
        }

        fn keys(&self) -> Vec<String> {
            self.data.keys().cloned().collect()
        }

        fn source_name(&self) -> &str {
            &self.name
        }

        fn priority(&self) -> LayerPriority {
            self.priority
        }

        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }
    }

    #[test]
    fn test_new_viper() {
        let spice = Spice::new();
        assert_eq!(spice.layers.len(), 0);
        assert_eq!(spice.config_paths.len(), 0);
        assert_eq!(spice.key_delimiter, ".");
        assert!(!spice.automatic_env);
        assert_eq!(spice.config_name, "");
        assert!(spice.env_prefix.is_none());
    }

    #[test]
    fn test_default_viper() {
        let spice = Spice::default();
        assert_eq!(spice.layers.len(), 0);
        assert_eq!(spice.key_delimiter, ".");
    }

    #[test]
    fn test_add_layer() {
        let mut spice = Spice::new();
        assert_eq!(spice.layer_count(), 0);

        // Add a layer
        let layer = Box::new(MockConfigLayer::new("test", LayerPriority::ConfigFile));
        spice.add_layer(layer);
        assert_eq!(spice.layer_count(), 1);

        // Add another layer with higher priority
        let layer = Box::new(MockConfigLayer::new("env", LayerPriority::Environment));
        spice.add_layer(layer);
        assert_eq!(spice.layer_count(), 2);

        // Verify layers are sorted by priority
        let layer_info = spice.layer_info();
        assert_eq!(layer_info[0].1, LayerPriority::Environment); // Higher priority first
        assert_eq!(layer_info[1].1, LayerPriority::ConfigFile);
    }

    #[test]
    fn test_remove_layers_by_priority() {
        let mut spice = Spice::new();

        // Add multiple layers
        spice.add_layer(Box::new(MockConfigLayer::new(
            "config1",
            LayerPriority::ConfigFile,
        )));
        spice.add_layer(Box::new(MockConfigLayer::new(
            "config2",
            LayerPriority::ConfigFile,
        )));
        spice.add_layer(Box::new(MockConfigLayer::new(
            "env",
            LayerPriority::Environment,
        )));
        assert_eq!(spice.layer_count(), 3);

        // Remove config file layers
        let removed = spice.remove_layers_by_priority(LayerPriority::ConfigFile);
        assert_eq!(removed, 2);
        assert_eq!(spice.layer_count(), 1);

        // Verify only environment layer remains
        let layer_info = spice.layer_info();
        assert_eq!(layer_info.len(), 1);
        assert_eq!(layer_info[0].1, LayerPriority::Environment);
    }

    #[test]
    fn test_clear_layers() {
        let mut spice = Spice::new();
        spice.add_layer(Box::new(MockConfigLayer::new(
            "test",
            LayerPriority::ConfigFile,
        )));
        assert_eq!(spice.layer_count(), 1);

        spice.clear_layers();
        assert_eq!(spice.layer_count(), 0);
    }

    #[test]
    fn test_layer_info() {
        let mut spice = Spice::new();
        spice.add_layer(Box::new(MockConfigLayer::new(
            "config",
            LayerPriority::ConfigFile,
        )));
        spice.add_layer(Box::new(MockConfigLayer::new(
            "env",
            LayerPriority::Environment,
        )));

        let layer_info = spice.layer_info();
        assert_eq!(layer_info.len(), 2);

        // Should be sorted by priority
        assert_eq!(layer_info[0].0, "env");
        assert_eq!(layer_info[0].1, LayerPriority::Environment);
        assert_eq!(layer_info[1].0, "config");
        assert_eq!(layer_info[1].1, LayerPriority::ConfigFile);
    }

    #[test]
    fn test_config_name() {
        let mut spice = Spice::new();
        assert_eq!(spice.config_name(), "");

        spice.set_config_name("myapp");
        assert_eq!(spice.config_name(), "myapp");

        spice.set_config_name("another_name".to_string());
        assert_eq!(spice.config_name(), "another_name");
    }

    #[test]
    fn test_config_paths() {
        let mut spice = Spice::new();
        assert_eq!(spice.config_paths().len(), 0);

        spice.add_config_path("/etc/myapp");
        spice.add_config_path(PathBuf::from("/home/user/.config"));
        assert_eq!(spice.config_paths().len(), 2);
        assert_eq!(spice.config_paths()[0], PathBuf::from("/etc/myapp"));
        assert_eq!(spice.config_paths()[1], PathBuf::from("/home/user/.config"));
    }

    #[test]
    fn test_env_prefix() {
        let mut spice = Spice::new();
        assert!(spice.env_prefix().is_none());

        spice.set_env_prefix("MYAPP");
        assert_eq!(spice.env_prefix(), Some("MYAPP"));

        spice.set_env_prefix("ANOTHER".to_string());
        assert_eq!(spice.env_prefix(), Some("ANOTHER"));
    }

    #[test]
    fn test_automatic_env() {
        let mut spice = Spice::new();
        assert!(!spice.is_automatic_env());

        spice.set_automatic_env(true);
        assert!(spice.is_automatic_env());

        spice.set_automatic_env(false);
        assert!(!spice.is_automatic_env());
    }

    #[test]
    fn test_key_delimiter() {
        let mut spice = Spice::new();
        assert_eq!(spice.key_delimiter(), ".");

        spice.set_key_delimiter("_");
        assert_eq!(spice.key_delimiter(), "_");

        spice.set_key_delimiter("::".to_string());
        assert_eq!(spice.key_delimiter(), "::");
    }

    #[test]
    fn test_set_and_get() {
        let mut spice = Spice::new();

        // Test setting and getting a string value
        spice
            .set("test.key", ConfigValue::String("test_value".to_string()))
            .unwrap();
        let value = spice.get("test.key").unwrap();
        assert_eq!(value, Some(ConfigValue::String("test_value".to_string())));

        // Test getting non-existent key
        let value = spice.get("nonexistent.key").unwrap();
        assert_eq!(value, None);
    }

    #[test]
    fn test_explicit_layer_creation() {
        let mut spice = Spice::new();
        assert_eq!(spice.layer_count(), 0);

        // Setting a value should create an explicit layer
        spice
            .set("key1", ConfigValue::String("value1".to_string()))
            .unwrap();
        assert_eq!(spice.layer_count(), 1);

        // Setting another value should reuse the explicit layer
        spice
            .set("key2", ConfigValue::String("value2".to_string()))
            .unwrap();
        assert_eq!(spice.layer_count(), 1);

        // Verify the layer has explicit priority
        let layer_info = spice.layer_info();
        assert_eq!(layer_info[0].1, LayerPriority::Explicit);
    }

    #[test]
    fn test_precedence_with_set() {
        let mut spice = Spice::new();

        // Add a lower priority layer
        let layer = Box::new(
            MockConfigLayer::new("config", LayerPriority::ConfigFile).with_value(
                "shared_key",
                ConfigValue::String("config_value".to_string()),
            ),
        );
        spice.add_layer(layer);

        // Explicit set should override
        spice
            .set(
                "shared_key",
                ConfigValue::String("explicit_value".to_string()),
            )
            .unwrap();

        let value = spice.get("shared_key").unwrap();
        assert_eq!(
            value,
            Some(ConfigValue::String("explicit_value".to_string()))
        );
    }

    #[test]
    fn test_unmarshal_full_config() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct TestConfig {
            name: String,
            port: u16,
            debug: bool,
        }

        let mut spice = Spice::new();
        spice.set("name", ConfigValue::from("test_app")).unwrap();
        spice.set("port", ConfigValue::from(8080i64)).unwrap();
        spice.set("debug", ConfigValue::from(true)).unwrap();

        let config: TestConfig = spice.unmarshal().unwrap();
        assert_eq!(config.name, "test_app");
        assert_eq!(config.port, 8080);
        assert_eq!(config.debug, true);
    }

    #[test]
    fn test_unmarshal_nested_config() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct DatabaseConfig {
            host: String,
            port: u16,
        }

        #[derive(Deserialize, Debug, PartialEq)]
        struct AppConfig {
            database: DatabaseConfig,
            debug: bool,
        }

        let mut spice = Spice::new();

        // Set up nested database configuration
        let mut db_config = HashMap::new();
        db_config.insert("host".to_string(), ConfigValue::from("localhost"));
        db_config.insert("port".to_string(), ConfigValue::from(5432i64));
        spice
            .set("database", ConfigValue::Object(db_config))
            .unwrap();
        spice.set("debug", ConfigValue::from(false)).unwrap();

        let config: AppConfig = spice.unmarshal().unwrap();
        assert_eq!(config.database.host, "localhost");
        assert_eq!(config.database.port, 5432);
        assert_eq!(config.debug, false);
    }

    #[test]
    fn test_unmarshal_with_defaults() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct ConfigWithDefaults {
            name: String,
            #[serde(default)]
            port: u16,
            #[serde(default = "default_debug")]
            debug: bool,
        }

        fn default_debug() -> bool {
            true
        }

        let mut spice = Spice::new();
        spice.set("name", ConfigValue::from("test_app")).unwrap();
        // Note: port and debug are not set, should use defaults

        let config: ConfigWithDefaults = spice.unmarshal().unwrap();
        assert_eq!(config.name, "test_app");
        assert_eq!(config.port, 0); // Default for u16
        assert_eq!(config.debug, true); // Custom default
    }

    #[test]
    fn test_unmarshal_key_specific() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct DatabaseConfig {
            host: String,
            port: u16,
            #[serde(default)]
            ssl: bool,
        }

        let mut spice = Spice::new();

        // Set up database configuration
        let mut db_config = HashMap::new();
        db_config.insert("host".to_string(), ConfigValue::from("localhost"));
        db_config.insert("port".to_string(), ConfigValue::from(5432i64));
        spice
            .set("database", ConfigValue::Object(db_config))
            .unwrap();
        spice
            .set("other_key", ConfigValue::from("other_value"))
            .unwrap();

        // Unmarshal only the database section
        let db_config: DatabaseConfig = spice.unmarshal_key("database").unwrap();
        assert_eq!(db_config.host, "localhost");
        assert_eq!(db_config.port, 5432);
        assert_eq!(db_config.ssl, false); // Default value
    }

    #[test]
    fn test_unmarshal_key_missing() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct TestConfig {
            name: String,
        }

        let spice = Spice::new();

        // Try to unmarshal a key that doesn't exist
        let result: Result<TestConfig, _> = spice.unmarshal_key("nonexistent");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_key_not_found());
    }

    #[test]
    fn test_unmarshal_type_mismatch() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct TestConfig {
            port: u16,
        }

        let mut spice = Spice::new();
        // Set port as a string instead of number
        spice
            .set("port", ConfigValue::from("not_a_number"))
            .unwrap();

        // This should fail during deserialization
        let result: Result<TestConfig, _> = spice.unmarshal();
        assert!(result.is_err());
    }

    #[test]
    fn test_unmarshal_with_field_renaming() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct TestConfig {
            #[serde(rename = "app_name")]
            name: String,
            #[serde(rename = "server_port")]
            port: u16,
        }

        let mut spice = Spice::new();
        spice.set("app_name", ConfigValue::from("my_app")).unwrap();
        spice
            .set("server_port", ConfigValue::from(3000i64))
            .unwrap();

        let config: TestConfig = spice.unmarshal().unwrap();
        assert_eq!(config.name, "my_app");
        assert_eq!(config.port, 3000);
    }

    #[test]
    fn test_unmarshal_array_config() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct ServerConfig {
            host: String,
            port: u16,
        }

        #[derive(Deserialize, Debug, PartialEq)]
        struct AppConfig {
            servers: Vec<ServerConfig>,
        }

        let mut spice = Spice::new();

        // Create array of server configurations
        let servers = vec![
            ConfigValue::Object({
                let mut server1 = HashMap::new();
                server1.insert("host".to_string(), ConfigValue::from("server1.com"));
                server1.insert("port".to_string(), ConfigValue::from(8080i64));
                server1
            }),
            ConfigValue::Object({
                let mut server2 = HashMap::new();
                server2.insert("host".to_string(), ConfigValue::from("server2.com"));
                server2.insert("port".to_string(), ConfigValue::from(8081i64));
                server2
            }),
        ];

        spice.set("servers", ConfigValue::Array(servers)).unwrap();

        let config: AppConfig = spice.unmarshal().unwrap();
        assert_eq!(config.servers.len(), 2);
        assert_eq!(config.servers[0].host, "server1.com");
        assert_eq!(config.servers[0].port, 8080);
        assert_eq!(config.servers[1].host, "server2.com");
        assert_eq!(config.servers[1].port, 8081);
    }

    #[test]
    fn test_unmarshal_with_validation_success() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct ServerConfig {
            host: String,
            port: u16,
        }

        impl ServerConfig {
            fn validate(&self) -> Result<(), String> {
                if self.port == 0 {
                    return Err("Port cannot be zero".to_string());
                }
                if self.host.is_empty() {
                    return Err("Host cannot be empty".to_string());
                }
                Ok(())
            }
        }

        let mut spice = Spice::new();
        spice.set("host", ConfigValue::from("localhost")).unwrap();
        spice.set("port", ConfigValue::from(8080i64)).unwrap();

        let config: ServerConfig = spice
            .unmarshal_with_validation(|config: &ServerConfig| {
                config.validate().map_err(|e| ConfigError::invalid_value(e))
            })
            .unwrap();

        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 8080);
    }

    #[test]
    fn test_unmarshal_with_validation_failure() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct ServerConfig {
            host: String,
            port: u16,
        }

        impl ServerConfig {
            fn validate(&self) -> Result<(), String> {
                if self.port == 0 {
                    return Err("Port cannot be zero".to_string());
                }
                if self.host.is_empty() {
                    return Err("Host cannot be empty".to_string());
                }
                Ok(())
            }
        }

        let mut spice = Spice::new();
        spice.set("host", ConfigValue::from("")).unwrap(); // Invalid empty host
        spice.set("port", ConfigValue::from(8080i64)).unwrap();

        let result: Result<ServerConfig, _> =
            spice.unmarshal_with_validation(|config: &ServerConfig| {
                config.validate().map_err(|e| ConfigError::invalid_value(e))
            });

        assert!(result.is_err());
        if let Err(ConfigError::InvalidValue(msg)) = result {
            assert_eq!(msg, "Host cannot be empty");
        } else {
            panic!("Expected InvalidValue error");
        }
    }

    #[test]
    fn test_unmarshal_key_with_validation_success() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct DatabaseConfig {
            host: String,
            port: u16,
        }

        impl DatabaseConfig {
            fn validate(&self) -> Result<(), String> {
                if self.port < 1024 {
                    return Err("Port should be >= 1024 for non-privileged access".to_string());
                }
                Ok(())
            }
        }

        let mut spice = Spice::new();
        let mut db_config = HashMap::new();
        db_config.insert("host".to_string(), ConfigValue::from("localhost"));
        db_config.insert("port".to_string(), ConfigValue::from(5432i64));
        spice
            .set("database", ConfigValue::Object(db_config))
            .unwrap();

        let config: DatabaseConfig = spice
            .unmarshal_key_with_validation("database", |config: &DatabaseConfig| {
                config.validate().map_err(|e| ConfigError::invalid_value(e))
            })
            .unwrap();

        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 5432);
    }

    #[test]
    fn test_unmarshal_key_with_validation_failure() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct DatabaseConfig {
            host: String,
            port: u16,
        }

        impl DatabaseConfig {
            fn validate(&self) -> Result<(), String> {
                if self.port < 1024 {
                    return Err("Port should be >= 1024 for non-privileged access".to_string());
                }
                Ok(())
            }
        }

        let mut spice = Spice::new();
        let mut db_config = HashMap::new();
        db_config.insert("host".to_string(), ConfigValue::from("localhost"));
        db_config.insert("port".to_string(), ConfigValue::from(80i64)); // Invalid low port
        spice
            .set("database", ConfigValue::Object(db_config))
            .unwrap();

        let result: Result<DatabaseConfig, _> = spice
            .unmarshal_key_with_validation("database", |config: &DatabaseConfig| {
                config.validate().map_err(|e| ConfigError::invalid_value(e))
            });

        assert!(result.is_err());
        if let Err(ConfigError::InvalidValue(msg)) = result {
            assert_eq!(msg, "Port should be >= 1024 for non-privileged access");
        } else {
            panic!("Expected InvalidValue error");
        }
    }

    #[test]
    fn test_get_string() {
        let mut spice = Spice::new();

        // Test string value
        spice
            .set("string_key", ConfigValue::String("hello".to_string()))
            .unwrap();
        let value = spice.get_string("string_key").unwrap();
        assert_eq!(value, Some("hello".to_string()));

        // Test integer coercion to string
        spice.set("int_key", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_string("int_key").unwrap();
        assert_eq!(value, Some("42".to_string()));

        // Test boolean coercion to string
        spice.set("bool_key", ConfigValue::Boolean(true)).unwrap();
        let value = spice.get_string("bool_key").unwrap();
        assert_eq!(value, Some("true".to_string()));

        // Test non-existent key
        let value = spice.get_string("nonexistent").unwrap();
        assert_eq!(value, None);
    }

    #[test]
    fn test_get_int() {
        let mut spice = Spice::new();

        // Test integer value
        spice.set("int_key", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_int("int_key").unwrap();
        assert_eq!(value, Some(42));

        // Test string value (should fail)
        spice
            .set("string_key", ConfigValue::String("hello".to_string()))
            .unwrap();
        let result = spice.get_int("string_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());

        // Test non-existent key
        let value = spice.get_int("nonexistent").unwrap();
        assert_eq!(value, None);
    }

    #[test]
    fn test_get_i64() {
        let mut spice = Spice::new();
        spice.set("key", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_i64("key").unwrap();
        assert_eq!(value, Some(42));
    }

    #[test]
    fn test_get_i32() {
        let mut spice = Spice::new();

        // Test valid i32 range
        spice.set("valid_key", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_i32("valid_key").unwrap();
        assert_eq!(value, Some(42));

        // Test i32 overflow
        spice
            .set("overflow_key", ConfigValue::Integer(i64::MAX))
            .unwrap();
        let result = spice.get_i32("overflow_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_get_float() {
        let mut spice = Spice::new();

        // Test float value
        spice.set("float_key", ConfigValue::Float(3.14)).unwrap();
        let value = spice.get_float("float_key").unwrap();
        assert_eq!(value, Some(3.14));

        // Test integer to float conversion
        spice.set("int_key", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_float("int_key").unwrap();
        assert_eq!(value, Some(42.0));

        // Test string value (should fail)
        spice
            .set("string_key", ConfigValue::String("hello".to_string()))
            .unwrap();
        let result = spice.get_float("string_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_get_f64() {
        let mut spice = Spice::new();
        spice.set("key", ConfigValue::Float(3.14)).unwrap();
        let value = spice.get_f64("key").unwrap();
        assert_eq!(value, Some(3.14));
    }

    #[test]
    fn test_get_f32() {
        let mut spice = Spice::new();

        // Test valid f32 range
        spice.set("valid_key", ConfigValue::Float(3.14)).unwrap();
        let value = spice.get_f32("valid_key").unwrap();
        assert!((value.unwrap() - 3.14f32).abs() < f32::EPSILON);

        // Test f32 overflow (f64::MAX should fail)
        spice
            .set("overflow_key", ConfigValue::Float(f64::MAX))
            .unwrap();
        let result = spice.get_f32("overflow_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_get_bool() {
        let mut spice = Spice::new();

        // Test boolean value
        spice.set("bool_key", ConfigValue::Boolean(true)).unwrap();
        let value = spice.get_bool("bool_key").unwrap();
        assert_eq!(value, Some(true));

        // Test string coercion to boolean
        spice
            .set("string_true", ConfigValue::String("true".to_string()))
            .unwrap();
        let value = spice.get_bool("string_true").unwrap();
        assert_eq!(value, Some(true));

        spice
            .set("string_false", ConfigValue::String("false".to_string()))
            .unwrap();
        let value = spice.get_bool("string_false").unwrap();
        assert_eq!(value, Some(false));

        // Test integer coercion to boolean
        spice.set("int_zero", ConfigValue::Integer(0)).unwrap();
        let value = spice.get_bool("int_zero").unwrap();
        assert_eq!(value, Some(false));

        spice.set("int_nonzero", ConfigValue::Integer(42)).unwrap();
        let value = spice.get_bool("int_nonzero").unwrap();
        assert_eq!(value, Some(true));

        // Test invalid string (should fail)
        spice
            .set("invalid_string", ConfigValue::String("maybe".to_string()))
            .unwrap();
        let result = spice.get_bool("invalid_string");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_get_array() {
        let mut spice = Spice::new();

        // Test array value
        let array = vec![
            ConfigValue::String("item1".to_string()),
            ConfigValue::Integer(42),
        ];
        spice
            .set("array_key", ConfigValue::Array(array.clone()))
            .unwrap();
        let value = spice.get_array("array_key").unwrap();
        assert_eq!(value, Some(array));

        // Test non-array value (should fail)
        spice
            .set("string_key", ConfigValue::String("hello".to_string()))
            .unwrap();
        let result = spice.get_array("string_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_get_object() {
        let mut spice = Spice::new();

        // Test object value
        let mut object = std::collections::HashMap::new();
        object.insert(
            "key1".to_string(),
            ConfigValue::String("value1".to_string()),
        );
        object.insert("key2".to_string(), ConfigValue::Integer(42));
        spice
            .set("object_key", ConfigValue::Object(object.clone()))
            .unwrap();
        let value = spice.get_object("object_key").unwrap();
        assert_eq!(value, Some(object));

        // Test non-object value (should fail)
        spice
            .set("string_key", ConfigValue::String("hello".to_string()))
            .unwrap();
        let result = spice.get_object("string_key");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_type_conversion());
    }

    #[test]
    fn test_is_set() {
        let mut spice = Spice::new();

        // Test non-existent key
        assert!(!spice.is_set("nonexistent"));

        // Test existing key
        spice
            .set("existing_key", ConfigValue::String("value".to_string()))
            .unwrap();
        assert!(spice.is_set("existing_key"));

        // Test null value (should still be considered set)
        spice.set("null_key", ConfigValue::Null).unwrap();
        assert!(spice.is_set("null_key"));
    }

    #[test]
    fn test_all_keys() {
        let mut spice = Spice::new();

        // Initially no keys
        assert_eq!(spice.all_keys().len(), 0);

        // Add some keys
        spice
            .set("key1", ConfigValue::String("value1".to_string()))
            .unwrap();
        spice.set("key2", ConfigValue::Integer(42)).unwrap();

        let keys = spice.all_keys();
        assert!(keys.contains(&"key1".to_string()));
        assert!(keys.contains(&"key2".to_string()));
    }

    #[test]
    fn test_all_settings() {
        let mut spice = Spice::new();

        // Add some configuration values
        spice
            .set("app.name", ConfigValue::String("test_app".to_string()))
            .unwrap();
        spice.set("app.port", ConfigValue::Integer(8080)).unwrap();
        spice.set("debug", ConfigValue::Boolean(true)).unwrap();

        let settings = spice.all_settings().unwrap();
        // Enhanced all_settings expands nested keys, so we have 2 top-level keys: "app" and "debug"
        assert_eq!(settings.len(), 2);

        // Check the nested app structure
        if let Some(ConfigValue::Object(app_obj)) = settings.get("app") {
            assert_eq!(
                app_obj.get("name"),
                Some(&ConfigValue::String("test_app".to_string()))
            );
            assert_eq!(app_obj.get("port"), Some(&ConfigValue::Integer(8080)));
        } else {
            panic!("Expected app to be an object");
        }

        assert_eq!(settings.get("debug"), Some(&ConfigValue::Boolean(true)));
    }

    #[test]
    fn test_write_config_json() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.json");

        let mut spice = Spice::new();
        spice
            .set("app.name", ConfigValue::String("test_app".to_string()))
            .unwrap();
        spice.set("app.port", ConfigValue::Integer(8080)).unwrap();
        spice.set("debug", ConfigValue::Boolean(true)).unwrap();

        // Write configuration to JSON file
        spice.write_config(&config_path).unwrap();

        // Verify file was created and contains expected content
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("test_app"));
        assert!(content.contains("8080"));
        assert!(content.contains("true"));

        // Verify we can parse it back
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        // Enhanced serialization expands nested keys
        assert_eq!(parsed["app"]["name"], "test_app");
        assert_eq!(parsed["app"]["port"], 8080);
        assert_eq!(parsed["debug"], true);
    }

    #[test]
    fn test_write_config_yaml() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.yaml");

        let mut spice = Spice::new();
        spice
            .set(
                "database.host",
                ConfigValue::String("localhost".to_string()),
            )
            .unwrap();
        spice
            .set("database.port", ConfigValue::Integer(5432))
            .unwrap();
        spice
            .set("database.ssl", ConfigValue::Boolean(false))
            .unwrap();

        // Write configuration to YAML file
        spice.write_config(&config_path).unwrap();

        // Verify file was created and contains expected content
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("localhost"));
        assert!(content.contains("5432"));
        assert!(content.contains("false"));

        // Verify we can parse it back
        let parsed: serde_yaml::Value = serde_yaml::from_str(&content).unwrap();
        assert_eq!(parsed["database"]["host"], "localhost");
        assert_eq!(parsed["database"]["port"], 5432);
        assert_eq!(parsed["database"]["ssl"], false);
    }

    #[test]
    fn test_write_config_toml() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.toml");

        let mut spice = Spice::new();
        spice
            .set("server.host", ConfigValue::String("0.0.0.0".to_string()))
            .unwrap();
        spice
            .set("server.port", ConfigValue::Integer(3000))
            .unwrap();
        spice
            .set("server.timeout", ConfigValue::Float(30.5))
            .unwrap();

        // Write configuration to TOML file
        spice.write_config(&config_path).unwrap();

        // Verify file was created and contains expected content
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("0.0.0.0"));
        assert!(content.contains("3000"));
        assert!(content.contains("30.5"));

        // Verify we can parse it back
        let parsed: toml::Value = toml::from_str(&content).unwrap();
        assert_eq!(
            parsed["server"]["host"],
            toml::Value::String("0.0.0.0".to_string())
        );
        assert_eq!(parsed["server"]["port"], toml::Value::Integer(3000));
        assert_eq!(parsed["server"]["timeout"], toml::Value::Float(30.5));
    }

    #[test]
    fn test_write_config_ini() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.ini");

        let mut spice = Spice::new();
        spice
            .set(
                "global_setting",
                ConfigValue::String("global_value".to_string()),
            )
            .unwrap();

        // Create a section with nested values
        let mut section_data = std::collections::HashMap::new();
        section_data.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        section_data.insert("port".to_string(), ConfigValue::Integer(3306));
        section_data.insert("enabled".to_string(), ConfigValue::Boolean(true));
        spice
            .set("database", ConfigValue::Object(section_data))
            .unwrap();

        // Write configuration to INI file
        spice.write_config(&config_path).unwrap();

        // Verify file was created and contains expected content
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("global_setting = global_value"));
        assert!(content.contains("[database]"));
        assert!(content.contains("host = localhost"));
        assert!(content.contains("port = 3306"));
        assert!(content.contains("enabled = true"));
    }

    #[test]
    fn test_write_config_as_format_override() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.txt"); // .txt extension

        let mut spice = Spice::new();
        spice
            .set("app.name", ConfigValue::String("test_app".to_string()))
            .unwrap();
        spice
            .set("app.version", ConfigValue::String("1.0.0".to_string()))
            .unwrap();

        // Write as YAML despite .txt extension
        spice.write_config_as(&config_path, "yaml").unwrap();

        // Verify file was created and contains YAML content
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Should be valid YAML
        let parsed: serde_yaml::Value = serde_yaml::from_str(&content).unwrap();
        assert_eq!(parsed["app"]["name"], "test_app");
        assert_eq!(parsed["app"]["version"], "1.0.0");
    }

    #[test]
    fn test_safe_write_config_new_file() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("safe_config.json");

        let mut spice = Spice::new();
        spice.set("safe", ConfigValue::Boolean(true)).unwrap();

        // Should succeed for new file
        spice.safe_write_config(&config_path).unwrap();

        // Verify file was created
        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("true"));
    }

    #[test]
    fn test_safe_write_config_existing_file() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("existing_config.json");

        // Create existing file
        fs::write(&config_path, "existing content").unwrap();

        let mut spice = Spice::new();
        spice.set("safe", ConfigValue::Boolean(true)).unwrap();

        // Should fail for existing file
        let result = spice.safe_write_config(&config_path);
        assert!(result.is_err());
        assert!(result.unwrap_err().is_io_error());

        // Original file should be unchanged
        let content = fs::read_to_string(&config_path).unwrap();
        assert_eq!(content, "existing content");
    }

    #[test]
    fn test_write_config_unsupported_format() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.unknown");

        let mut spice = Spice::new();
        spice
            .set("test", ConfigValue::String("value".to_string()))
            .unwrap();

        // Should fail for unsupported format
        let result = spice.write_config(&config_path);
        assert!(result.is_err());
        // Enhanced error handling now returns Serialization error with context
        assert!(matches!(result.unwrap_err(), ConfigError::Serialization(_)));
    }

    #[test]
    fn test_write_config_as_unsupported_format() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.txt");

        let mut spice = Spice::new();
        spice
            .set("test", ConfigValue::String("value".to_string()))
            .unwrap();

        // Should fail for unsupported format
        let result = spice.write_config_as(&config_path, "unknown");
        assert!(result.is_err());
        // Enhanced error handling now returns Serialization error with context
        assert!(matches!(result.unwrap_err(), ConfigError::Serialization(_)));
    }

    #[test]
    fn test_write_config_complex_nested_structure() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("complex_config.json");

        let mut spice = Spice::new();

        // Create complex nested structure
        let mut database_config = std::collections::HashMap::new();
        database_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        database_config.insert("port".to_string(), ConfigValue::Integer(5432));

        let mut credentials = std::collections::HashMap::new();
        credentials.insert(
            "username".to_string(),
            ConfigValue::String("admin".to_string()),
        );
        credentials.insert(
            "password".to_string(),
            ConfigValue::String("secret".to_string()),
        );
        database_config.insert("credentials".to_string(), ConfigValue::Object(credentials));

        spice
            .set("database", ConfigValue::Object(database_config))
            .unwrap();

        // Create array of servers
        let servers = vec![
            ConfigValue::Object({
                let mut server = std::collections::HashMap::new();
                server.insert("name".to_string(), ConfigValue::String("web1".to_string()));
                server.insert("port".to_string(), ConfigValue::Integer(8080));
                server
            }),
            ConfigValue::Object({
                let mut server = std::collections::HashMap::new();
                server.insert("name".to_string(), ConfigValue::String("web2".to_string()));
                server.insert("port".to_string(), ConfigValue::Integer(8081));
                server
            }),
        ];
        spice.set("servers", ConfigValue::Array(servers)).unwrap();

        // Write and verify
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify structure
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["database"]["host"], "localhost");
        assert_eq!(parsed["database"]["credentials"]["username"], "admin");
        assert_eq!(parsed["servers"][0]["name"], "web1");
        assert_eq!(parsed["servers"][1]["port"], 8081);
    }

    #[test]
    fn test_write_config_with_layer_precedence() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("precedence_config.json");

        let mut spice = Spice::new();

        // Add default layer
        spice
            .set_default(
                "shared_key",
                ConfigValue::String("default_value".to_string()),
            )
            .unwrap();
        spice
            .set_default("default_only", ConfigValue::String("default".to_string()))
            .unwrap();

        // Add explicit layer (higher precedence)
        spice
            .set(
                "shared_key",
                ConfigValue::String("explicit_value".to_string()),
            )
            .unwrap();
        spice
            .set("explicit_only", ConfigValue::String("explicit".to_string()))
            .unwrap();

        // Write configuration
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify precedence is respected
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["shared_key"], "explicit_value"); // Explicit should win
        assert_eq!(parsed["default_only"], "default");
        assert_eq!(parsed["explicit_only"], "explicit");
    }

    #[test]
    fn test_write_config_round_trip() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("round_trip.json");

        let mut original_viper = Spice::new();
        original_viper
            .set(
                "app.name",
                ConfigValue::String("round_trip_test".to_string()),
            )
            .unwrap();
        original_viper
            .set("app.port", ConfigValue::Integer(9000))
            .unwrap();
        original_viper
            .set("app.debug", ConfigValue::Boolean(false))
            .unwrap();
        original_viper
            .set("app.timeout", ConfigValue::Float(45.5))
            .unwrap();

        // Write configuration
        original_viper.write_config(&config_path).unwrap();

        // Load configuration into new Spice instance
        let mut loaded_viper = Spice::new();
        loaded_viper.set_config_file(&config_path).unwrap();

        // Verify all values match
        assert_eq!(
            loaded_viper.get_string("app.name").unwrap(),
            Some("round_trip_test".to_string())
        );
        assert_eq!(loaded_viper.get_i64("app.port").unwrap(), Some(9000));
        assert_eq!(loaded_viper.get_bool("app.debug").unwrap(), Some(false));
        assert_eq!(loaded_viper.get_f64("app.timeout").unwrap(), Some(45.5));
    }

    #[test]
    fn test_write_config_empty_configuration() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("empty_config.json");

        let spice = Spice::new(); // No configuration set

        // Should write empty object
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Should be valid JSON representing empty object
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed.is_object());
        assert_eq!(parsed.as_object().unwrap().len(), 0);
    }

    #[test]
    fn test_write_config_permission_error() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let readonly_dir = temp_dir.path().join("readonly");
        fs::create_dir(&readonly_dir).unwrap();

        // Make directory read-only (Unix-specific test)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&readonly_dir).unwrap().permissions();
            perms.set_mode(0o444); // Read-only
            fs::set_permissions(&readonly_dir, perms).unwrap();

            let config_path = readonly_dir.join("config.json");
            let mut spice = Spice::new();
            spice
                .set("test", ConfigValue::String("value".to_string()))
                .unwrap();

            // Should fail with IO error
            let result = spice.write_config(&config_path);
            assert!(result.is_err());
            assert!(result.unwrap_err().is_io_error());

            // Restore permissions for cleanup
            let mut perms = fs::metadata(&readonly_dir).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&readonly_dir, perms).unwrap();
        }
    }

    #[test]
    fn test_all_keys_with_values() {
        let mut spice = Spice::new();

        // Initially no keys
        assert_eq!(spice.all_keys().len(), 0);

        // Add some keys
        spice
            .set("key1", ConfigValue::String("value1".to_string()))
            .unwrap();
        spice.set("key2", ConfigValue::Integer(42)).unwrap();

        let keys = spice.all_keys();
        assert_eq!(keys.len(), 2);
        assert!(keys.contains(&"key1".to_string()));
        assert!(keys.contains(&"key2".to_string()));
    }

    #[test]
    fn test_nested_key_access_simple() {
        let mut spice = Spice::new();

        // Create nested object structure
        let mut database_config = HashMap::new();
        database_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        database_config.insert("port".to_string(), ConfigValue::Integer(5432));
        spice
            .set("database", ConfigValue::Object(database_config))
            .unwrap();

        // Test nested access
        let host = spice.get("database.host").unwrap();
        assert_eq!(host, Some(ConfigValue::String("localhost".to_string())));

        let port = spice.get("database.port").unwrap();
        assert_eq!(port, Some(ConfigValue::Integer(5432)));

        // Test non-existent nested key
        let nonexistent = spice.get("database.nonexistent").unwrap();
        assert_eq!(nonexistent, None);
    }

    #[test]
    fn test_nested_key_access_deep() {
        let mut spice = Spice::new();

        // Create deeply nested structure
        let mut server_config = HashMap::new();
        server_config.insert(
            "host".to_string(),
            ConfigValue::String("server1".to_string()),
        );
        server_config.insert("port".to_string(), ConfigValue::Integer(8080));

        let mut database_config = HashMap::new();
        database_config.insert("host".to_string(), ConfigValue::String("db1".to_string()));
        database_config.insert("port".to_string(), ConfigValue::Integer(5432));

        let mut app_config = HashMap::new();
        app_config.insert("server".to_string(), ConfigValue::Object(server_config));
        app_config.insert("database".to_string(), ConfigValue::Object(database_config));

        spice.set("app", ConfigValue::Object(app_config)).unwrap();

        // Test deep nested access
        let server_host = spice.get("app.server.host").unwrap();
        assert_eq!(
            server_host,
            Some(ConfigValue::String("server1".to_string()))
        );

        let db_port = spice.get("app.database.port").unwrap();
        assert_eq!(db_port, Some(ConfigValue::Integer(5432)));
    }

    #[test]
    fn test_array_index_access() {
        let mut spice = Spice::new();

        // Create array structure
        let servers = vec![
            ConfigValue::String("server1.example.com".to_string()),
            ConfigValue::String("server2.example.com".to_string()),
            ConfigValue::String("server3.example.com".to_string()),
        ];
        spice.set("servers", ConfigValue::Array(servers)).unwrap();

        // Test array index access
        let server0 = spice.get("servers.0").unwrap();
        assert_eq!(
            server0,
            Some(ConfigValue::String("server1.example.com".to_string()))
        );

        let server1 = spice.get("servers.1").unwrap();
        assert_eq!(
            server1,
            Some(ConfigValue::String("server2.example.com".to_string()))
        );

        let server2 = spice.get("servers.2").unwrap();
        assert_eq!(
            server2,
            Some(ConfigValue::String("server3.example.com".to_string()))
        );

        // Test out of bounds access
        let server_oob = spice.get("servers.10").unwrap();
        assert_eq!(server_oob, None);
    }

    #[test]
    fn test_mixed_nested_and_array_access() {
        let mut spice = Spice::new();

        // Create mixed structure with objects and arrays
        let mut server1 = HashMap::new();
        server1.insert(
            "host".to_string(),
            ConfigValue::String("server1.example.com".to_string()),
        );
        server1.insert("port".to_string(), ConfigValue::Integer(8080));

        let mut server2 = HashMap::new();
        server2.insert(
            "host".to_string(),
            ConfigValue::String("server2.example.com".to_string()),
        );
        server2.insert("port".to_string(), ConfigValue::Integer(8081));

        let servers = vec![ConfigValue::Object(server1), ConfigValue::Object(server2)];

        let mut config = HashMap::new();
        config.insert("servers".to_string(), ConfigValue::Array(servers));
        spice.set("app", ConfigValue::Object(config)).unwrap();

        // Test mixed access
        let server0_host = spice.get("app.servers.0.host").unwrap();
        assert_eq!(
            server0_host,
            Some(ConfigValue::String("server1.example.com".to_string()))
        );

        let server1_port = spice.get("app.servers.1.port").unwrap();
        assert_eq!(server1_port, Some(ConfigValue::Integer(8081)));

        // Test non-existent path
        let nonexistent = spice.get("app.servers.0.nonexistent").unwrap();
        assert_eq!(nonexistent, None);
    }

    #[test]
    fn test_nested_access_with_exact_key_priority() {
        let mut spice = Spice::new();

        // Set both an exact key and a nested structure
        spice
            .set(
                "database.host",
                ConfigValue::String("exact_key_value".to_string()),
            )
            .unwrap();

        let mut database_config = HashMap::new();
        database_config.insert(
            "host".to_string(),
            ConfigValue::String("nested_value".to_string()),
        );
        spice
            .set("database", ConfigValue::Object(database_config))
            .unwrap();

        // Exact key should take precedence over nested access
        let host = spice.get("database.host").unwrap();
        assert_eq!(
            host,
            Some(ConfigValue::String("exact_key_value".to_string()))
        );
    }

    #[test]
    fn test_sub_configuration() {
        let mut spice = Spice::new();

        // Create nested configuration
        let mut database_config = HashMap::new();
        database_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        database_config.insert("port".to_string(), ConfigValue::Integer(5432));
        database_config.insert(
            "username".to_string(),
            ConfigValue::String("admin".to_string()),
        );
        spice
            .set("database", ConfigValue::Object(database_config))
            .unwrap();

        // Create sub-configuration
        let sub_viper = spice.sub("database").unwrap();
        assert!(sub_viper.is_some());
        let sub_viper = sub_viper.unwrap();

        // Test direct access in sub-configuration
        let host = sub_viper.get_string("host").unwrap();
        assert_eq!(host, Some("localhost".to_string()));

        let port = sub_viper.get_int("port").unwrap();
        assert_eq!(port, Some(5432));

        let username = sub_viper.get_string("username").unwrap();
        assert_eq!(username, Some("admin".to_string()));

        // Test non-existent key in sub-configuration
        let nonexistent = sub_viper.get("nonexistent").unwrap();
        assert_eq!(nonexistent, None);
    }

    #[test]
    fn test_sub_configuration_non_object() {
        let mut spice = Spice::new();

        // Set a non-object value
        spice
            .set(
                "simple_key",
                ConfigValue::String("simple_value".to_string()),
            )
            .unwrap();

        // Sub-configuration should return None for non-object values
        let sub_viper = spice.sub("simple_key").unwrap();
        assert!(sub_viper.is_none());
    }

    #[test]
    fn test_sub_configuration_nonexistent_key() {
        let spice = Spice::new();

        // Sub-configuration should return None for non-existent keys
        let sub_viper = spice.sub("nonexistent").unwrap();
        assert!(sub_viper.is_none());
    }

    #[test]
    fn test_nested_sub_configuration() {
        let mut spice = Spice::new();

        // Create deeply nested structure
        let mut server_config = HashMap::new();
        server_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        server_config.insert("port".to_string(), ConfigValue::Integer(8080));

        let mut app_config = HashMap::new();
        app_config.insert("server".to_string(), ConfigValue::Object(server_config));

        spice.set("app", ConfigValue::Object(app_config)).unwrap();

        // Create sub-configuration for app
        let app_viper = spice.sub("app").unwrap().unwrap();

        // Create nested sub-configuration for server
        let server_viper = app_viper.sub("server").unwrap().unwrap();

        // Test access in nested sub-configuration
        let host = server_viper.get_string("host").unwrap();
        assert_eq!(host, Some("localhost".to_string()));

        let port = server_viper.get_int("port").unwrap();
        assert_eq!(port, Some(8080));
    }

    #[test]
    fn test_custom_key_delimiter() {
        let mut spice = Spice::new();
        spice.set_key_delimiter("::");

        // Create nested structure
        let mut database_config = HashMap::new();
        database_config.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        spice
            .set("database", ConfigValue::Object(database_config))
            .unwrap();

        // Test nested access with custom delimiter
        let host = spice.get("database::host").unwrap();
        assert_eq!(host, Some(ConfigValue::String("localhost".to_string())));

        // Test that dot notation doesn't work with custom delimiter
        let host_dot = spice.get("database.host").unwrap();
        assert_eq!(host_dot, None);
    }

    #[test]
    fn test_parse_key() {
        let spice = Spice::new();

        // Test simple key
        let parts = spice.parse_key("simple");
        assert_eq!(parts, vec![KeyPart::Key("simple".to_string())]);

        // Test nested key
        let parts = spice.parse_key("database.host");
        assert_eq!(
            parts,
            vec![
                KeyPart::Key("database".to_string()),
                KeyPart::Key("host".to_string())
            ]
        );

        // Test array index
        let parts = spice.parse_key("servers.0");
        assert_eq!(
            parts,
            vec![KeyPart::Key("servers".to_string()), KeyPart::Index(0)]
        );

        // Test mixed
        let parts = spice.parse_key("app.servers.0.host");
        assert_eq!(
            parts,
            vec![
                KeyPart::Key("app".to_string()),
                KeyPart::Key("servers".to_string()),
                KeyPart::Index(0),
                KeyPart::Key("host".to_string())
            ]
        );
    }

    #[test]
    fn test_traverse_nested_value() {
        let spice = Spice::new();

        // Create test structure
        let mut server = HashMap::new();
        server.insert(
            "host".to_string(),
            ConfigValue::String("localhost".to_string()),
        );
        server.insert("port".to_string(), ConfigValue::Integer(8080));

        let servers = vec![ConfigValue::Object(server)];
        let root = ConfigValue::Array(servers);

        // Test traversal
        let path = vec![KeyPart::Index(0), KeyPart::Key("host".to_string())];
        let result = spice.traverse_nested_value(&root, &path);
        assert_eq!(result, Some(ConfigValue::String("localhost".to_string())));

        // Test invalid path
        let path = vec![KeyPart::Index(1), KeyPart::Key("host".to_string())];
        let result = spice.traverse_nested_value(&root, &path);
        assert_eq!(result, None);

        // Test empty path
        let path = vec![];
        let result = spice.traverse_nested_value(&root, &path);
        assert_eq!(result, Some(root));
    }

    #[test]
    fn test_layer_precedence_in_get_operations() {
        let mut spice = Spice::new();

        // Add layers with different priorities
        let config_layer = Box::new(
            MockConfigLayer::new("config", LayerPriority::ConfigFile)
                .with_value(
                    "shared_key",
                    ConfigValue::String("config_value".to_string()),
                )
                .with_value(
                    "config_only",
                    ConfigValue::String("config_only_value".to_string()),
                ),
        );
        spice.add_layer(config_layer);

        let env_layer = Box::new(
            MockConfigLayer::new("env", LayerPriority::Environment)
                .with_value("shared_key", ConfigValue::String("env_value".to_string()))
                .with_value(
                    "env_only",
                    ConfigValue::String("env_only_value".to_string()),
                ),
        );
        spice.add_layer(env_layer);

        // Explicit set (highest priority)
        spice
            .set(
                "shared_key",
                ConfigValue::String("explicit_value".to_string()),
            )
            .unwrap();

        // Test precedence: explicit > env > config
        assert_eq!(
            spice.get_string("shared_key").unwrap(),
            Some("explicit_value".to_string())
        );
        assert_eq!(
            spice.get_string("env_only").unwrap(),
            Some("env_only_value".to_string())
        );
        assert_eq!(
            spice.get_string("config_only").unwrap(),
            Some("config_only_value".to_string())
        );
    }

    #[test]
    fn test_set_default() {
        let mut spice = Spice::new();

        // Set a default value
        spice
            .set_default("database.host", ConfigValue::from("localhost"))
            .unwrap();
        spice
            .set_default("database.port", ConfigValue::from(5432i64))
            .unwrap();

        // Verify defaults are accessible
        assert_eq!(
            spice.get_string("database.host").unwrap(),
            Some("localhost".to_string())
        );
        assert_eq!(spice.get_i64("database.port").unwrap(), Some(5432));

        // Verify default layer was created with correct priority
        let layer_info = spice.layer_info();
        assert!(layer_info
            .iter()
            .any(|(name, priority)| name == "defaults" && *priority == LayerPriority::Defaults));
    }

    #[test]
    fn test_set_defaults_bulk() {
        let mut spice = Spice::new();

        // Set multiple defaults at once
        let mut defaults = HashMap::new();
        defaults.insert("server.host".to_string(), ConfigValue::from("0.0.0.0"));
        defaults.insert("server.port".to_string(), ConfigValue::from(8080i64));
        defaults.insert("server.ssl".to_string(), ConfigValue::from(false));
        defaults.insert("database.timeout".to_string(), ConfigValue::from(30i64));

        spice.set_defaults(defaults).unwrap();

        // Verify all defaults are accessible
        assert_eq!(
            spice.get_string("server.host").unwrap(),
            Some("0.0.0.0".to_string())
        );
        assert_eq!(spice.get_i64("server.port").unwrap(), Some(8080));
        assert_eq!(spice.get_bool("server.ssl").unwrap(), Some(false));
        assert_eq!(spice.get_i64("database.timeout").unwrap(), Some(30));

        // Verify only one default layer was created
        let layer_info = spice.layer_info();
        let default_layers: Vec<_> = layer_info
            .iter()
            .filter(|(name, _)| name == "defaults")
            .collect();
        assert_eq!(default_layers.len(), 1);
    }

    #[test]
    fn test_default_precedence() {
        let mut spice = Spice::new();

        // Set a default value
        spice
            .set_default("key", ConfigValue::from("default_value"))
            .unwrap();
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("default_value".to_string())
        );

        // Override with explicit value (higher precedence)
        spice
            .set("key", ConfigValue::from("explicit_value"))
            .unwrap();
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("explicit_value".to_string())
        );

        // Add a config file layer (higher precedence than defaults, lower than explicit)
        let config_layer = Box::new(
            MockConfigLayer::new("config", LayerPriority::ConfigFile)
                .with_value("key", ConfigValue::from("config_value")),
        );
        spice.add_layer(config_layer);

        // Explicit should still win
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("explicit_value".to_string())
        );

        // Remove explicit layer and config should win over default
        spice.remove_layers_by_priority(LayerPriority::Explicit);
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("config_value".to_string())
        );

        // Remove config layer and default should be used
        spice.remove_layers_by_priority(LayerPriority::ConfigFile);
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("default_value".to_string())
        );
    }

    #[test]
    fn test_multiple_default_operations() {
        let mut spice = Spice::new();

        // Set individual defaults
        spice
            .set_default("key1", ConfigValue::from("value1"))
            .unwrap();
        spice
            .set_default("key2", ConfigValue::from("value2"))
            .unwrap();

        // Set bulk defaults
        let mut bulk_defaults = HashMap::new();
        bulk_defaults.insert("key3".to_string(), ConfigValue::from("value3"));
        bulk_defaults.insert("key4".to_string(), ConfigValue::from("value4"));
        spice.set_defaults(bulk_defaults).unwrap();

        // Override one of the individual defaults
        spice
            .set_default("key1", ConfigValue::from("updated_value1"))
            .unwrap();

        // Verify all values
        assert_eq!(
            spice.get_string("key1").unwrap(),
            Some("updated_value1".to_string())
        );
        assert_eq!(
            spice.get_string("key2").unwrap(),
            Some("value2".to_string())
        );
        assert_eq!(
            spice.get_string("key3").unwrap(),
            Some("value3".to_string())
        );
        assert_eq!(
            spice.get_string("key4").unwrap(),
            Some("value4".to_string())
        );

        // Verify still only one default layer
        let layer_info = spice.layer_info();
        let default_layers: Vec<_> = layer_info
            .iter()
            .filter(|(name, _)| name == "defaults")
            .collect();
        assert_eq!(default_layers.len(), 1);
    }

    #[test]
    fn test_defaults_with_nested_keys() {
        let mut spice = Spice::new();

        // Set nested default values
        spice
            .set_default("database.connection.host", ConfigValue::from("localhost"))
            .unwrap();
        spice
            .set_default("database.connection.port", ConfigValue::from(5432i64))
            .unwrap();
        spice
            .set_default("database.pool.max_size", ConfigValue::from(10i64))
            .unwrap();

        // Verify nested access works with defaults
        assert_eq!(
            spice.get_string("database.connection.host").unwrap(),
            Some("localhost".to_string())
        );
        assert_eq!(
            spice.get_i64("database.connection.port").unwrap(),
            Some(5432)
        );
        assert_eq!(spice.get_i64("database.pool.max_size").unwrap(), Some(10));

        // Test that defaults work with sub-configurations
        // Note: This will only work if we have a nested object structure, not just dot-notation keys
        // For now, just verify the keys exist
        assert!(spice.is_set("database.connection.host"));
        assert!(spice.is_set("database.connection.port"));
        assert!(spice.is_set("database.pool.max_size"));
    }

    #[test]
    fn test_defaults_with_different_value_types() {
        let mut spice = Spice::new();

        // Set defaults with various types
        spice
            .set_default("string_val", ConfigValue::from("hello"))
            .unwrap();
        spice
            .set_default("int_val", ConfigValue::from(42i64))
            .unwrap();
        spice
            .set_default("float_val", ConfigValue::from(3.14))
            .unwrap();
        spice
            .set_default("bool_val", ConfigValue::from(true))
            .unwrap();
        spice.set_default("null_val", ConfigValue::Null).unwrap();

        // Create array and object defaults
        let array_val =
            ConfigValue::Array(vec![ConfigValue::from("item1"), ConfigValue::from("item2")]);
        spice.set_default("array_val", array_val).unwrap();

        let mut obj = HashMap::new();
        obj.insert("nested_key".to_string(), ConfigValue::from("nested_value"));
        spice
            .set_default("object_val", ConfigValue::Object(obj))
            .unwrap();

        // Verify all types work correctly
        assert_eq!(
            spice.get_string("string_val").unwrap(),
            Some("hello".to_string())
        );
        assert_eq!(spice.get_i64("int_val").unwrap(), Some(42));
        assert_eq!(spice.get_f64("float_val").unwrap(), Some(3.14));
        assert_eq!(spice.get_bool("bool_val").unwrap(), Some(true));
        assert_eq!(spice.get("null_val").unwrap(), Some(ConfigValue::Null));

        let array = spice.get_array("array_val").unwrap().unwrap();
        assert_eq!(array.len(), 2);
        assert_eq!(array[0], ConfigValue::from("item1"));

        let obj = spice.get_object("object_val").unwrap().unwrap();
        assert_eq!(
            obj.get("nested_key"),
            Some(&ConfigValue::from("nested_value"))
        );
    }

    // File discovery tests
    #[test]
    fn test_find_config_file_empty_name() {
        let spice = Spice::new();
        let result = spice.find_config_file().unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_find_config_file_no_paths() {
        let mut spice = Spice::new();
        spice.set_config_name("nonexistent");

        let result = spice.find_config_file().unwrap();
        // Should return None since no config file exists
        assert!(result.is_none());
    }

    #[test]
    fn test_find_config_file_with_temp_file() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_content = r#"{"test_key": "test_value"}"#;
        let config_file = temp_dir.path().join("test_config.json");
        fs::write(&config_file, config_content).unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("test_config");
        spice.add_config_path(temp_dir.path());

        let result = spice.find_config_file().unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap(), config_file);
    }

    #[test]
    fn test_find_config_file_multiple_extensions() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();

        // Create multiple config files with different extensions
        let json_content = r#"{"format": "json"}"#;
        let yaml_content = "format: yaml";
        let toml_content = "format = \"toml\"";

        fs::write(temp_dir.path().join("app.json"), json_content).unwrap();
        fs::write(temp_dir.path().join("app.yaml"), yaml_content).unwrap();
        fs::write(temp_dir.path().join("app.toml"), toml_content).unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("app");
        spice.add_config_path(temp_dir.path());

        let result = spice.find_config_file().unwrap();
        assert!(result.is_some());

        // Should find the first one (json comes first in the extension list)
        let found_file = result.unwrap();
        assert_eq!(found_file.extension().unwrap(), "json");
    }

    #[test]
    fn test_find_config_file_priority_order() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir1 = TempDir::new().unwrap();
        let temp_dir2 = TempDir::new().unwrap();

        // Create config files in both directories
        let config_content1 = r#"{"source": "dir1"}"#;
        let config_content2 = r#"{"source": "dir2"}"#;

        fs::write(temp_dir1.path().join("priority_test.json"), config_content1).unwrap();
        fs::write(temp_dir2.path().join("priority_test.json"), config_content2).unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("priority_test");
        spice.add_config_path(temp_dir1.path()); // Added first, should have priority
        spice.add_config_path(temp_dir2.path());

        let result = spice.find_config_file().unwrap();
        assert!(result.is_some());

        // Should find the file from the first directory
        let found_file = result.unwrap();
        assert!(found_file.starts_with(temp_dir1.path()));
    }

    #[test]
    fn test_find_all_config_files() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir1 = TempDir::new().unwrap();
        let temp_dir2 = TempDir::new().unwrap();

        // Create config files in both directories with different extensions
        fs::write(temp_dir1.path().join("multi.json"), r#"{"source": "dir1"}"#).unwrap();
        fs::write(temp_dir1.path().join("multi.yaml"), "source: dir1_yaml").unwrap();
        fs::write(temp_dir2.path().join("multi.toml"), "source = \"dir2\"").unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("multi");
        spice.add_config_path(temp_dir1.path());
        spice.add_config_path(temp_dir2.path());

        let result = spice.find_all_config_files().unwrap();
        assert_eq!(result.len(), 3); // Should find all three files

        // Verify all files are found
        let file_names: Vec<String> = result
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(file_names.contains(&"multi.json".to_string()));
        assert!(file_names.contains(&"multi.yaml".to_string()));
        assert!(file_names.contains(&"multi.toml".to_string()));
    }

    #[test]
    fn test_read_in_config_success() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_content = r#"{"database": {"host": "localhost", "port": 5432}}"#;
        let config_file = temp_dir.path().join("read_test.json");
        fs::write(&config_file, config_content).unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("read_test");
        spice.add_config_path(temp_dir.path());

        let result = spice.read_in_config();
        assert!(result.is_ok());

        // Verify the configuration was loaded
        assert_eq!(
            spice.get_string("database.host").unwrap(),
            Some("localhost".to_string())
        );
        assert_eq!(spice.get_i64("database.port").unwrap(), Some(5432));
    }

    #[test]
    fn test_read_in_config_file_not_found() {
        let mut spice = Spice::new();
        spice.set_config_name("nonexistent");
        spice.add_config_path("/nonexistent/path");

        let result = spice.read_in_config();
        assert!(result.is_err());

        if let Err(ConfigError::KeyNotFound { key }) = result {
            assert!(key.contains("nonexistent"));
        } else {
            panic!("Expected KeyNotFound error");
        }
    }

    #[test]
    fn test_set_config_file_direct() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_content = r#"{"direct": "load", "value": 42}"#;
        let config_file = temp_dir.path().join("direct.json");
        fs::write(&config_file, config_content).unwrap();

        let mut spice = Spice::new();
        let result = spice.set_config_file(&config_file);
        assert!(result.is_ok());

        // Verify the configuration was loaded
        assert_eq!(
            spice.get_string("direct").unwrap(),
            Some("load".to_string())
        );
        assert_eq!(spice.get_i64("value").unwrap(), Some(42));
    }

    #[test]
    fn test_merge_in_config() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();

        // Create multiple config files with overlapping keys
        let config1 = r#"{"shared": "from_json", "json_only": "json_value"}"#;
        let config2 = "shared: from_yaml\nyaml_only: yaml_value";
        let config3 = "shared = \"from_toml\"\ntoml_only = \"toml_value\"";

        fs::write(temp_dir.path().join("merge.json"), config1).unwrap();
        fs::write(temp_dir.path().join("merge.yaml"), config2).unwrap();
        fs::write(temp_dir.path().join("merge.toml"), config3).unwrap();

        let mut spice = Spice::new();
        spice.set_config_name("merge");
        spice.add_config_path(temp_dir.path());

        let merged_count = spice.merge_in_config().unwrap();
        assert_eq!(merged_count, 3);

        // Verify all unique keys are present
        assert!(spice.is_set("json_only"));
        assert!(spice.is_set("yaml_only"));
        assert!(spice.is_set("toml_only"));

        // The shared key should have the value from the first file found (JSON)
        assert_eq!(
            spice.get_string("shared").unwrap(),
            Some("from_json".to_string())
        );
    }

    #[test]
    fn test_load_config_file_invalid_format() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let invalid_json = r#"{"invalid": json content}"#; // Missing quotes around "json"
        let config_file = temp_dir.path().join("invalid.json");
        fs::write(&config_file, invalid_json).unwrap();

        let mut spice = Spice::new();
        let result = spice.load_config_file(&config_file);
        assert!(result.is_err());

        // Should be a parse error
        match result {
            Err(ConfigError::Parse {
                source_name,
                message: _,
            }) => {
                // The source_name might be the file path, not just "JSON"
                assert!(source_name.contains("JSON") || source_name.contains("invalid.json"));
            }
            Err(e) => panic!("Expected Parse error, got: {:?}", e),
            Ok(_) => panic!("Expected error for invalid JSON, but got success"),
        }
    }

    #[test]
    fn test_get_standard_config_paths() {
        let spice = Spice::new();
        let paths = spice.get_standard_config_paths().unwrap();

        // Should always include current directory
        assert!(paths.contains(&PathBuf::from(".")));

        // Should include some system paths (exact paths depend on OS)
        assert!(paths.len() > 1);
    }

    #[test]
    fn test_config_file_precedence_with_explicit_set() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_content = r#"{"precedence_test": "from_file"}"#;
        let config_file = temp_dir.path().join("precedence.json");
        fs::write(&config_file, config_content).unwrap();

        let mut spice = Spice::new();

        // Load config file first
        spice.load_config_file(&config_file).unwrap();
        assert_eq!(
            spice.get_string("precedence_test").unwrap(),
            Some("from_file".to_string())
        );

        // Set explicit value (should override file)
        spice
            .set("precedence_test", ConfigValue::from("explicit_value"))
            .unwrap();
        assert_eq!(
            spice.get_string("precedence_test").unwrap(),
            Some("explicit_value".to_string())
        );
    }

    #[test]
    fn test_multiple_format_support() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();

        // Test each supported format
        let formats = vec![
            ("test.json", r#"{"format": "json", "number": 42}"#),
            ("test.yaml", "format: yaml\nnumber: 42"),
            ("test.toml", "format = \"toml\"\nnumber = 42"),
            ("test.ini", "[section]\nformat = ini\nnumber = 42"),
        ];

        for (filename, content) in formats {
            let config_file = temp_dir.path().join(filename);
            fs::write(&config_file, content).unwrap();

            let mut spice = Spice::new();
            let result = spice.load_config_file(&config_file);
            assert!(result.is_ok(), "Failed to load {}: {:?}", filename, result);

            // Verify content was parsed correctly
            if filename.ends_with(".ini") {
                // INI files have sections
                assert_eq!(
                    spice.get_string("section.format").unwrap(),
                    Some("ini".to_string())
                );
                assert_eq!(spice.get_i64("section.number").unwrap(), Some(42));
            } else {
                assert!(spice.is_set("format"));
                assert_eq!(spice.get_i64("number").unwrap(), Some(42));
            }
        }
    }

    #[test]
    fn test_file_watching_integration() {
        use std::fs;
        use std::sync::{Arc, Mutex};
        use std::thread;
        use std::time::Duration;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");

        // Create initial config file
        fs::write(&config_path, r#"{"key": "initial_value"}"#).unwrap();

        let mut spice = Spice::new();
        spice.set_config_file(&config_path).unwrap();

        // Verify initial value
        assert_eq!(
            spice.get_string("key").unwrap(),
            Some("initial_value".to_string())
        );

        // Enable file watching
        spice.watch_config().unwrap();
        assert!(spice.is_watching());

        // Register callback to track changes
        let change_count = Arc::new(Mutex::new(0));
        let change_count_clone = Arc::clone(&change_count);

        spice
            .on_config_change(move || {
                let mut count = change_count_clone.lock().unwrap();
                *count += 1;
            })
            .unwrap();

        // Modify the file
        fs::write(&config_path, r#"{"key": "updated_value"}"#).unwrap();

        // Give some time for the file watcher to detect the change
        thread::sleep(Duration::from_millis(100));

        // Check that callback was called
        let final_count = *change_count.lock().unwrap();
        assert!(
            final_count > 0,
            "Configuration change callback should have been called"
        );

        // Stop watching
        spice.stop_watching();
        assert!(!spice.is_watching());
    }

    #[test]
    fn test_on_config_change_without_watching() {
        let mut spice = Spice::new();

        // Try to register callback without enabling file watching
        let result = spice.on_config_change(|| {});
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("File watching is not enabled"));
    }

    #[test]
    fn test_multiple_config_change_callbacks() {
        use std::fs;
        use std::sync::{Arc, Mutex};
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let mut spice = Spice::new();
        spice.set_config_file(&config_path).unwrap();
        spice.watch_config().unwrap();

        let callback1_called = Arc::new(Mutex::new(false));
        let callback2_called = Arc::new(Mutex::new(false));

        let callback1_called_clone = Arc::clone(&callback1_called);
        let callback2_called_clone = Arc::clone(&callback2_called);

        // Register multiple callbacks
        spice
            .on_config_change(move || {
                *callback1_called_clone.lock().unwrap() = true;
            })
            .unwrap();

        spice
            .on_config_change(move || {
                *callback2_called_clone.lock().unwrap() = true;
            })
            .unwrap();

        // Manually trigger callbacks for testing
        if let Some(watcher) = &spice.watcher {
            watcher.trigger_callbacks_for_test();
        }

        // Both callbacks should have been called
        assert!(*callback1_called.lock().unwrap());
        assert!(*callback2_called.lock().unwrap());

        spice.stop_watching();
    }

    #[test]
    fn test_watched_config_files() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.json");
        fs::write(&config_path, "{}").unwrap();

        let mut spice = Spice::new();
        assert_eq!(spice.watched_config_files().len(), 0);

        spice.set_config_file(&config_path).unwrap();
        spice.watch_config().unwrap();

        let watched_files = spice.watched_config_files();
        assert_eq!(watched_files.len(), 1);
        assert_eq!(watched_files[0], config_path);

        spice.stop_watching();
        assert_eq!(spice.watched_config_files().len(), 0);
    }

    #[test]
    fn test_serialization_with_special_float_values() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("special_floats.json");

        let mut spice = Spice::new();

        // Add special float values that need optimization
        spice
            .set("normal_float", ConfigValue::Float(3.14159))
            .unwrap();
        spice.set("zero_float", ConfigValue::Float(0.0)).unwrap();
        spice
            .set("negative_zero", ConfigValue::Float(-0.0))
            .unwrap();
        spice
            .set("nan_float", ConfigValue::Float(f64::NAN))
            .unwrap();
        spice
            .set("infinity_float", ConfigValue::Float(f64::INFINITY))
            .unwrap();
        spice
            .set("neg_infinity_float", ConfigValue::Float(f64::NEG_INFINITY))
            .unwrap();

        // Write configuration - should handle special values
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify special values were handled
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["normal_float"], 3.14159);
        assert_eq!(parsed["zero_float"], 0.0);

        // NaN and infinity should be converted to strings
        assert_eq!(parsed["nan_float"], "NaN");
        assert_eq!(parsed["infinity_float"], "inf");
        assert_eq!(parsed["neg_infinity_float"], "-inf");
    }

    #[test]
    fn test_serialization_configuration_merging() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("merged_config.json");

        let mut spice = Spice::new();

        // Add values from different layers to test merging
        spice
            .set_default("app.name", ConfigValue::String("default-app".to_string()))
            .unwrap();
        spice
            .set_default("app.version", ConfigValue::String("1.0.0".to_string()))
            .unwrap();
        spice
            .set_default("app.debug", ConfigValue::Boolean(false))
            .unwrap();

        // Override some defaults with explicit values
        spice
            .set("app.name", ConfigValue::String("my-app".to_string()))
            .unwrap();
        spice.set("app.debug", ConfigValue::Boolean(true)).unwrap();

        // Add additional explicit values
        spice
            .set(
                "database.host",
                ConfigValue::String("localhost".to_string()),
            )
            .unwrap();
        spice
            .set("database.port", ConfigValue::Integer(5432))
            .unwrap();

        // Write configuration - should merge all layers properly
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify merging worked correctly
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        // Explicit values should override defaults
        assert_eq!(parsed["app"]["name"], "my-app");
        assert_eq!(parsed["app"]["debug"], true);

        // Default values should be preserved when not overridden
        assert_eq!(parsed["app"]["version"], "1.0.0");

        // Explicit-only values should be present
        assert_eq!(parsed["database"]["host"], "localhost");
        assert_eq!(parsed["database"]["port"], 5432);
    }

    #[test]
    fn test_write_config_as_with_enhanced_error_handling() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("subdir").join("config.yaml");

        let mut spice = Spice::new();
        spice
            .set("test.key", ConfigValue::String("test_value".to_string()))
            .unwrap();

        // Should create parent directories automatically
        spice.write_config_as(&config_path, "yaml").unwrap();

        assert!(config_path.exists());
        assert!(config_path.parent().unwrap().exists());

        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("test_value"));
    }

    #[test]
    fn test_write_config_as_unsupported_format_enhanced_error() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.txt");

        let mut spice = Spice::new();
        spice
            .set("test", ConfigValue::String("value".to_string()))
            .unwrap();

        // Should fail with enhanced error message
        let result = spice.write_config_as(&config_path, "unsupported");
        assert!(result.is_err());

        if let Err(crate::error::ConfigError::Serialization(msg)) = result {
            assert!(msg.contains("Failed to detect parser for format 'unsupported'"));
        } else {
            panic!("Expected Serialization error with enhanced message");
        }
    }

    #[test]
    fn test_serialization_nested_key_expansion() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("nested_expansion.json");

        let mut spice = Spice::new();

        // Set nested keys using dot notation
        spice
            .set(
                "app.database.host",
                ConfigValue::String("localhost".to_string()),
            )
            .unwrap();
        spice
            .set("app.database.port", ConfigValue::Integer(5432))
            .unwrap();
        spice
            .set(
                "app.server.host",
                ConfigValue::String("0.0.0.0".to_string()),
            )
            .unwrap();
        spice
            .set("app.server.port", ConfigValue::Integer(8080))
            .unwrap();

        // Write configuration - should expand nested keys properly
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify nested structure
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["app"]["database"]["host"], "localhost");
        assert_eq!(parsed["app"]["database"]["port"], 5432);
        assert_eq!(parsed["app"]["server"]["host"], "0.0.0.0");
        assert_eq!(parsed["app"]["server"]["port"], 8080);
    }

    #[test]
    fn test_serialization_format_specific_handling() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();

        let mut spice = Spice::new();
        spice
            .set("string_key", ConfigValue::String("hello world".to_string()))
            .unwrap();
        spice.set("integer_key", ConfigValue::Integer(42)).unwrap();
        spice.set("float_key", ConfigValue::Float(3.14159)).unwrap();
        spice
            .set("boolean_key", ConfigValue::Boolean(true))
            .unwrap();
        spice.set("null_key", ConfigValue::Null).unwrap();

        // Test JSON serialization
        let json_path = temp_dir.path().join("test.json");
        spice.write_config_as(&json_path, "json").unwrap();
        let json_content = fs::read_to_string(&json_path).unwrap();
        assert!(json_content.contains("\"hello world\""));
        assert!(json_content.contains("42"));
        assert!(json_content.contains("3.14159"));
        assert!(json_content.contains("true"));
        assert!(json_content.contains("null"));

        // Test YAML serialization
        let yaml_path = temp_dir.path().join("test.yaml");
        spice.write_config_as(&yaml_path, "yaml").unwrap();
        let yaml_content = fs::read_to_string(&yaml_path).unwrap();
        assert!(yaml_content.contains("hello world"));
        assert!(yaml_content.contains("42"));
        assert!(yaml_content.contains("3.14159"));
        assert!(yaml_content.contains("true"));

        // Test TOML serialization
        let toml_path = temp_dir.path().join("test.toml");
        spice.write_config_as(&toml_path, "toml").unwrap();
        let toml_content = fs::read_to_string(&toml_path).unwrap();
        assert!(toml_content.contains("\"hello world\""));
        assert!(toml_content.contains("42"));
        assert!(toml_content.contains("3.14159"));
        assert!(toml_content.contains("true"));
    }

    #[test]
    fn test_write_config_file_permission_error_enhanced() {
        use std::fs;
        use tempfile::TempDir;

        // Only run on Unix systems where we can control permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            let temp_dir = TempDir::new().unwrap();
            let readonly_dir = temp_dir.path().join("readonly");
            fs::create_dir(&readonly_dir).unwrap();

            // Make directory read-only
            let mut perms = fs::metadata(&readonly_dir).unwrap().permissions();
            perms.set_mode(0o444);
            fs::set_permissions(&readonly_dir, perms).unwrap();

            let config_path = readonly_dir.join("config.json");

            let mut spice = Spice::new();
            spice
                .set("test", ConfigValue::String("value".to_string()))
                .unwrap();

            // Should fail with enhanced IO error message
            let result = spice.write_config(&config_path);
            assert!(result.is_err());

            if let Err(crate::error::ConfigError::Io(io_err)) = result {
                let error_msg = io_err.to_string();
                assert!(error_msg.contains("Failed to write configuration to"));
                assert!(error_msg.contains("config.json"));
            } else {
                panic!("Expected IO error with enhanced message");
            }

            // Restore permissions for cleanup
            let mut perms = fs::metadata(&readonly_dir).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&readonly_dir, perms).unwrap();
        }
    }

    #[test]
    fn test_serialization_optimization_recursive() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("recursive_optimization.json");

        let mut spice = Spice::new();

        // Create deeply nested structure with special values
        let mut level1 = std::collections::HashMap::new();
        let mut level2 = std::collections::HashMap::new();
        let mut level3 = std::collections::HashMap::new();

        level3.insert("normal".to_string(), ConfigValue::Float(1.23));
        level3.insert("nan".to_string(), ConfigValue::Float(f64::NAN));
        level3.insert("infinity".to_string(), ConfigValue::Float(f64::INFINITY));

        level2.insert("nested".to_string(), ConfigValue::Object(level3));
        level2.insert(
            "array".to_string(),
            ConfigValue::Array(vec![
                ConfigValue::Float(f64::NAN),
                ConfigValue::Float(f64::INFINITY),
                ConfigValue::Float(2.71),
            ]),
        );

        level1.insert("deep".to_string(), ConfigValue::Object(level2));
        spice.set("root", ConfigValue::Object(level1)).unwrap();

        // Write configuration - should recursively optimize all values
        spice.write_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();

        // Parse back and verify recursive optimization
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["root"]["deep"]["nested"]["normal"], 1.23);
        assert_eq!(parsed["root"]["deep"]["nested"]["nan"], "NaN");
        assert_eq!(parsed["root"]["deep"]["nested"]["infinity"], "inf");
        assert_eq!(parsed["root"]["deep"]["array"][0], "NaN");
        assert_eq!(parsed["root"]["deep"]["array"][1], "inf");
        assert_eq!(parsed["root"]["deep"]["array"][2], 2.71);
    }

    #[cfg(feature = "cli")]
    mod flag_binding_tests {
        use super::*;
        use clap::{Arg, Command};
        use std::collections::HashMap;

        fn create_test_cli_app() -> Command {
            Command::new("test")
                .disable_help_flag(true)
                .arg(
                    Arg::new("host")
                        .long("host")
                        .short('h')
                        .value_name("HOST")
                        .action(clap::ArgAction::Set)
                        .help("Database host"),
                )
                .arg(
                    Arg::new("port")
                        .long("port")
                        .short('p')
                        .value_name("PORT")
                        .action(clap::ArgAction::Set)
                        .help("Database port"),
                )
                .arg(
                    Arg::new("verbose")
                        .long("verbose")
                        .short('v')
                        .action(clap::ArgAction::SetTrue)
                        .help("Enable verbose output"),
                )
        }

        #[test]
        fn test_bind_flags_basic() {
            let app = create_test_cli_app();
            let args = vec!["test", "--host", "localhost", "--port", "5432", "--verbose"];
            let matches = app.try_get_matches_from(args).unwrap();

            let mut spice = Spice::new();
            spice.bind_flags(matches);

            // Test string flag
            assert_eq!(
                spice.get_string("host").unwrap(),
                Some("localhost".to_string())
            );

            // Test integer flag (parsed from string)
            assert_eq!(spice.get_i64("port").unwrap(), Some(5432));

            // Test boolean flag
            assert_eq!(spice.get_bool("verbose").unwrap(), Some(true));
        }

        #[test]
        fn test_bind_flags_with_mappings() {
            let app = create_test_cli_app();
            let args = vec!["test", "--host", "localhost", "--port", "5432"];
            let matches = app.try_get_matches_from(args).unwrap();

            let mut mappings = HashMap::new();
            mappings.insert("host".to_string(), "database.host".to_string());
            mappings.insert("port".to_string(), "database.port".to_string());

            let mut spice = Spice::new();
            spice.bind_flags_with_mappings(matches, mappings);

            // Test mapped keys
            assert_eq!(
                spice.get_string("database.host").unwrap(),
                Some("localhost".to_string())
            );
            assert_eq!(spice.get_i64("database.port").unwrap(), Some(5432));

            // Original keys should not be available
            assert_eq!(spice.get_string("host").unwrap(), None);
            assert_eq!(spice.get_i64("port").unwrap(), None);
        }

        #[test]
        fn test_bind_flag_individual() {
            let app = create_test_cli_app();
            let args = vec!["test", "--verbose", "--host", "localhost"];
            let matches = app.try_get_matches_from(args).unwrap();

            let mut spice = Spice::new();
            spice.bind_flags(matches);

            // Initially available under original key
            assert_eq!(spice.get_bool("verbose").unwrap(), Some(true));

            // Bind individual flag to custom key
            spice.bind_flag("verbose", "logging.verbose").unwrap();

            // After binding, should be available under the new key
            assert_eq!(spice.get_bool("logging.verbose").unwrap(), Some(true));
            // Original key should no longer be available since mapping replaces it
            assert_eq!(spice.get_bool("verbose").unwrap(), None);
        }

        #[test]
        fn test_bind_flag_without_flag_layer() {
            let mut spice = Spice::new();

            // Should fail when no flag layer exists
            let result = spice.bind_flag("verbose", "logging.verbose");
            assert!(result.is_err());

            if let Err(ConfigError::UnsupportedOperation(msg)) = result {
                assert!(msg.contains("No flag configuration layer found"));
            } else {
                panic!("Expected UnsupportedOperation error");
            }
        }

        #[test]
        fn test_flag_precedence_over_other_sources() {
            let mut spice = Spice::new();

            // Set default value
            spice
                .set_default("host", ConfigValue::String("default-host".to_string()))
                .unwrap();

            // Add flag layer
            let app = create_test_cli_app();
            let args = vec!["test", "--host", "flag-host"];
            let matches = app.try_get_matches_from(args).unwrap();
            spice.bind_flags(matches);

            // Flag should override default
            assert_eq!(
                spice.get_string("host").unwrap(),
                Some("flag-host".to_string())
            );
        }

        #[test]
        fn test_explicit_set_overrides_flags() {
            let mut spice = Spice::new();

            // Add flag layer
            let app = create_test_cli_app();
            let args = vec!["test", "--host", "flag-host"];
            let matches = app.try_get_matches_from(args).unwrap();
            spice.bind_flags(matches);

            // Explicit set should override flag
            spice
                .set("host", ConfigValue::String("explicit-host".to_string()))
                .unwrap();

            assert_eq!(
                spice.get_string("host").unwrap(),
                Some("explicit-host".to_string())
            );
        }

        #[test]
        fn test_count_flags() {
            let app = Command::new("test").disable_help_flag(true).arg(
                Arg::new("debug")
                    .long("debug")
                    .short('d')
                    .action(clap::ArgAction::Count)
                    .help("Debug level"),
            );

            let args = vec!["test", "-ddd"];
            let matches = app.try_get_matches_from(args).unwrap();

            let mut spice = Spice::new();
            spice.bind_flags(matches);

            // Count flags should be converted to integers
            assert_eq!(spice.get_i64("debug").unwrap(), Some(3));
        }

        #[test]
        fn test_flag_layer_priority() {
            let mut spice = Spice::new();

            // Add layers in different order to test priority sorting
            spice
                .set_default("key", ConfigValue::String("default".to_string()))
                .unwrap();

            let app = create_test_cli_app();
            let args = vec!["test", "--host", "flag-value"];
            let matches = app.try_get_matches_from(args).unwrap();
            spice.bind_flags(matches);

            // Check that layers are properly sorted by priority
            let layer_info = spice.layer_info();
            let flag_layer_index = layer_info
                .iter()
                .position(|(_, priority)| *priority == LayerPriority::Flags);
            let default_layer_index = layer_info
                .iter()
                .position(|(_, priority)| *priority == LayerPriority::Defaults);

            assert!(flag_layer_index.is_some());
            assert!(default_layer_index.is_some());
            assert!(flag_layer_index.unwrap() < default_layer_index.unwrap());
        }

        #[test]
        fn test_multiple_flag_layers() {
            let mut spice = Spice::new();

            // Add first flag layer
            let app1 = Command::new("test1")
                .disable_help_flag(true)
                .arg(Arg::new("host").long("host").action(clap::ArgAction::Set));
            let args1 = vec!["test1", "--host", "host1"];
            let matches1 = app1.try_get_matches_from(args1).unwrap();
            spice.bind_flags(matches1);

            // Add second flag layer
            let app2 = Command::new("test2")
                .disable_help_flag(true)
                .arg(Arg::new("port").long("port").action(clap::ArgAction::Set));
            let args2 = vec!["test2", "--port", "8080"];
            let matches2 = app2.try_get_matches_from(args2).unwrap();
            spice.bind_flags(matches2);

            // Both flags should be available
            assert_eq!(spice.get_string("host").unwrap(), Some("host1".to_string()));
            assert_eq!(spice.get_i64("port").unwrap(), Some(8080));
        }
    }
}