cdk-mintd 0.18.0

CDK mint binary
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
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
#![allow(missing_docs)]
//! Cdk mintd lib

// std
use std::collections::{HashMap, HashSet};
use std::env::{self};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

// external crates
use anyhow::{anyhow, bail, Context, Result};
use axum::extract::DefaultBodyLimit;
use axum::Router;
use bip39::Mnemonic;
use cdk::cdk_database::{self, KVStore, KVStoreCompareAndSwap, MintDatabase, MintKeysDatabase};
use cdk::mint::{Mint, MintBuilder, MintMeltLimits};
use cdk::nuts::nut00::KnownMethod;
#[cfg(any(
    feature = "cln",
    feature = "lnd",
    feature = "ldk-node",
    feature = "fakewallet",
    feature = "bdk",
    feature = "grpc-processor"
))]
use cdk::nuts::nut17::SupportedMethods;
use cdk::nuts::nut19::{CachedEndpoint, Method as NUT19Method, Path as NUT19Path};
use cdk::nuts::{
    AuthRequired, ContactInfo, Method, MintVersion, PaymentMethod, ProtectedEndpoint, RoutePath,
};
use cdk_axum::cache::HttpCache;
use cdk_common::common::QuoteTTL;
use cdk_common::database::DynMintDatabase;
// internal crate modules
#[cfg(feature = "prometheus")]
use cdk_common::payment::MetricsMintPayment;
use cdk_common::payment::MintPayment;
#[cfg(feature = "postgres")]
use cdk_postgres::{MintPgAuthDatabase, MintPgDatabase, PgConfig};
#[cfg(feature = "sqlite")]
use cdk_sqlite::mint::MintSqliteAuthDatabase;
#[cfg(feature = "sqlite")]
use cdk_sqlite::MintSqliteDatabase;
use cli::CLIArgs;
use config::{AuthType, DatabaseEngine, PaymentBackendType};
use env_vars::ENV_WORK_DIR;
use setup::PaymentBackendSetup;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::decompression::RequestDecompressionLayer;
use tower_http::trace::TraceLayer;
use tracing_appender::{non_blocking, rolling};
use tracing_subscriber::fmt::writer::MakeWriterExt;
use tracing_subscriber::EnvFilter;

pub mod cli;
pub mod config;
mod config_migration;
mod config_service;
mod config_store;
pub mod env_vars;
mod secret;
pub mod setup;

pub use config_migration::{migrate_legacy_configuration, MigrationOutcome};
pub use config_service::{ApplyOutcome, RollbackOutcome};

#[cfg(test)]
pub(crate) mod test_utils {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Mutex, MutexGuard, OnceLock};

    pub(crate) fn env_lock() -> MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }

    pub(crate) fn unique_temp_path(name: &str) -> PathBuf {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        std::env::temp_dir().join(format!(
            "{name}_{}_{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ))
    }
}

const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
const DEFAULT_BATCH_MINT_SIZE: u64 = 100;
const REQUEST_BODY_LIMIT_BYTES: usize = 1_048_576;

type DynSignatory = Arc<dyn cdk_signatory::signatory::Signatory + Send + Sync>;

#[derive(Clone)]
struct ValidatedSigningSource {
    expected_pubkey: cdk::nuts::PublicKey,
    remote_signatory: Option<DynSignatory>,
}

impl std::fmt::Debug for ValidatedSigningSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ValidatedSigningSource")
            .field("expected_pubkey", &self.expected_pubkey)
            .field("remote_signatory", &self.remote_signatory.is_some())
            .finish()
    }
}

/// Drives the startup-selected configuration document through its
/// activation lifecycle and centralizes the policy derived from it.
///
/// The activation phase is derived from the persisted
/// [`config_store::DocumentState`]: a `Pending` document is *activating*
/// during this startup — its canonical values are forced into the database
/// and, once every service is up, the record is committed `Applied`. An
/// `Applied` document keeps RPC-managed canonical values.
#[derive(Debug, Clone)]
struct ConfigurationActivation {
    service: config_service::ConfigurationService,
    phase: ActivationPhase,
}

/// Phase of the document being activated by this startup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActivationPhase {
    /// The document was never served by a daemon: force its canonical
    /// values and commit `revision` as applied once all services are up.
    Pending {
        /// Revision expected to be committed by this startup.
        revision: u64,
    },
    /// The document was served by a previous daemon run.
    Applied,
}

impl ConfigurationActivation {
    fn new(
        service: config_service::ConfigurationService,
        state: config_store::DocumentState,
        revision: u64,
    ) -> Self {
        let phase = match state {
            config_store::DocumentState::Pending => ActivationPhase::Pending { revision },
            config_store::DocumentState::Applied => ActivationPhase::Applied,
        };
        Self { service, phase }
    }

    /// Whether startup forces the document's canonical mint info and quote
    /// TTL into the database instead of preserving RPC-managed values.
    fn forces_configuration(&self) -> bool {
        matches!(self.phase, ActivationPhase::Pending { .. })
    }

    /// Whether startup preserves RPC-managed canonical database values.
    fn preserves_database_values(&self, rpc_enabled: bool) -> bool {
        rpc_enabled && !self.forces_configuration()
    }

    /// Commits the document as applied now that every service is up.
    ///
    /// A document that was already applied is left untouched. A document
    /// replaced by a concurrent `config apply` during startup stays pending
    /// for the next restart.
    async fn mark_applied(&self) -> Result<()> {
        if let ActivationPhase::Pending { revision } = self.phase {
            if !self.service.mark_applied(revision).await? {
                tracing::info!(
                    "A newer configuration was stored during startup and remains unapplied for the next restart."
                );
            }
        }
        Ok(())
    }
}

#[cfg(feature = "management-rpc")]
#[derive(Debug, Clone)]
struct ConfigurationMutationGuard {
    service: config_service::ConfigurationService,
}

#[cfg(feature = "management-rpc")]
#[async_trait::async_trait]
impl cdk_mint_rpc::MintMutationGuard for ConfigurationMutationGuard {
    async fn check(&self) -> Result<(), cdk_mint_rpc::MintMutationGuardError> {
        match self.service.has_pending_configuration().await {
            Ok(true) => Err(cdk_mint_rpc::MintMutationGuardError::FailedPrecondition(
                "A configuration apply is pending; restart cdk-mintd before making management RPC changes"
                    .to_owned(),
            )),
            Ok(false) => Ok(()),
            Err(error) => Err(cdk_mint_rpc::MintMutationGuardError::Internal(format!(
                "Could not inspect the stored configuration state: {error}"
            ))),
        }
    }
}

#[cfg(all(feature = "management-rpc", feature = "bdk"))]
type ConfiguredWalletInfoProvider = Option<cdk_mint_rpc::DynWalletInfoProvider>;
#[cfg(not(all(feature = "management-rpc", feature = "bdk")))]
type ConfiguredWalletInfoProvider = ();

#[cfg(all(feature = "management-rpc", feature = "bdk"))]
#[derive(Clone)]
struct BdkWalletInfoProvider {
    bdk: Arc<cdk_bdk::CdkBdk>,
}

#[cfg(all(feature = "management-rpc", feature = "bdk"))]
#[async_trait::async_trait]
impl cdk_mint_rpc::WalletInfoProvider for BdkWalletInfoProvider {
    async fn create_deposit_address(
        &self,
    ) -> std::result::Result<String, cdk_mint_rpc::WalletInfoError> {
        self.bdk
            .create_operator_deposit_address()
            .await
            .map_err(|err| cdk_mint_rpc::WalletInfoError::new(err.to_string()))
    }

    async fn get_balance(
        &self,
    ) -> std::result::Result<cdk_mint_rpc::wallet::GetBalanceResponse, cdk_mint_rpc::WalletInfoError>
    {
        let balance = self.bdk.wallet_balance().await;

        Ok(cdk_mint_rpc::wallet::GetBalanceResponse {
            confirmed_sat: balance.confirmed_sat,
            trusted_pending_sat: balance.trusted_pending_sat,
            untrusted_pending_sat: balance.untrusted_pending_sat,
            immature_sat: balance.immature_sat,
            trusted_spendable_sat: balance.trusted_spendable_sat,
            total_sat: balance.total_sat,
            network: balance.network,
            synced_height: balance.synced_height,
        })
    }

    async fn list_transactions(
        &self,
        offset: usize,
        limit: usize,
    ) -> std::result::Result<cdk_mint_rpc::WalletTransactionPage, cdk_mint_rpc::WalletInfoError>
    {
        let page = self
            .bdk
            .wallet_transactions(offset, limit)
            .await
            .map_err(|err| cdk_mint_rpc::WalletInfoError::new(err.to_string()))?;

        Ok(cdk_mint_rpc::WalletTransactionPage {
            transactions: page
                .items
                .into_iter()
                .map(|transaction| cdk_mint_rpc::wallet::WalletTransaction {
                    txid: transaction.txid,
                    inputs: transaction
                        .inputs
                        .into_iter()
                        .map(|input| cdk_mint_rpc::wallet::WalletTransactionInput {
                            txid: input.txid,
                            vout: input.vout,
                            amount_sat: input.amount_sat,
                            address: input.address,
                        })
                        .collect(),
                    outputs: transaction
                        .outputs
                        .into_iter()
                        .map(|output| cdk_mint_rpc::wallet::WalletTransactionOutput {
                            vout: output.vout,
                            address: output.address,
                            amount_sat: output.amount_sat,
                            quote_id: output.quote_id,
                        })
                        .collect(),
                    received_sat: transaction.received_sat,
                    sent_sat: transaction.sent_sat,
                    fee_sat: transaction.fee_sat,
                    balance_delta_sat: transaction.balance_delta_sat,
                    confirmation_height: transaction.confirmation_height,
                    confirmation_time: transaction.confirmation_time,
                    first_seen: transaction.first_seen,
                })
                .collect(),
            total: page.total,
        })
    }

    async fn list_addresses(
        &self,
        offset: usize,
        limit: usize,
    ) -> std::result::Result<cdk_mint_rpc::WalletAddressPage, cdk_mint_rpc::WalletInfoError> {
        let page = self
            .bdk
            .wallet_addresses(offset, limit)
            .await
            .map_err(|err| cdk_mint_rpc::WalletInfoError::new(err.to_string()))?;

        Ok(cdk_mint_rpc::WalletAddressPage {
            addresses: page
                .items
                .into_iter()
                .map(|address| cdk_mint_rpc::wallet::WalletAddress {
                    address: address.address,
                    keychain: match address.keychain {
                        cdk_bdk::WalletKeychain::External => {
                            cdk_mint_rpc::wallet::KeychainKind::External.into()
                        }
                        cdk_bdk::WalletKeychain::Internal => {
                            cdk_mint_rpc::wallet::KeychainKind::Internal.into()
                        }
                    },
                    derivation_index: address.derivation_index,
                    used: address.used,
                    balance_sat: address.balance_sat,
                    confirmed_balance_sat: address.confirmed_balance_sat,
                })
                .collect(),
            total: page.total,
        })
    }
}

#[cfg(all(feature = "management-rpc", feature = "bdk"))]
fn no_wallet_info_provider() -> ConfiguredWalletInfoProvider {
    None
}

#[cfg(not(all(feature = "management-rpc", feature = "bdk")))]
fn no_wallet_info_provider() -> ConfiguredWalletInfoProvider {}

fn extract_supported_payment_methods(mint_info: &cdk::nuts::MintInfo) -> Vec<String> {
    let mut seen = HashSet::new();
    mint_info
        .nuts
        .nut04
        .methods
        .iter()
        .map(|method| method.method.to_string())
        .filter(|method| seen.insert(method.clone()))
        .collect()
}

#[cfg(feature = "cln")]
fn expand_path(path: &str) -> Option<PathBuf> {
    if path == "~" {
        return home::home_dir();
    }

    if let Some(remainder) = path.strip_prefix("~/") {
        return home::home_dir().map(|home_dir| home_dir.join(remainder));
    }

    Some(PathBuf::from(path))
}

/// Performs the initial setup for the application, including configuring tracing,
/// parsing CLI arguments, setting up the working directory, loading settings,
/// and initializing the database connection.
async fn initial_setup(
    work_dir: &Path,
    settings: &config::Settings,
    db_password: Option<String>,
) -> Result<(
    DynMintDatabase,
    Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
    Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync>,
    Arc<dyn KVStoreCompareAndSwap<Err = cdk_database::Error> + Send + Sync>,
)> {
    tracing::info!("Initializing database...");
    let (localstore, keystore, kv, configuration_store) =
        setup_database(settings, work_dir, db_password).await?;
    tracing::info!("Database initialized successfully");
    Ok((localstore, keystore, kv, configuration_store))
}

/// Operator intent for the mint database targeted by `config init`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MintInitializationMode {
    /// Initialize a database that has never served a mint.
    New,
    /// Import configuration into a database containing an existing mint.
    Existing,
}

/// Operator intent for BDK wallet persistence during configuration changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BdkWalletPolicy {
    /// Require a matching, initialized BDK wallet database.
    RequireExisting,
    /// Permit creation of a BDK wallet only when its database is absent.
    AllowNew,
}

/// Sets up and initializes a tracing subscriber with custom log filtering.
/// Logs can be configured to output to stdout only, file only, or both.
/// Returns a guard that must be kept alive and properly dropped on shutdown.
pub fn setup_tracing(
    work_dir: &Path,
    logging_config: &config::LoggingConfig,
) -> Result<Option<tracing_appender::non_blocking::WorkerGuard>> {
    let default_filter = "debug";
    let hyper_filter = "hyper=warn,rustls=warn,reqwest=warn";
    let h2_filter = "h2=warn";
    let tower_filter = "tower=warn";
    let tower_http = "tower_http=warn";
    let rustls = "rustls=warn";
    let tungstenite = "tungstenite=warn";
    let tokio_postgres = "tokio_postgres=warn";

    let env_filter = EnvFilter::new(format!(
        "{default_filter},{hyper_filter},{h2_filter},{tower_filter},{tower_http},{rustls},{tungstenite},{tokio_postgres}"
    ));

    use config::LoggingOutput;
    match logging_config.output {
        LoggingOutput::Stderr => {
            // Console output only (stderr)
            let console_level = logging_config
                .console_level
                .as_deref()
                .unwrap_or("info")
                .parse::<tracing::Level>()
                .unwrap_or(tracing::Level::INFO);

            let stderr = std::io::stderr.with_max_level(console_level);

            tracing_subscriber::fmt()
                .with_env_filter(env_filter)
                .with_ansi(false)
                .with_writer(stderr)
                .init();

            tracing::info!("Logging initialized: console only ({}+)", console_level);
            Ok(None)
        }
        LoggingOutput::File => {
            // File output only
            let file_level = logging_config
                .file_level
                .as_deref()
                .unwrap_or("debug")
                .parse::<tracing::Level>()
                .unwrap_or(tracing::Level::DEBUG);

            // Create logs directory in work_dir if it doesn't exist
            let logs_dir = work_dir.join("logs");
            std::fs::create_dir_all(&logs_dir)?;

            // Set up file appender with daily rotation
            let file_appender = rolling::daily(&logs_dir, "cdk-mintd.log");
            let (non_blocking_appender, guard) = non_blocking(file_appender);

            let file_writer = non_blocking_appender.with_max_level(file_level);

            tracing_subscriber::fmt()
                .with_env_filter(env_filter)
                .with_ansi(false)
                .with_writer(file_writer)
                .init();

            tracing::info!(
                "Logging initialized: file only at {}/cdk-mintd.log ({}+)",
                logs_dir.display(),
                file_level
            );
            Ok(Some(guard))
        }
        LoggingOutput::Both => {
            // Both console and file output (stderr + file)
            let console_level = logging_config
                .console_level
                .as_deref()
                .unwrap_or("info")
                .parse::<tracing::Level>()
                .unwrap_or(tracing::Level::INFO);
            let file_level = logging_config
                .file_level
                .as_deref()
                .unwrap_or("debug")
                .parse::<tracing::Level>()
                .unwrap_or(tracing::Level::DEBUG);

            // Create logs directory in work_dir if it doesn't exist
            let logs_dir = work_dir.join("logs");
            std::fs::create_dir_all(&logs_dir)?;

            // Set up file appender with daily rotation
            let file_appender = rolling::daily(&logs_dir, "cdk-mintd.log");
            let (non_blocking_appender, guard) = non_blocking(file_appender);

            // Combine console output (stderr) and file output
            let stderr = std::io::stderr.with_max_level(console_level);
            let file_writer = non_blocking_appender.with_max_level(file_level);

            tracing_subscriber::fmt()
                .with_env_filter(env_filter)
                .with_ansi(false)
                .with_writer(stderr.and(file_writer))
                .init();

            tracing::info!(
                "Logging initialized: console ({}+) and file at {}/cdk-mintd.log ({}+)",
                console_level,
                logs_dir.display(),
                file_level
            );
            Ok(Some(guard))
        }
    }
}

/// Retrieves the work directory based on command-line arguments, environment variables, or system defaults.
pub async fn get_work_directory(args: &CLIArgs) -> Result<PathBuf> {
    let work_dir = if let Some(work_dir) = &args.work_dir {
        tracing::info!("Using work dir from cmd arg");
        work_dir.clone()
    } else if let Ok(env_work_dir) = env::var(ENV_WORK_DIR) {
        tracing::info!("Using work dir from env var");
        env_work_dir.into()
    } else {
        work_dir()?
    };
    tracing::info!("Using work dir: {}", work_dir.display());
    Ok(work_dir)
}

/// Loads the application settings based on a configuration file and environment variables.
pub fn load_settings(work_dir: &Path, config_path: Option<PathBuf>) -> Result<config::Settings> {
    let settings = load_settings_from_sources(work_dir, config_path)?;
    validate_settings(&settings)?;

    Ok(settings)
}

fn load_settings_from_sources(
    work_dir: &Path,
    config_path: Option<PathBuf>,
) -> Result<config::Settings> {
    // get config file name from args
    let config_file_arg = match config_path {
        Some(c) => c,
        None => work_dir.join("config.toml"),
    };

    let mut settings = if config_file_arg.exists() {
        config::Settings::try_new(Some(config_file_arg.clone()))
            .with_context(|| format!("Failed to read config file {}", config_file_arg.display()))?
    } else {
        tracing::info!("Config file does not exist. Attempting to read env vars");
        config::Settings::default()
    };
    // This check for any settings defined in ENV VARs
    // ENV VARS will take **priority** over those in the config
    settings.from_env()
}

pub(crate) fn validate_settings(settings: &config::Settings) -> Result<()> {
    validate_payment_backends(settings)?;
    settings
        .validate_backend_pairing()
        .map_err(anyhow::Error::msg)?;
    validate_listen_config(settings)?;
    validate_signing_config(settings)?;
    validate_payment_backend_config(settings)?;
    validate_onchain_config(settings)?;
    validate_database_config(settings)?;
    validate_auth_config(settings)?;
    validate_management_rpc_config(settings)?;
    validate_prometheus_config(settings)?;

    Ok(())
}

fn validate_payment_backends(settings: &config::Settings) -> Result<()> {
    let has_payment_backend = settings
        .payment_backend
        .iter()
        .any(|backend| backend.backend != PaymentBackendType::None);
    let has_onchain_backend = settings
        .onchain
        .as_ref()
        .is_some_and(|onchain| onchain.onchain_backend != config::OnchainBackend::None);

    if !has_payment_backend && !has_onchain_backend {
        bail!("At least one payment backend must be configured");
    }

    Ok(())
}

fn validate_database_config(settings: &config::Settings) -> Result<()> {
    if settings.database.engine == DatabaseEngine::Postgres {
        let pg_config = settings.database.postgres.as_ref().ok_or_else(|| {
            anyhow!("PostgreSQL configuration is required when using PostgreSQL engine")
        })?;

        if pg_config.url.is_empty() {
            bail!("PostgreSQL URL is required. Set it in config file [database.postgres] section or via CDK_MINTD_POSTGRES_URL/CDK_MINTD_DATABASE_URL environment variable");
        }
    }

    Ok(())
}

fn validate_listen_config(settings: &config::Settings) -> Result<()> {
    format!(
        "{}:{}",
        settings.info.listen_host, settings.info.listen_port
    )
    .parse::<SocketAddr>()
    .map_err(|err| {
        anyhow!(
            "Invalid mint listen address [info].listen_host/[info].listen_port ({}:{}): {err}",
            settings.info.listen_host,
            settings.info.listen_port
        )
    })?;

    Ok(())
}

fn validate_signing_config(settings: &config::Settings) -> Result<()> {
    const MIN_SEED_BYTES: usize = 32;

    if let Some(signatory) = settings.enabled_signatory() {
        let has_local_seed = settings
            .info
            .seed
            .as_ref()
            .is_some_and(|seed| !seed.is_empty());
        let has_local_mnemonic = settings
            .info
            .mnemonic
            .as_ref()
            .is_some_and(|mnemonic| !mnemonic.is_empty());
        if has_local_seed || has_local_mnemonic {
            bail!(
                "Remote signatory configuration cannot include [info].seed or [info].mnemonic; \
                 keep private signing material on the signatory host"
            );
        }

        if signatory.tls_dir.is_none() && !signatory.allow_insecure {
            bail!(
                "gRPC signatory TLS is not configured. Set [signatory].tls_dir or \
                 [signatory].allow_insecure = true to connect without TLS"
            );
        }

        return Ok(());
    }

    let seed = settings.info.seed.as_ref();
    let mnemonic = settings
        .info
        .mnemonic
        .as_ref()
        .filter(|value| !value.is_empty());

    if let Some(seed) = seed {
        if seed.is_empty() {
            bail!("Seed in [info].seed must not be empty");
        }
        if seed.len() < MIN_SEED_BYTES {
            bail!(
                "Seed in [info].seed is too short ({} bytes); require at least {MIN_SEED_BYTES} bytes",
                seed.len()
            );
        }
        return Ok(());
    }

    if let Some(mnemonic) = mnemonic {
        Mnemonic::from_str(mnemonic)
            .map_err(|err| anyhow!("Invalid mnemonic in [info].mnemonic: {err}"))?;
        return Ok(());
    }

    bail!("No signing source configured. Set [info].mnemonic or [info].seed to an env:/file: secret reference, or enable [signatory]");
}

fn validate_payment_backend_config(settings: &config::Settings) -> Result<()> {
    // `validate_payment_backends` already permits valid on-chain-only configs,
    // so an empty `payment_backend` simply skips the backend-specific checks below.
    for payment_backend in &settings.payment_backend {
        if payment_backend.min_mint > payment_backend.max_mint {
            bail!("Payment backend min_mint cannot be greater than max_mint");
        }
        if payment_backend.min_melt > payment_backend.max_melt {
            bail!("Payment backend min_melt cannot be greater than max_melt");
        }

        match payment_backend.backend {
            PaymentBackendType::None => {}
            #[cfg(feature = "cln")]
            PaymentBackendType::Cln => {
                let cln = settings.cln.as_ref().ok_or_else(|| {
                    anyhow!("CLN backend selected but [cln] config section is missing")
                })?;
                if cln.rpc_path.as_os_str().is_empty() {
                    bail!("CLN rpc_path must be set in [cln].rpc_path");
                }
            }
            #[cfg(feature = "lnd")]
            PaymentBackendType::Lnd => {
                let lnd = settings.lnd.as_ref().ok_or_else(|| {
                    anyhow!("LND backend selected but [lnd] config section is missing")
                })?;
                if lnd.address.is_empty() {
                    bail!("LND address must be set in [lnd].address");
                }
                if lnd.cert_file.as_os_str().is_empty() {
                    bail!("LND cert_file must be set in [lnd].cert_file");
                }
                if lnd.macaroon_file.as_os_str().is_empty() {
                    bail!("LND macaroon_file must be set in [lnd].macaroon_file");
                }
            }
            #[cfg(feature = "fakewallet")]
            PaymentBackendType::FakeWallet => {
                let fake_wallet = settings.fake_wallet.as_ref().ok_or_else(|| {
                    anyhow!(
                        "Fake wallet backend selected but [fake_wallet] config section is missing"
                    )
                })?;
                if fake_wallet.supported_units.is_empty() {
                    bail!("Fake wallet supported_units must contain at least one unit in [fake_wallet].supported_units");
                }
                if fake_wallet.min_delay_time > fake_wallet.max_delay_time {
                    bail!("Fake wallet min_delay_time cannot be greater than max_delay_time");
                }
            }
            #[cfg(feature = "grpc-processor")]
            PaymentBackendType::GrpcProcessor => {
                let grpc_processor = settings.grpc_processor.as_ref().ok_or_else(|| {
                    anyhow!(
                        "gRPC payment processor backend selected but [grpc_processor] config section is missing"
                    )
                })?;
                if grpc_processor.supported_units.is_empty() {
                    bail!("gRPC payment processor supported_units must contain at least one unit in [grpc_processor].supported_units");
                }
                if grpc_processor.address.is_empty() {
                    bail!("gRPC payment processor address must be set in [grpc_processor].address");
                }
            }
            #[cfg(feature = "ldk-node")]
            PaymentBackendType::LdkNode => {
                if settings.ldk_node.is_none() {
                    bail!("LDK Node backend selected but [ldk_node] config section is missing");
                }
            }
        }
    }

    Ok(())
}

fn validate_onchain_config(settings: &config::Settings) -> Result<()> {
    let Some(onchain) = settings.onchain.as_ref() else {
        return Ok(());
    };

    if onchain.min_mint > onchain.max_mint {
        bail!("On-chain min_mint cannot be greater than max_mint");
    }
    if onchain.min_melt > onchain.max_melt {
        bail!("On-chain min_melt cannot be greater than max_melt");
    }

    match onchain.onchain_backend {
        config::OnchainBackend::None => {}
        #[cfg(feature = "bdk")]
        config::OnchainBackend::Bdk => {
            let bdk = settings.bdk.as_ref().ok_or_else(|| {
                anyhow!("BDK onchain backend selected but [bdk] config section is missing")
            })?;
            bdk.validate().map_err(anyhow::Error::msg)?;
        }
        #[cfg(feature = "fakewallet")]
        config::OnchainBackend::FakeWallet => {
            if settings.fake_wallet.is_none() {
                bail!(
                    "Fake wallet onchain backend selected but [fake_wallet] config section is missing"
                );
            }
        }
    }

    Ok(())
}

fn validate_auth_config(settings: &config::Settings) -> Result<()> {
    let Some(auth) = settings.auth.as_ref() else {
        return Ok(());
    };

    if auth.openid_discovery.is_empty() {
        bail!("Auth openid_discovery must be set in [auth].openid_discovery");
    }
    if auth.openid_client_id.is_empty() {
        bail!("Auth openid_client_id must be set in [auth].openid_client_id");
    }

    if settings.database.engine == DatabaseEngine::Postgres {
        let auth_db_config = settings.auth_database.as_ref().ok_or_else(|| {
            anyhow!("Auth database configuration is required when using PostgreSQL with authentication. Set [auth_database]")
        })?;
        let auth_pg_config = auth_db_config.postgres.as_ref().ok_or_else(|| {
            anyhow!("PostgreSQL auth database configuration is required when using PostgreSQL with authentication. Set [auth_database.postgres]")
        })?;
        if auth_pg_config.url.is_empty() {
            bail!("Auth database PostgreSQL URL is required. Set [auth_database.postgres].url to an env: or file: secret reference");
        }
    }

    Ok(())
}

fn validate_management_rpc_config(settings: &config::Settings) -> Result<()> {
    #[cfg(not(feature = "management-rpc"))]
    let _ = settings;

    #[cfg(feature = "management-rpc")]
    if let Some(rpc_settings) = settings.mint_management_rpc.as_ref() {
        if rpc_settings.enabled {
            let address = rpc_settings.address.as_deref().unwrap_or("127.0.0.1");
            let port = rpc_settings.port.unwrap_or(8086);
            format!("{address}:{port}")
                .parse::<SocketAddr>()
                .map_err(|err| {
                    anyhow!(
                        "Invalid mint management RPC address [mint_management_rpc].address/[mint_management_rpc].port ({address}:{port}): {err}"
                    )
                })?;
        }
    }

    Ok(())
}

fn validate_prometheus_config(settings: &config::Settings) -> Result<()> {
    #[cfg(not(feature = "prometheus"))]
    let _ = settings;

    #[cfg(feature = "prometheus")]
    if let Some(prometheus_settings) = settings.prometheus.as_ref() {
        if prometheus_settings.enabled {
            let address = prometheus_settings
                .address
                .as_deref()
                .unwrap_or("127.0.0.1");
            let port = prometheus_settings.port.unwrap_or(9000);
            format!("{address}:{port}")
                .parse::<SocketAddr>()
                .map_err(|err| {
                    anyhow!(
                        "Invalid Prometheus address [prometheus].address/[prometheus].port ({address}:{port}): {err}"
                    )
                })?;
        }
    }

    Ok(())
}

/// Loads settings from command line arguments, environment variables, and optional seed file.
pub fn load_settings_from_args(work_dir: &Path, args: &CLIArgs) -> Result<config::Settings> {
    let mut settings = load_settings_from_sources(work_dir, args.config.clone())?;

    if let Some(seed_file) = args.seed_file.as_deref() {
        apply_seed_file(&mut settings, seed_file)?;
    }

    validate_settings(&settings)?;

    Ok(settings)
}

/// Overrides the configured mint and active payment backend mnemonic with a seed file.
pub fn apply_seed_file(settings: &mut config::Settings, seed_file: &Path) -> Result<()> {
    let mnemonic = std::fs::read_to_string(seed_file)
        .with_context(|| format!("Failed to read seed file {}", seed_file.display()))?;
    let mnemonic = mnemonic.trim();

    if mnemonic.is_empty() {
        bail!("Seed file {} is empty", seed_file.display());
    }

    Mnemonic::parse(mnemonic)
        .with_context(|| format!("Invalid seed phrase in seed file {}", seed_file.display()))?;

    settings.info.seed = None;
    settings.info.mnemonic = Some(mnemonic.to_owned());

    #[cfg(feature = "bdk")]
    if settings
        .onchain
        .as_ref()
        .is_some_and(|onchain| onchain.onchain_backend == config::OnchainBackend::Bdk)
    {
        let mut bdk = settings.bdk.clone().unwrap_or_default();
        bdk.mnemonic = Some(mnemonic.to_owned());
        settings.bdk = Some(bdk);
    }

    #[cfg(feature = "ldk-node")]
    if settings
        .payment_backend
        .iter()
        .any(|backend| backend.backend == PaymentBackendType::LdkNode)
    {
        let mut ldk_node = settings.ldk_node.clone().unwrap_or_default();
        ldk_node.ldk_node_mnemonic = Some(mnemonic.to_owned());
        settings.ldk_node = Some(ldk_node);
    }

    Ok(())
}

async fn setup_database(
    settings: &config::Settings,
    _work_dir: &Path,
    _db_password: Option<String>,
) -> Result<(
    DynMintDatabase,
    Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
    Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync>,
    Arc<dyn KVStoreCompareAndSwap<Err = cdk_database::Error> + Send + Sync>,
)> {
    tracing::info!("Using database engine: {:?}", settings.database.engine);
    match settings.database.engine {
        #[cfg(feature = "sqlite")]
        DatabaseEngine::Sqlite => {
            let db = setup_sqlite_database(_work_dir, _db_password).await?;
            let localstore: Arc<dyn MintDatabase<cdk_database::Error> + Send + Sync> = db.clone();
            let kv: Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync> = db.clone();
            let configuration_store: Arc<
                dyn KVStoreCompareAndSwap<Err = cdk_database::Error> + Send + Sync,
            > = db.clone();
            let keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync> = db;
            Ok((localstore, keystore, kv, configuration_store))
        }
        #[cfg(feature = "postgres")]
        DatabaseEngine::Postgres => {
            // Get the PostgreSQL configuration, ensuring it exists
            let pg_config = settings.database.postgres.as_ref().ok_or_else(|| {
                anyhow!("PostgreSQL configuration is required when using PostgreSQL engine")
            })?;

            if pg_config.url.is_empty() {
                bail!("PostgreSQL URL is required. Set it in config file [database.postgres] section or via CDK_MINTD_POSTGRES_URL/CDK_MINTD_DATABASE_URL environment variable");
            }

            #[cfg(feature = "postgres")]
            let db_config = PgConfig::new(
                pg_config.url.as_str(),
                pg_config.tls_mode.as_deref(),
                pg_config.max_connections,
                pg_config.connection_timeout_seconds,
            );
            #[cfg(feature = "postgres")]
            let pg_db = Arc::new(MintPgDatabase::new(db_config).await?);
            tracing::info!("PostgreSQL database connection established");
            #[cfg(feature = "postgres")]
            let localstore: Arc<dyn MintDatabase<cdk_database::Error> + Send + Sync> =
                pg_db.clone();
            #[cfg(feature = "postgres")]
            let kv: Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync> = pg_db.clone();
            #[cfg(feature = "postgres")]
            let configuration_store: Arc<
                dyn KVStoreCompareAndSwap<Err = cdk_database::Error> + Send + Sync,
            > = pg_db.clone();
            #[cfg(feature = "postgres")]
            let keystore: Arc<
                dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync,
            > = pg_db;
            #[cfg(feature = "postgres")]
            return Ok((localstore, keystore, kv, configuration_store));

            #[cfg(not(feature = "postgres"))]
            bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
        }
        #[cfg(not(feature = "sqlite"))]
        DatabaseEngine::Sqlite => {
            bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
        }
        #[cfg(not(feature = "postgres"))]
        DatabaseEngine::Postgres => {
            bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
        }
    }
}

#[cfg(feature = "sqlite")]
async fn setup_sqlite_database(
    work_dir: &Path,
    _password: Option<String>,
) -> Result<Arc<MintSqliteDatabase>> {
    let sql_db_path = work_dir.join("cdk-mintd.sqlite");
    tracing::info!("SQLite database path: {}", sql_db_path.display());

    #[cfg(not(feature = "sqlcipher"))]
    let db = MintSqliteDatabase::new(&sql_db_path).await?;
    #[cfg(feature = "sqlcipher")]
    let db = {
        // Get password from command line arguments for sqlcipher
        let password = _password
            .ok_or_else(|| anyhow!("Password required when sqlcipher feature is enabled"))?;
        tracing::info!("Using SQLCipher encryption for SQLite database");
        MintSqliteDatabase::new((sql_db_path, password)).await?
    };

    tracing::info!("SQLite database initialized successfully");
    Ok(Arc::new(db))
}

/**
 * Configures a `MintBuilder` instance with provided settings and initializes
 * routers for the configured payment backends.
 */
async fn configure_mint_builder_with_wallet_info(
    settings: &config::Settings,
    mint_builder: MintBuilder,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    work_dir: &Path,
    kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
) -> Result<(MintBuilder, ConfiguredWalletInfoProvider)> {
    settings
        .validate_backend_pairing()
        .map_err(anyhow::Error::msg)?;

    // Configure basic mint information
    let mint_builder = configure_basic_info(settings, mint_builder);

    // Check that fake wallet is not used on mainnet
    #[cfg(feature = "fakewallet")]
    if settings
        .payment_backend
        .iter()
        .any(|backend| backend.backend == PaymentBackendType::FakeWallet)
    {
        if let Some(_onchain) = &settings.onchain {
            #[cfg(feature = "bdk")]
            if _onchain.onchain_backend == config::OnchainBackend::Bdk {
                if let Some(bdk) = &settings.bdk {
                    if let Some(network) = &bdk.network {
                        let network = network.to_lowercase();
                        if network == "mainnet" || network == "bitcoin" {
                            bail!("Fake wallet cannot be used as a payment backend when On-chain is configured for Mainnet");
                        }
                    }
                }
            }
        }
    }

    // Configure payment backends
    let mint_builder = configure_payment_backends(
        settings,
        mint_builder,
        runtime.clone(),
        work_dir,
        kv_store.clone(),
    )
    .await?;

    // Configure onchain backend
    let (mint_builder, wallet_info_provider) = configure_onchain_backend_with_wallet_info(
        settings,
        mint_builder,
        runtime,
        work_dir,
        kv_store,
    )
    .await?;

    // Extract configured payment methods from mint_builder
    let mint_info = mint_builder.current_mint_info();
    let payment_methods = extract_supported_payment_methods(&mint_info);

    // Enable batch minting by default for all supported methods
    let mint_builder = mint_builder
        .with_batch_minting(Some(DEFAULT_BATCH_MINT_SIZE), Some(payment_methods.clone()));

    // Configure caching with payment methods
    let mint_builder = configure_cache(settings, mint_builder, &payment_methods).await?;

    // Configure transaction limits
    let mint_builder =
        mint_builder.with_limits(settings.limits.max_inputs, settings.limits.max_outputs);

    // Verify at least one payment processor is configured
    if mint_builder
        .current_mint_info()
        .nuts
        .nut04
        .methods
        .is_empty()
    {
        bail!("At least one payment backend must be configured");
    }

    Ok((mint_builder, wallet_info_provider))
}

#[cfg(test)]
async fn configure_mint_builder(
    settings: &config::Settings,
    mint_builder: MintBuilder,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    work_dir: &Path,
    kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
) -> Result<MintBuilder> {
    Ok(
        configure_mint_builder_with_wallet_info(
            settings,
            mint_builder,
            runtime,
            work_dir,
            kv_store,
        )
        .await?
        .0,
    )
}

/// Configures basic mint information (name, contact info, descriptions, etc.)
fn configure_basic_info(settings: &config::Settings, mint_builder: MintBuilder) -> MintBuilder {
    // Add contact information
    let mut contacts = Vec::new();
    if let Some(nostr_key) = &settings.mint_info.contact_nostr_public_key {
        if !nostr_key.is_empty() {
            contacts.push(ContactInfo::new("nostr".to_string(), nostr_key.to_string()));
        }
    }
    if let Some(email) = &settings.mint_info.contact_email {
        if !email.is_empty() {
            contacts.push(ContactInfo::new("email".to_string(), email.to_string()));
        }
    }

    // Add version information
    let mint_version = MintVersion::new(
        "cdk-mintd".to_string(),
        CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
    );

    // Configure mint builder with basic info
    let mut builder = mint_builder.with_version(mint_version);

    // Only set name if it's not empty
    if !settings.mint_info.name.is_empty() {
        builder = builder.with_name(settings.mint_info.name.clone());
    }

    // Only set description if it's not empty
    if !settings.mint_info.description.is_empty() {
        builder = builder.with_description(settings.mint_info.description.clone());
    }

    // Add optional information
    if let Some(long_description) = &settings.mint_info.description_long {
        if !long_description.is_empty() {
            builder = builder.with_long_description(long_description.to_string());
        }
    }

    for contact in contacts {
        builder = builder.with_contact_info(contact);
    }

    if let Some(pubkey) = settings.mint_info.pubkey {
        builder = builder.with_pubkey(pubkey);
    }

    if let Some(icon_url) = &settings.mint_info.icon_url {
        if !icon_url.is_empty() {
            builder = builder.with_icon_url(icon_url.to_string());
        }
    }

    if let Some(motd) = &settings.mint_info.motd {
        if !motd.is_empty() {
            builder = builder.with_motd(motd.to_string());
        }
    }

    if let Some(tos_url) = &settings.mint_info.tos_url {
        if !tos_url.is_empty() {
            builder = builder.with_tos_url(tos_url.to_string());
        }
    }

    builder = builder.with_keyset_v2(settings.info.use_keyset_v2);

    builder
}
/// Configures payment backends based on the specified backend types
async fn configure_payment_backends(
    settings: &config::Settings,
    mut mint_builder: MintBuilder,
    _runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    work_dir: &Path,
    _kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
) -> Result<MintBuilder> {
    if settings.payment_backend.is_empty() {
        tracing::info!("No payment backend configured");
        return Ok(mint_builder);
    }

    #[cfg(feature = "fakewallet")]
    let mut configure_fake_wallet_keyset_rotations = false;

    for backend_entry in &settings.payment_backend {
        let mint_melt_limits = MintMeltLimits {
            mint_min: backend_entry.min_mint,
            mint_max: backend_entry.max_mint,
            melt_min: backend_entry.min_melt,
            melt_max: backend_entry.max_melt,
        };

        tracing::debug!(
            "Payment backend: {:?} (unit: {:?})",
            backend_entry.backend,
            backend_entry.unit
        );

        match backend_entry.backend {
            #[cfg(feature = "cln")]
            PaymentBackendType::Cln => {
                let cln_settings = settings.cln.clone().ok_or_else(|| {
                    anyhow!("CLN backend selected but [cln] config section is missing")
                })?;
                let cln = cln_settings
                    .setup(
                        settings,
                        cdk::nuts::CurrencyUnit::Msat,
                        None,
                        work_dir,
                        _kv_store.clone(),
                    )
                    .await?;
                #[cfg(feature = "prometheus")]
                let cln = MetricsMintPayment::new(cln);

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    backend_entry.unit.clone(),
                    mint_melt_limits,
                    Arc::new(cln),
                )
                .await?;
            }
            #[cfg(feature = "lnd")]
            PaymentBackendType::Lnd => {
                let lnd_settings = settings.lnd.clone().ok_or_else(|| {
                    anyhow!("LND backend selected but [lnd] config section is missing")
                })?;
                let lnd = lnd_settings
                    .setup(
                        settings,
                        cdk::nuts::CurrencyUnit::Msat,
                        None,
                        work_dir,
                        _kv_store.clone(),
                    )
                    .await?;
                #[cfg(feature = "prometheus")]
                let lnd = MetricsMintPayment::new(lnd);

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    backend_entry.unit.clone(),
                    mint_melt_limits,
                    Arc::new(lnd),
                )
                .await?;
            }
            #[cfg(feature = "fakewallet")]
            PaymentBackendType::FakeWallet => {
                let fake_wallet = settings.fake_wallet.clone().ok_or_else(|| {
                    anyhow!(
                        "Fake wallet backend selected but [fake_wallet] config section is missing"
                    )
                })?;
                tracing::info!("Using fake wallet: {:?}", fake_wallet);

                let fake = fake_wallet
                    .setup(
                        settings,
                        backend_entry.unit.clone(),
                        None,
                        work_dir,
                        _kv_store.clone(),
                    )
                    .await?;
                #[cfg(feature = "prometheus")]
                let fake = MetricsMintPayment::new(fake);

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    backend_entry.unit.clone(),
                    mint_melt_limits,
                    Arc::new(fake),
                )
                .await?;

                configure_fake_wallet_keyset_rotations = true;
            }
            #[cfg(feature = "grpc-processor")]
            PaymentBackendType::GrpcProcessor => {
                let grpc_processor = settings.grpc_processor.clone().ok_or_else(|| {
                    anyhow!(
                        "gRPC payment processor backend selected but [grpc_processor] config section is missing"
                    )
                })?;

                tracing::info!(
                    "Attempting to start with gRPC payment processor at {}:{}.",
                    grpc_processor.address,
                    grpc_processor.port
                );

                let processor = grpc_processor
                    .setup(settings, backend_entry.unit.clone(), None, work_dir, None)
                    .await?;
                #[cfg(feature = "prometheus")]
                let processor = MetricsMintPayment::new(processor);

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    backend_entry.unit.clone(),
                    mint_melt_limits,
                    Arc::new(processor),
                )
                .await?;
            }
            #[cfg(feature = "ldk-node")]
            PaymentBackendType::LdkNode => {
                let ldk_node_settings = settings.ldk_node.clone().ok_or_else(|| {
                    anyhow!("LDK Node backend selected but [ldk_node] config section is missing")
                })?;
                tracing::info!("Using LDK Node backend: {:?}", ldk_node_settings);

                let ldk_node = ldk_node_settings
                    .setup(
                        settings,
                        backend_entry.unit.clone(),
                        _runtime.clone(),
                        work_dir,
                        _kv_store.clone(),
                    )
                    .await?;

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    backend_entry.unit.clone(),
                    mint_melt_limits,
                    Arc::new(ldk_node),
                )
                .await?;
            }
            PaymentBackendType::None => {
                tracing::info!(
                    "No payment backend configured for unit {:?}",
                    backend_entry.unit
                );
            }
        };
    }

    #[cfg(feature = "fakewallet")]
    if configure_fake_wallet_keyset_rotations {
        let fake_wallet = settings.fake_wallet.as_ref().ok_or_else(|| {
            anyhow!("Fake wallet backend selected but [fake_wallet] config section is missing")
        })?;
        mint_builder = configure_fake_wallet_keyset_rotations_once(mint_builder, fake_wallet);
    }

    Ok(mint_builder)
}

#[cfg(feature = "fakewallet")]
fn configure_fake_wallet_keyset_rotations_once(
    mut mint_builder: MintBuilder,
    fake_wallet: &config::FakeWallet,
) -> MintBuilder {
    for rotation_cfg in &fake_wallet.keyset_rotations {
        use cdk::mint::KeysetRotation;

        let amounts = cdk::mint::UnitConfig::default().amounts;
        let final_expiry = if rotation_cfg.expired {
            Some(cdk::util::unix_time().saturating_sub(3600))
        } else {
            None
        };

        mint_builder = mint_builder.with_keyset_rotation(KeysetRotation {
            unit: rotation_cfg.unit.clone(),
            amounts,
            input_fee_ppk: rotation_cfg.input_fee_ppk,
            use_keyset_v2: rotation_cfg.version == "v2",
            final_expiry,
        });
    }

    mint_builder
}

/// Configures Onchain backend based on the specified backend type
async fn configure_onchain_backend_with_wallet_info(
    settings: &config::Settings,
    #[cfg_attr(not(feature = "bdk"), allow(unused_mut))] mut mint_builder: MintBuilder,
    _runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    _work_dir: &Path,
    _kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
) -> Result<(MintBuilder, ConfiguredWalletInfoProvider)> {
    use config::OnchainBackend;
    #[cfg(feature = "bdk")]
    use setup::OnchainBackendSetup;

    #[cfg(all(feature = "management-rpc", feature = "bdk"))]
    let mut wallet_info_provider = no_wallet_info_provider();

    if let Some(onchain_settings) = &settings.onchain {
        match onchain_settings.onchain_backend {
            #[cfg(feature = "bdk")]
            OnchainBackend::Bdk => {
                let mint_melt_limits = MintMeltLimits {
                    mint_min: onchain_settings.min_mint,
                    mint_max: onchain_settings.max_mint,
                    melt_min: onchain_settings.min_melt,
                    melt_max: onchain_settings.max_melt,
                };

                let bdk_settings = settings.bdk.clone().ok_or_else(|| {
                    anyhow!("BDK onchain backend selected but [bdk] config section is missing")
                })?;
                let bdk = bdk_settings
                    .setup(
                        settings,
                        cdk::nuts::CurrencyUnit::Sat,
                        None,
                        _work_dir,
                        _kv_store,
                    )
                    .await?;
                let bdk = Arc::new(bdk);

                #[cfg(feature = "management-rpc")]
                {
                    wallet_info_provider = Some(Arc::new(BdkWalletInfoProvider {
                        bdk: Arc::clone(&bdk),
                    }));
                }

                mint_builder = configure_backend_for_unit(
                    settings,
                    mint_builder,
                    cdk::nuts::CurrencyUnit::Sat,
                    mint_melt_limits,
                    bdk,
                )
                .await?;
            }
            OnchainBackend::None => {}
            #[cfg(feature = "fakewallet")]
            OnchainBackend::FakeWallet => {
                let has_payment_backend = settings
                    .payment_backend
                    .iter()
                    .any(|backend| backend.backend != PaymentBackendType::None);
                let has_real_payment_backend = settings.payment_backend.iter().any(|backend| {
                    !matches!(
                        backend.backend,
                        PaymentBackendType::None | PaymentBackendType::FakeWallet
                    )
                });

                if !has_payment_backend {
                    let mint_melt_limits = MintMeltLimits {
                        mint_min: onchain_settings.min_mint,
                        mint_max: onchain_settings.max_mint,
                        melt_min: onchain_settings.min_melt,
                        melt_max: onchain_settings.max_melt,
                    };
                    let fake_wallet = settings
                        .fake_wallet
                        .clone()
                        .ok_or_else(|| anyhow!("Fake wallet config section is missing"))?;

                    for unit in fake_wallet.clone().supported_units {
                        let fake = fake_wallet
                            .setup(settings, unit.clone(), None, _work_dir, _kv_store.clone())
                            .await?;
                        #[cfg(feature = "prometheus")]
                        let fake = MetricsMintPayment::new(fake);

                        mint_builder = configure_backend_for_methods(
                            settings,
                            mint_builder,
                            unit,
                            mint_melt_limits,
                            Arc::new(fake),
                            vec![PaymentMethod::Known(KnownMethod::Onchain)],
                        )
                        .await?;
                    }
                } else if has_real_payment_backend {
                    bail!(
                        "onchain_backend = \"fakewallet\" cannot be combined with a real payment backend"
                    );
                }
            }
        }
    }

    #[cfg(all(feature = "management-rpc", feature = "bdk"))]
    {
        Ok((mint_builder, wallet_info_provider))
    }
    #[cfg(not(all(feature = "management-rpc", feature = "bdk")))]
    {
        Ok((mint_builder, no_wallet_info_provider()))
    }
}

#[cfg(test)]
async fn configure_onchain_backend(
    settings: &config::Settings,
    mint_builder: MintBuilder,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    work_dir: &Path,
    kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
) -> Result<MintBuilder> {
    Ok(configure_onchain_backend_with_wallet_info(
        settings,
        mint_builder,
        runtime,
        work_dir,
        kv_store,
    )
    .await?
    .0)
}

/// Helper function to configure a mint builder with a payment backend for a specific currency unit
async fn configure_backend_for_unit(
    settings: &config::Settings,
    mint_builder: MintBuilder,
    unit: cdk::nuts::CurrencyUnit,
    mint_melt_limits: MintMeltLimits,
    backend: Arc<dyn MintPayment<Err = cdk_common::payment::Error> + Send + Sync>,
) -> Result<MintBuilder> {
    let payment_settings = backend.get_settings().await?;
    validate_backend_unit(&unit, &payment_settings.unit)?;

    let mut methods = Vec::new();

    // Add bolt11 if supported by payment processor
    if payment_settings.bolt11.is_some() {
        methods.push(PaymentMethod::Known(KnownMethod::Bolt11));
    }

    // Add bolt12 if supported by payment processor
    if payment_settings.bolt12.is_some() {
        methods.push(PaymentMethod::Known(KnownMethod::Bolt12));
    }

    // Add onchain if supported by payment processor
    if payment_settings.onchain.is_some() {
        methods.push(PaymentMethod::Known(KnownMethod::Onchain));
    }

    // Add custom methods from payment settings
    for method_name in payment_settings.custom.keys() {
        methods.push(PaymentMethod::from(method_name.as_str()));
    }

    configure_backend_for_methods(
        settings,
        mint_builder,
        unit,
        mint_melt_limits,
        backend,
        methods,
    )
    .await
}

async fn configure_backend_for_methods(
    settings: &config::Settings,
    mut mint_builder: MintBuilder,
    unit: cdk::nuts::CurrencyUnit,
    mint_melt_limits: MintMeltLimits,
    backend: Arc<dyn MintPayment<Err = cdk_common::payment::Error> + Send + Sync>,
    methods: Vec<PaymentMethod>,
) -> Result<MintBuilder> {
    // Add all supported payment methods to the mint builder
    for method in &methods {
        mint_builder
            .add_payment_processor(
                unit.clone(),
                method.clone(),
                mint_melt_limits,
                backend.clone(),
            )
            .await?;
    }

    // Configure NUT17 (WebSocket support) for all payment methods
    for method in &methods {
        let method_str = method.to_string();
        let nut17_supported = match method_str.as_str() {
            "bolt11" => SupportedMethods::default_bolt11(unit.clone()),
            "bolt12" => SupportedMethods::default_bolt12(unit.clone()),
            _ => SupportedMethods::default_custom(method.clone(), unit.clone()),
        };
        mint_builder = mint_builder.with_supported_websockets(nut17_supported);
    }

    if let Some(input_fee) = settings.info.input_fee_ppk {
        mint_builder.set_unit_fee(&unit, input_fee)?;
    }

    Ok(mint_builder)
}

fn validate_backend_unit(
    configured_unit: &cdk::nuts::CurrencyUnit,
    backend_unit: &str,
) -> Result<()> {
    let backend_unit = cdk::nuts::CurrencyUnit::from_str(backend_unit)
        .with_context(|| format!("Payment backend returned invalid unit `{backend_unit}`"))?;

    if units_are_compatible(&backend_unit, configured_unit) {
        return Ok(());
    }

    bail!(
        "Payment backend reports unit {} but config registers unit {}; only matching units or sat/msat conversions are supported",
        backend_unit,
        configured_unit
    )
}

fn units_are_compatible(
    backend_unit: &cdk::nuts::CurrencyUnit,
    configured_unit: &cdk::nuts::CurrencyUnit,
) -> bool {
    backend_unit == configured_unit
        || matches!(
            (backend_unit, configured_unit),
            (cdk::nuts::CurrencyUnit::Sat, cdk::nuts::CurrencyUnit::Msat)
                | (cdk::nuts::CurrencyUnit::Msat, cdk::nuts::CurrencyUnit::Sat)
        )
}

/// Configures cache settings with support for custom payment methods
async fn configure_cache(
    settings: &config::Settings,
    mint_builder: MintBuilder,
    payment_methods: &[String],
) -> Result<MintBuilder> {
    let mut cached_endpoints = vec![
        // Always include swap endpoint
        CachedEndpoint::new(NUT19Method::Post, NUT19Path::Swap),
    ];

    // Add cache endpoints for each configured payment method
    for method in payment_methods {
        // All payment methods (including bolt11, bolt12) use custom paths now
        cached_endpoints.push(CachedEndpoint::new(
            NUT19Method::Post,
            NUT19Path::custom_mint(method),
        ));
        cached_endpoints.push(CachedEndpoint::new(
            NUT19Method::Post,
            NUT19Path::custom_melt(method),
        ));
    }

    let cache: HttpCache = HttpCache::from_config(settings.info.http_cache.clone()).await?;
    Ok(mint_builder.with_cache(Some(cache.ttl.as_secs()), cached_endpoints))
}

async fn setup_authentication(
    settings: &config::Settings,
    _work_dir: &Path,
    mut mint_builder: MintBuilder,
    _password: Option<String>,
) -> Result<(
    MintBuilder,
    Option<cdk_common::database::DynMintAuthDatabase>,
)> {
    if let Some(auth_settings) = settings.auth.clone() {
        use cdk_common::database::DynMintAuthDatabase;

        tracing::info!("Auth settings are defined. {:?}", auth_settings);
        let auth_localstore: DynMintAuthDatabase = match settings.database.engine {
            #[cfg(feature = "sqlite")]
            DatabaseEngine::Sqlite => {
                #[cfg(feature = "sqlite")]
                {
                    let sql_db_path = _work_dir.join("cdk-mintd-auth.sqlite");
                    #[cfg(not(feature = "sqlcipher"))]
                    let sqlite_db = MintSqliteAuthDatabase::new(&sql_db_path).await?;
                    #[cfg(feature = "sqlcipher")]
                    let sqlite_db = {
                        // Get password from command line arguments for sqlcipher
                        let password = _password.clone().ok_or_else(|| {
                            anyhow!("Password required when sqlcipher feature is enabled")
                        })?;
                        MintSqliteAuthDatabase::new((sql_db_path, password)).await?
                    };

                    Arc::new(sqlite_db)
                }
                #[cfg(not(feature = "sqlite"))]
                {
                    bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
                }
            }
            #[cfg(feature = "postgres")]
            DatabaseEngine::Postgres => {
                #[cfg(feature = "postgres")]
                {
                    // Require dedicated auth database configuration - no fallback to main database
                    let auth_db_config = settings.auth_database.as_ref().ok_or_else(|| {
                        anyhow!("Auth database configuration is required when using PostgreSQL with authentication. Set [auth_database]")
                    })?;

                    let auth_pg_config = auth_db_config.postgres.as_ref().ok_or_else(|| {
                        anyhow!("PostgreSQL auth database configuration is required when using PostgreSQL with authentication. Set [auth_database.postgres]")
                    })?;

                    if auth_pg_config.url.is_empty() {
                        bail!("Auth database PostgreSQL URL is required and cannot be empty. Set [auth_database.postgres].url to an env: or file: secret reference");
                    }

                    let auth_db_config = PgConfig::new(
                        auth_pg_config.url.as_str(),
                        auth_pg_config.tls_mode.as_deref(),
                        auth_pg_config.max_connections,
                        auth_pg_config.connection_timeout_seconds,
                    );
                    Arc::new(MintPgAuthDatabase::new(auth_db_config).await?)
                }
                #[cfg(not(feature = "postgres"))]
                {
                    bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
                }
            }
            #[cfg(not(feature = "sqlite"))]
            DatabaseEngine::Sqlite => {
                bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
            }
            #[cfg(not(feature = "postgres"))]
            DatabaseEngine::Postgres => {
                bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
            }
        };

        let mut protected_endpoints = HashMap::new();
        let mut blind_auth_endpoints = vec![];
        let mut clear_auth_endpoints = vec![];
        let mut unprotected_endpoints = vec![];

        let mint_blind_auth_endpoint =
            ProtectedEndpoint::new(Method::Post, RoutePath::MintBlindAuth);

        protected_endpoints.insert(mint_blind_auth_endpoint.clone(), AuthRequired::Clear);

        clear_auth_endpoints.push(mint_blind_auth_endpoint);

        // Helper function to add endpoint based on auth type
        let mut add_endpoint = |endpoint: ProtectedEndpoint, auth_type: &AuthType| {
            match auth_type {
                AuthType::Blind => {
                    protected_endpoints.insert(endpoint.clone(), AuthRequired::Blind);
                    blind_auth_endpoints.push(endpoint);
                }
                AuthType::Clear => {
                    protected_endpoints.insert(endpoint.clone(), AuthRequired::Clear);
                    clear_auth_endpoints.push(endpoint);
                }
                AuthType::None => {
                    unprotected_endpoints.push(endpoint);
                }
            };
        };

        // Payment method endpoints (bolt11, bolt12, custom) will be added dynamically
        // after the mint is built and we can query the payment processors for their
        // supported methods. See the start_services_with_shutdown function where we
        // add auth endpoints for all configured payment methods.

        // Swap endpoint
        {
            let swap_protected_endpoint = ProtectedEndpoint::new(Method::Post, RoutePath::Swap);
            add_endpoint(swap_protected_endpoint, &auth_settings.swap);
        }

        // Restore endpoint
        {
            let restore_protected_endpoint =
                ProtectedEndpoint::new(Method::Post, RoutePath::Restore);
            add_endpoint(restore_protected_endpoint, &auth_settings.restore);
        }

        // Check proof state endpoint
        {
            let state_protected_endpoint =
                ProtectedEndpoint::new(Method::Post, RoutePath::Checkstate);
            add_endpoint(state_protected_endpoint, &auth_settings.check_proof_state);
        }

        // Ws endpoint
        {
            let ws_protected_endpoint = ProtectedEndpoint::new(Method::Get, RoutePath::Ws);
            add_endpoint(ws_protected_endpoint, &auth_settings.websocket_auth);
        }

        // Custom protected_endpoints will be added dynamically after the mint is built
        // and we can query the payment processors for their supported methods.
        // For now, we don't add any custom endpoints here - they'll be added in the
        // start_services_with_shutdown function after we have access to the mint instance.

        mint_builder = mint_builder.with_auth(
            auth_localstore.clone(),
            auth_settings.openid_discovery,
            auth_settings.openid_client_id,
            clear_auth_endpoints,
        );
        mint_builder =
            mint_builder.with_blind_auth(auth_settings.mint_max_bat, blind_auth_endpoints);

        let mut tx = auth_localstore.begin_transaction().await?;

        if !unprotected_endpoints.is_empty() {
            tx.remove_protected_endpoints(unprotected_endpoints).await?;
        }
        if !protected_endpoints.is_empty() {
            tx.add_protected_endpoints(protected_endpoints).await?;
        }
        tx.commit().await?;

        Ok((mint_builder, Some(auth_localstore)))
    } else {
        Ok((mint_builder, None))
    }
}

/// Build mints with the configured the signing method (remote signatory or local seed)
async fn build_mint(
    settings: &config::Settings,
    keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
    mint_builder: MintBuilder,
    validated_signing_source: Option<&ValidatedSigningSource>,
) -> Result<Mint> {
    if let Some(signatory) = settings.enabled_signatory() {
        let tls_dir = signatory.tls_dir.clone();

        if tls_dir.is_none() {
            if !signatory.allow_insecure {
                bail!(
                    "gRPC signatory TLS is not configured. Set [signatory].tls_dir or \
                     [signatory].allow_insecure = true to connect without TLS"
                );
            }

            tracing::warn!(
                "No gRPC signatory TLS directory configured; connecting without TLS because \
                 allow_insecure is true"
            );
        }

        let remote_signatory = match validated_signing_source
            .and_then(|validated| validated.remote_signatory.clone())
        {
            Some(remote_signatory) => {
                tracing::info!(
                    "Using the remote signatory connection validated during configuration startup"
                );
                remote_signatory
            }
            None => {
                tracing::info!(
                    "Connecting to remote signatory at {}:{} with TLS directory {:?}",
                    signatory.address,
                    signatory.port,
                    tls_dir
                );
                Arc::new(
                    cdk_signatory::SignatoryRpcClient::new(
                        &signatory.address,
                        signatory.port,
                        tls_dir,
                    )
                    .await?,
                )
            }
        };
        if let Some(validated) = validated_signing_source {
            ensure_signatory_identity(&remote_signatory, validated.expected_pubkey).await?;
        }

        Ok(mint_builder.build_with_signatory(remote_signatory).await?)
    } else if let Some(seed) = settings.info.seed.clone().filter(|seed| !seed.is_empty()) {
        if validated_signing_source.is_some_and(|validated| validated.remote_signatory.is_some()) {
            bail!("Validated remote signatory provided for local signing configuration");
        }
        let seed_bytes: Vec<u8> = seed.into();
        Ok(mint_builder.build_with_seed(keystore, &seed_bytes).await?)
    } else if let Some(mnemonic) = settings
        .info
        .mnemonic
        .clone()
        .map(|s| Mnemonic::from_str(&s))
        .transpose()?
    {
        Ok(mint_builder
            .build_with_seed(keystore, &mnemonic.to_seed_normalized(""))
            .await?)
    } else {
        bail!("No seed nor remote signatory set");
    }
}

async fn ensure_signatory_identity(
    signatory: &DynSignatory,
    expected_pubkey: cdk::nuts::PublicKey,
) -> Result<()> {
    let actual_pubkey = signatory.keysets().await?.pubkey;
    if actual_pubkey != expected_pubkey {
        return Err(config_service::ConfigurationServiceError::SigningIdentityChange.into());
    }
    Ok(())
}

async fn reconcile_canonical_configuration(
    mint: &Mint,
    mut configured_mint_info: cdk::nuts::MintInfo,
    configured_quote_ttl: QuoteTTL,
    preserve_database_values: bool,
) -> Result<()> {
    if !preserve_database_values {
        tracing::info!(
            "Applying mint info and quote TTL from the database-backed configuration document."
        );
        if let Ok(stored_mint_info) = mint.mint_info().await {
            if configured_mint_info.pubkey.is_none() {
                configured_mint_info.pubkey = stored_mint_info.pubkey;
            }
        }
        mint.set_mint_info_and_quote_ttl(configured_mint_info, configured_quote_ttl)
            .await?;
        return Ok(());
    }

    if mint.mint_info().await.is_err() {
        tracing::info!("Mint info not set on mint, setting.");
        mint.set_mint_info_and_quote_ttl(configured_mint_info, configured_quote_ttl)
            .await?;
        return Ok(());
    }

    if !mint.quote_ttl_is_persisted().await? {
        mint.set_quote_ttl(configured_quote_ttl).await?;
    }
    let mint_version = MintVersion::new(
        "cdk-mintd".to_string(),
        CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
    );
    let mut stored_mint_info = mint.mint_info().await?;
    stored_mint_info.version = Some(mint_version);
    mint.set_mint_info(stored_mint_info).await?;
    tracing::info!("Preserving RPC-managed mint info from the database.");
    Ok(())
}

/// A mint daemon with every resource built and all database reconciliation
/// completed, ready to start its services.
struct PreparedMintd {
    mint: Arc<cdk::mint::Mint>,
    #[cfg(feature = "prometheus")]
    prometheus: Option<config::Prometheus>,
    mint_service: Router,
    listen_addr: String,
    listen_port: u16,
    activation: Option<ConfigurationActivation>,
    shutdown_tx: tokio::sync::broadcast::Sender<()>,
    /// Management RPC server and its TLS directory, when enabled.
    #[cfg(feature = "management-rpc")]
    rpc_to_start: Option<(cdk_mint_rpc::MintRPCServer, Option<PathBuf>)>,
}

/// A mint daemon with all services started and its configuration committed
/// as applied, serving requests until shutdown.
struct RunningMintd {
    mint: Arc<cdk::mint::Mint>,
    mint_service: Router,
    listener: tokio::net::TcpListener,
    shutdown_tx: tokio::sync::broadcast::Sender<()>,
    #[cfg(feature = "prometheus")]
    prometheus_handle: Option<tokio::task::JoinHandle<()>>,
    #[cfg(feature = "management-rpc")]
    rpc_server: Option<cdk_mint_rpc::MintRPCServer>,
}

impl PreparedMintd {
    /// Builds every resource and performs all database reconciliation
    /// without starting tasks or binding listeners.
    #[allow(clippy::too_many_arguments)]
    async fn prepare(
        mint: Arc<cdk::mint::Mint>,
        settings: &config::Settings,
        _work_dir: &Path,
        _wallet_info_provider: ConfiguredWalletInfoProvider,
        mint_builder_info: cdk::nuts::MintInfo,
        routers: Vec<Router>,
        auth_localstore: Option<cdk_common::database::DynMintAuthDatabase>,
        activation: Option<ConfigurationActivation>,
    ) -> Result<Self> {
        let listen_addr = settings.info.listen_host.clone();
        let listen_port = settings.info.listen_port;
        let cache: HttpCache = HttpCache::from_config(settings.info.http_cache.clone()).await?;

        #[cfg(feature = "management-rpc")]
        let mut rpc_enabled = false;
        #[cfg(not(feature = "management-rpc"))]
        let rpc_enabled = false;

        #[cfg(feature = "management-rpc")]
        let mut rpc_to_start = None;

        #[cfg(feature = "management-rpc")]
        {
            if let Some(rpc_settings) = settings.mint_management_rpc.clone() {
                if rpc_settings.enabled {
                    let addr = rpc_settings.address.unwrap_or("127.0.0.1".to_string());
                    let port = rpc_settings.port.unwrap_or(8086);
                    let mut mint_rpc = cdk_mint_rpc::MintRPCServer::new(&addr, port, mint.clone())?
                        .with_mint_quote_payment_override(
                            rpc_settings.allow_mint_quote_payment_override,
                        );
                    if let Some(activation) = activation.as_ref() {
                        mint_rpc =
                            mint_rpc.with_mutation_guard(Arc::new(ConfigurationMutationGuard {
                                service: activation.service.clone(),
                            }));
                    }
                    #[cfg(feature = "bdk")]
                    if let Some(provider) = _wallet_info_provider.clone() {
                        mint_rpc = mint_rpc.with_wallet_info_provider(provider);
                    }

                    let tls_dir = rpc_settings.tls_dir.unwrap_or(_work_dir.join("tls"));

                    let tls_dir = if tls_dir.exists() {
                        Some(tls_dir)
                    } else if rpc_settings.allow_insecure {
                        tracing::warn!(
                        "TLS directory does not exist: {}. Starting RPC server in INSECURE mode without TLS encryption because allow_insecure is true",
                        tls_dir.display()
                    );
                        None
                    } else {
                        bail!(
                            "Management RPC TLS directory does not exist: {}. Set \
                         [mint_management_rpc].tls_dir or \
                         [mint_management_rpc].allow_insecure = true to start without \
                         TLS",
                            tls_dir.display()
                        );
                    };

                    rpc_to_start = Some((mint_rpc, tls_dir));
                    rpc_enabled = true;
                }
            }
        }

        // Determine the desired QuoteTTL from config/env or fall back to defaults
        let desired_quote_ttl: QuoteTTL = settings.info.quote_ttl.unwrap_or_default();

        let preserve_database_values = match activation.as_ref() {
            Some(activation) => activation.preserves_database_values(rpc_enabled),
            // A startup without a database-backed configuration record never
            // forces document values; preserve database values when the
            // management RPC could have authored them.
            None => rpc_enabled,
        };

        reconcile_canonical_configuration(
            mint.as_ref(),
            mint_builder_info,
            desired_quote_ttl,
            preserve_database_values,
        )
        .await?;

        let mint_info = mint.mint_info().await?;
        let nut04_methods = mint_info.nuts.nut04.supported_methods();
        let nut05_methods = mint_info.nuts.nut05.supported_methods();

        // Get custom payment methods from payment processors
        let mut custom_methods = mint.get_custom_payment_methods().await?;

        // Add bolt11 if it's supported by any payment processor
        let bolt11_method = PaymentMethod::Known(KnownMethod::Bolt11);
        let bolt11_supported =
            nut04_methods.contains(&&bolt11_method) || nut05_methods.contains(&&bolt11_method);
        // Add bolt12 if it's supported by any payment processor
        let bolt12_method = PaymentMethod::Known(KnownMethod::Bolt12);
        let bolt12_supported =
            nut04_methods.contains(&&bolt12_method) || nut05_methods.contains(&&bolt12_method);

        // Add onchain if it's supported by any payment processor
        let onchain_method = PaymentMethod::Known(KnownMethod::Onchain);
        let onchain_supported =
            nut04_methods.contains(&&onchain_method) || nut05_methods.contains(&&onchain_method);

        if bolt11_supported
            && !custom_methods.contains(&PaymentMethod::Known(KnownMethod::Bolt11).to_string())
        {
            custom_methods.push(PaymentMethod::Known(KnownMethod::Bolt11).to_string());
        }
        if bolt12_supported
            && !custom_methods.contains(&PaymentMethod::Known(KnownMethod::Bolt12).to_string())
        {
            custom_methods.push(PaymentMethod::Known(KnownMethod::Bolt12).to_string());
        }
        if onchain_supported
            && !custom_methods.contains(&PaymentMethod::Known(KnownMethod::Onchain).to_string())
        {
            custom_methods.push(PaymentMethod::Known(KnownMethod::Onchain).to_string());
        }

        tracing::info!("Payment methods: {:?}", custom_methods);

        // Configure auth for custom payment methods if auth is enabled
        if let (Some(ref auth_settings), Some(auth_db)) = (&settings.auth, &auth_localstore) {
            if auth_settings.auth_enabled {
                use std::collections::HashMap;

                use cdk::nuts::nut21::{Method, ProtectedEndpoint, RoutePath};
                use cdk::nuts::AuthRequired;

                use crate::config::AuthType;

                // First, remove all existing payment-method-related endpoints from the database
                // to ensure old payment methods don't persist when configuration changes
                let existing_endpoints = auth_db.get_auth_for_endpoints().await?;
                let payment_method_endpoints_to_remove: Vec<ProtectedEndpoint> = existing_endpoints
                    .keys()
                    .filter(|endpoint| {
                        matches!(
                            endpoint.path,
                            RoutePath::MintQuote(_)
                                | RoutePath::Mint(_)
                                | RoutePath::MeltQuote(_)
                                | RoutePath::Melt(_)
                        )
                    })
                    .cloned()
                    .collect();

                if !payment_method_endpoints_to_remove.is_empty() {
                    tracing::debug!(
                        "Removing {} old payment method endpoints from database",
                        payment_method_endpoints_to_remove.len()
                    );
                    let mut tx = auth_db.begin_transaction().await?;
                    tx.remove_protected_endpoints(payment_method_endpoints_to_remove)
                        .await?;
                    tx.commit().await?;
                }

                // Now add endpoints for current payment methods
                if !custom_methods.is_empty() {
                    let mut protected_endpoints = HashMap::new();

                    for method_name in &custom_methods {
                        tracing::debug!(
                            "Adding auth endpoints for payment method: {}",
                            method_name
                        );

                        // Determine auth type based on settings
                        let mint_quote_auth = match auth_settings.get_mint_quote {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        let check_mint_quote_auth = match auth_settings.check_mint_quote {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        let mint_auth = match auth_settings.mint {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        let melt_quote_auth = match auth_settings.get_melt_quote {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        let check_melt_quote_auth = match auth_settings.check_melt_quote {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        let melt_auth = match auth_settings.melt {
                            AuthType::Clear => Some(AuthRequired::Clear),
                            AuthType::Blind => Some(AuthRequired::Blind),
                            AuthType::None => None,
                        };

                        // Create endpoints for each payment method operation
                        if let Some(auth) = mint_quote_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Post,
                                    RoutePath::MintQuote(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                        if let Some(auth) = check_mint_quote_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Get,
                                    RoutePath::MintQuote(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                        if let Some(auth) = mint_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Post,
                                    RoutePath::Mint(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                        if let Some(auth) = melt_quote_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Post,
                                    RoutePath::MeltQuote(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                        if let Some(auth) = check_melt_quote_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Get,
                                    RoutePath::MeltQuote(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                        if let Some(auth) = melt_auth {
                            protected_endpoints.insert(
                                ProtectedEndpoint::new(
                                    Method::Post,
                                    RoutePath::Melt(method_name.clone()),
                                ),
                                auth,
                            );
                        }
                    }

                    // Add all custom endpoints in one transaction
                    if !protected_endpoints.is_empty() {
                        let mut tx = auth_db.begin_transaction().await?;
                        tx.add_protected_endpoints(protected_endpoints).await?;
                        tx.commit().await?;
                    }
                }
            }
        }

        let v1_service = cdk_axum::create_mint_router_with_custom_cache(
            Arc::clone(&mint),
            cache,
            custom_methods,
            settings.info.enable_info_page.unwrap_or(true),
        )
        .await?;

        let mut mint_service = Router::new()
            .merge(v1_service)
            .layer(DefaultBodyLimit::max(REQUEST_BODY_LIMIT_BYTES))
            .layer(
                ServiceBuilder::new()
                    .layer(RequestDecompressionLayer::new())
                    .layer(CompressionLayer::new()),
            )
            .layer(TraceLayer::new_for_http());

        for router in routers {
            mint_service = mint_service.merge(router);
        }

        // Create a broadcast channel to share shutdown signal between services
        let (shutdown_tx, _) = tokio::sync::broadcast::channel::<()>(1);

        Ok(Self {
            mint,
            #[cfg(feature = "prometheus")]
            prometheus: settings.prometheus.clone(),
            mint_service,
            listen_addr,
            listen_port,
            activation,
            shutdown_tx,
            #[cfg(feature = "management-rpc")]
            rpc_to_start,
        })
    }

    /// Starts all services, binds the HTTP listener, and commits the
    /// configuration as applied.
    async fn activate(self) -> Result<RunningMintd> {
        #[cfg(feature = "management-rpc")]
        let rpc_server = {
            if let Some((mut mint_rpc, tls_dir)) = self.rpc_to_start {
                mint_rpc.start(tls_dir).await?;
                Some(mint_rpc)
            } else {
                None
            }
        };

        // Start Prometheus server if enabled
        #[cfg(feature = "prometheus")]
        let prometheus_handle = {
            if let Some(prometheus_settings) = &self.prometheus {
                if prometheus_settings.enabled {
                    let addr = prometheus_settings
                        .address
                        .clone()
                        .unwrap_or("127.0.0.1".to_string());
                    let port = prometheus_settings.port.unwrap_or(9000);

                    let address = format!("{addr}:{port}")
                        .parse()
                        .with_context(|| format!("Invalid Prometheus address {addr}:{port}"))?;

                    let server = cdk_prometheus::PrometheusBuilder::new()
                        .bind_address(address)
                        .build_with_cdk_metrics()?;

                    let mut shutdown_rx = self.shutdown_tx.subscribe();
                    let prometheus_shutdown = async move {
                        let _ = shutdown_rx.recv().await;
                    };

                    Some(tokio::spawn(async move {
                        if let Err(e) = server.start(prometheus_shutdown).await {
                            tracing::error!("Failed to start prometheus server: {}", e);
                        }
                    }))
                } else {
                    None
                }
            } else {
                None
            }
        };

        self.mint.start().await?;

        let socket_addr =
            SocketAddr::from_str(&format!("{}:{}", self.listen_addr, self.listen_port))?;

        let listener = tokio::net::TcpListener::bind(socket_addr).await?;

        tracing::info!("listening on {}", listener.local_addr()?);

        // All fallible startup steps have succeeded and the daemon is about to
        // serve with this configuration, so it can be recorded as applied.
        if let Some(activation) = &self.activation {
            activation.mark_applied().await?;
        }

        Ok(RunningMintd {
            mint: self.mint,
            mint_service: self.mint_service,
            listener,
            shutdown_tx: self.shutdown_tx,
            #[cfg(feature = "prometheus")]
            prometheus_handle,
            #[cfg(feature = "management-rpc")]
            rpc_server,
        })
    }
}

impl RunningMintd {
    /// Serves requests until the shutdown signal fires, then stops all
    /// services gracefully.
    async fn serve(
        self,
        shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> Result<()> {
        // Create a task to wait for the shutdown signal and broadcast it
        let shutdown_broadcast_task = {
            let shutdown_tx = self.shutdown_tx.clone();
            tokio::spawn(async move {
                shutdown_signal.await;
                tracing::info!("Shutdown signal received, broadcasting to all services");
                let _ = shutdown_tx.send(());
            })
        };

        // Create shutdown future for axum server
        let mut axum_shutdown_rx = self.shutdown_tx.subscribe();
        let axum_shutdown = async move {
            let _ = axum_shutdown_rx.recv().await;
        };

        // Wait for axum server to complete with custom shutdown signal
        let axum_result =
            axum::serve(self.listener, self.mint_service).with_graceful_shutdown(axum_shutdown);

        match axum_result.await {
            Ok(_) => {
                tracing::info!("Axum server stopped with okay status");
            }
            Err(err) => {
                tracing::warn!("Axum server stopped with error");
                tracing::error!("{}", err);
                bail!("Axum exited with error")
            }
        }

        // Wait for the shutdown broadcast task to complete
        let _ = shutdown_broadcast_task.await;

        // Wait for prometheus server to shutdown if it was started
        #[cfg(feature = "prometheus")]
        if let Some(handle) = self.prometheus_handle {
            if let Err(e) = handle.await {
                tracing::warn!("Prometheus server task failed: {}", e);
            }
        }

        self.mint.stop().await?;

        #[cfg(feature = "management-rpc")]
        {
            if let Some(rpc_server) = self.rpc_server {
                rpc_server.stop().await?;
            }
        }

        Ok(())
    }
}

/// Starts all mintd services and blocks until the shutdown signal fires.
#[allow(clippy::too_many_arguments)]
async fn start_services_with_shutdown(
    mint: Arc<cdk::mint::Mint>,
    settings: &config::Settings,
    work_dir: &Path,
    wallet_info_provider: ConfiguredWalletInfoProvider,
    mint_builder_info: cdk::nuts::MintInfo,
    shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
    routers: Vec<Router>,
    auth_localstore: Option<cdk_common::database::DynMintAuthDatabase>,
    activation: Option<ConfigurationActivation>,
) -> Result<()> {
    let prepared = PreparedMintd::prepare(
        mint,
        settings,
        work_dir,
        wallet_info_provider,
        mint_builder_info,
        routers,
        auth_localstore,
        activation,
    )
    .await?;
    let running = prepared.activate().await?;
    running.serve(shutdown_signal).await
}

async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install CTRL+C handler");
    tracing::info!("Shutdown signal received");
}

fn work_dir() -> Result<PathBuf> {
    let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
    let dir = home_dir.join(".cdk-mintd");

    std::fs::create_dir_all(&dir)?;

    Ok(dir)
}

/// The main entry point for the application when used as a library
pub async fn run_mintd(
    work_dir: &Path,
    settings: &config::Settings,
    db_password: Option<String>,
    enable_logging: bool,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    routers: Vec<Router>,
) -> Result<()> {
    let _guard = if enable_logging {
        setup_tracing(work_dir, &settings.info.logging)?
    } else {
        None
    };

    let result = run_mintd_with_shutdown(
        work_dir,
        settings,
        shutdown_signal(),
        db_password,
        runtime,
        routers,
    )
    .await;

    // Explicitly drop the guard to ensure proper cleanup
    if let Some(guard) = _guard {
        tracing::info!("Shutting down logging worker thread");
        drop(guard);
        // Give the worker thread a moment to flush any remaining logs
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }

    tracing::info!("Mintd shutdown");

    result
}

/// Run mintd with a custom shutdown signal
pub async fn run_mintd_with_shutdown(
    work_dir: &Path,
    settings: &config::Settings,
    shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
    db_password: Option<String>,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    routers: Vec<Router>,
) -> Result<()> {
    let (localstore, keystore, kv, _configuration_store) =
        initial_setup(work_dir, settings, db_password.clone()).await?;

    run_mintd_with_database_and_shutdown(
        work_dir,
        settings,
        localstore,
        keystore,
        kv,
        shutdown_signal,
        db_password,
        runtime,
        routers,
        None,
        None,
    )
    .await
}

#[allow(clippy::too_many_arguments)]
async fn run_mintd_with_database_and_shutdown(
    work_dir: &Path,
    settings: &config::Settings,
    localstore: DynMintDatabase,
    keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
    kv: Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync>,
    shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
    db_password: Option<String>,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    routers: Vec<Router>,
    activation: Option<ConfigurationActivation>,
    validated_signing_source: Option<ValidatedSigningSource>,
) -> Result<()> {
    let mint_builder = MintBuilder::new(localstore);

    // If RPC is enabled and DB contains mint_info already, initialize the builder from DB.
    // This ensures subsequent builder modifications (like version injection) can respect stored values.
    let maybe_mint_builder = {
        #[cfg(feature = "management-rpc")]
        {
            if activation
                .as_ref()
                .is_some_and(ConfigurationActivation::forces_configuration)
            {
                mint_builder
            } else if let Some(rpc_settings) = settings.mint_management_rpc.clone() {
                if rpc_settings.enabled {
                    // Best-effort: pull DB state into builder if present
                    let mut tmp = mint_builder;
                    if let Err(e) = tmp.init_from_db_if_present().await {
                        tracing::warn!("Failed to init builder from DB: {}", e);
                    }
                    tmp
                } else {
                    mint_builder
                }
            } else {
                mint_builder
            }
        }
        #[cfg(not(feature = "management-rpc"))]
        {
            mint_builder
        }
    };

    let (mint_builder, wallet_info_provider) = configure_mint_builder_with_wallet_info(
        settings,
        maybe_mint_builder,
        runtime,
        work_dir,
        Some(kv),
    )
    .await?;
    let (mint_builder, auth_localstore) =
        setup_authentication(settings, work_dir, mint_builder, db_password).await?;

    let config_mint_info = mint_builder.current_mint_info();

    let mint = build_mint(
        settings,
        keystore,
        mint_builder,
        validated_signing_source.as_ref(),
    )
    .await?;

    tracing::debug!("Mint built from builder.");

    let mint = Arc::new(mint);

    start_services_with_shutdown(
        mint.clone(),
        settings,
        work_dir,
        wallet_info_provider,
        config_mint_info,
        shutdown_signal,
        routers,
        auth_localstore,
        activation,
    )
    .await
}

fn load_database_bootstrap_settings() -> Result<config::Settings> {
    let mut settings = config::Settings::default();
    if let Ok(database) = env::var(env_vars::DATABASE_ENV_VAR) {
        settings.database.engine =
            DatabaseEngine::from_str(&database).map_err(anyhow::Error::msg)?;
    }
    if settings.database.engine == DatabaseEngine::Postgres {
        settings.database.postgres = Some(config::PostgresConfig::default().from_env());
    } else {
        settings.database.postgres = None;
    }
    validate_database_config(&settings)?;
    Ok(settings)
}

fn configuration_service(
    store: Arc<dyn KVStoreCompareAndSwap<Err = cdk_database::Error> + Send + Sync>,
    settings: &config::Settings,
) -> config_service::ConfigurationService {
    config_service::ConfigurationService::new(
        config_store::ConfigRepository::new(store),
        settings.database.clone(),
    )
}

/// Validates a database-backed configuration document without writing it.
pub async fn validate_configuration_document(document: &str) -> Result<()> {
    config_service::ConfigurationService::validate_import(document).await?;
    Ok(())
}

/// Initializes the authoritative configuration record in the selected database.
pub async fn initialize_configuration(
    work_dir: &Path,
    document: &str,
    mode: MintInitializationMode,
    bdk_wallet_policy: BdkWalletPolicy,
    db_password: Option<String>,
) -> Result<()> {
    let bootstrap = load_database_bootstrap_settings()?;
    let (localstore, keystore, _kv, configuration_store) =
        initial_setup(work_dir, &bootstrap, db_password).await?;
    let mut mint_builder = MintBuilder::new(localstore);
    mint_builder.init_from_db_if_present().await?;
    let database_pubkey = mint_builder.current_mint_info().pubkey;
    let mut keyset_transaction = keystore.begin_transaction().await?;
    let has_keysets = !keyset_transaction.get_keyset_infos().await?.is_empty();
    keyset_transaction.commit().await?;

    configuration_service(configuration_store, &bootstrap)
        .initialize(
            document,
            mode,
            database_pubkey,
            has_keysets,
            work_dir,
            bdk_wallet_policy,
        )
        .await?;
    Ok(())
}

/// Validates and atomically replaces the authoritative configuration record.
pub async fn apply_configuration(
    work_dir: &Path,
    document: &str,
    validate_only: bool,
    bdk_wallet_policy: BdkWalletPolicy,
    db_password: Option<String>,
) -> Result<ApplyOutcome> {
    let bootstrap = load_database_bootstrap_settings()?;
    let (_localstore, _keystore, _kv, configuration_store) =
        initial_setup(work_dir, &bootstrap, db_password).await?;
    Ok(configuration_service(configuration_store, &bootstrap)
        .apply(document, validate_only, work_dir, bdk_wallet_policy)
        .await?)
}

/// Stages the last configuration known to have been applied successfully.
pub async fn rollback_configuration(
    work_dir: &Path,
    db_password: Option<String>,
) -> Result<RollbackOutcome> {
    let bootstrap = load_database_bootstrap_settings()?;
    let (_localstore, _keystore, _kv, configuration_store) =
        initial_setup(work_dir, &bootstrap, db_password).await?;
    Ok(configuration_service(configuration_store, &bootstrap)
        .rollback()
        .await?)
}

/// Reads the unresolved authoritative configuration document.
pub async fn stored_configuration_document(
    work_dir: &Path,
    db_password: Option<String>,
) -> Result<String> {
    let bootstrap = load_database_bootstrap_settings()?;
    let (_localstore, _keystore, _kv, configuration_store) =
        initial_setup(work_dir, &bootstrap, db_password).await?;
    Ok(configuration_service(configuration_store, &bootstrap)
        .document()
        .await?)
}

/// Runs mintd using only the configuration stored in its primary database.
pub async fn run_mintd_from_database(
    work_dir: &Path,
    db_password: Option<String>,
    enable_logging: bool,
    runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
    routers: Vec<Router>,
) -> Result<()> {
    let bootstrap = load_database_bootstrap_settings()?;
    let (localstore, keystore, kv, configuration_store) =
        initial_setup(work_dir, &bootstrap, db_password.clone()).await?;
    let service = configuration_service(configuration_store, &bootstrap);
    let startup = service.startup().await?;
    config_service::require_existing_bdk_wallet(
        &startup.resolved.settings,
        work_dir,
        startup.bdk_wallet_policy,
    )?;
    let validated_signing_source = Some(ValidatedSigningSource {
        expected_pubkey: startup.signing_identity.pubkey,
        remote_signatory: startup
            .remote_signatory
            .map(|signatory| -> DynSignatory { signatory }),
    });
    let activation = Some(ConfigurationActivation::new(
        service,
        startup.state,
        startup.revision,
    ));
    let settings = startup.resolved.settings;

    let guard = if enable_logging {
        setup_tracing(work_dir, &settings.info.logging)?
    } else {
        None
    };

    let result = run_mintd_with_database_and_shutdown(
        work_dir,
        &settings,
        localstore,
        keystore,
        kv,
        shutdown_signal(),
        db_password,
        runtime,
        routers,
        activation,
        validated_signing_source,
    )
    .await;

    if let Some(guard) = guard {
        tracing::info!("Shutting down logging worker thread");
        drop(guard);
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }

    tracing::info!("Mintd shutdown");
    result
}

#[cfg(test)]
mod tests {
    use std::fs;

    use cdk::nuts::{CurrencyUnit, MintMethodSettings, PaymentMethod};

    use super::*;

    const TEST_MNEMONIC: &str =
        "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";

    fn temp_seed_file(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("cdk_mintd_{name}_{}", std::process::id()))
    }

    #[cfg(all(feature = "sqlite", feature = "fakewallet"))]
    fn sqlite_configuration_document(secret_path: &Path, name: &str) -> String {
        format!(
            r#"
[info]
mnemonic = "file:{}"

[mint_info]
name = "{name}"

[payment_backend]
backend = "fakewallet"

[fake_wallet]

[database]
engine = "sqlite"
"#,
            secret_path.display()
        )
    }

    #[cfg(all(feature = "sqlite", feature = "bdk"))]
    fn sqlite_bdk_configuration_document(secret_path: &Path, name: &str) -> String {
        format!(
            r#"
[info]
mnemonic = "file:{}"

[mint_info]
name = "{name}"

[payment_backend]
backend = "none"

[onchain]
onchain_backend = "bdk"

[bdk]
network = "regtest"
mnemonic = "file:{}"

[database]
engine = "sqlite"
"#,
            secret_path.display(),
            secret_path.display()
        )
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn validated_remote_signatory_identity_is_checked_at_mint_build_boundary() {
        use cdk_signatory::db_signatory::DbSignatory;
        use cdk_signatory::signatory::Signatory;
        use cdk_sqlite::mint::memory;

        let expected_store = Arc::new(memory::empty().await.expect("expected signatory database"));
        let expected_signatory =
            DbSignatory::new(expected_store, &[7; 32], HashMap::new(), Default::default())
                .await
                .expect("expected signatory");
        let expected_pubkey = expected_signatory
            .keysets()
            .await
            .expect("expected keysets")
            .pubkey;

        let actual_store = Arc::new(memory::empty().await.expect("actual signatory database"));
        let actual_signatory: DynSignatory = Arc::new(
            DbSignatory::new(actual_store, &[9; 32], HashMap::new(), Default::default())
                .await
                .expect("actual signatory"),
        );
        let actual_pubkey = actual_signatory
            .keysets()
            .await
            .expect("actual keysets")
            .pubkey;

        ensure_signatory_identity(&actual_signatory, actual_pubkey)
            .await
            .expect("matching identity");
        let error = ensure_signatory_identity(&actual_signatory, expected_pubkey)
            .await
            .expect_err("changed identity should be rejected");
        assert!(
            error
                .to_string()
                .contains("signing identity does not match this mint database"),
            "unexpected error: {error}"
        );
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn unapplied_configuration_refreshes_canonical_values_once() {
        use cdk_sqlite::mint::memory;

        let database = Arc::new(memory::empty().await.expect("in-memory database"));
        let mut builder = MintBuilder::new(database.clone());
        builder
            .configure_unit(CurrencyUnit::Sat, Default::default())
            .expect("configure unit");
        let mint = builder
            .build_with_seed(database.clone(), &[7; 32])
            .await
            .expect("build mint");

        let stored_info = MintBuilder::new(database.clone())
            .with_name("stored".to_owned())
            .current_mint_info();
        mint.set_mint_info(stored_info)
            .await
            .expect("set stored mint info");
        mint.set_quote_ttl(QuoteTTL::new(10, 20))
            .await
            .expect("set stored quote ttl");

        let imported_info = MintBuilder::new(database.clone())
            .with_name("imported".to_owned())
            .current_mint_info();
        reconcile_canonical_configuration(&mint, imported_info, QuoteTTL::new(30, 40), false)
            .await
            .expect("apply imported canonical values");
        assert_eq!(
            mint.mint_info().await.expect("mint info").name.as_deref(),
            Some("imported")
        );
        assert_eq!(
            mint.quote_ttl().await.expect("quote ttl"),
            QuoteTTL::new(30, 40)
        );

        let mut rpc_info = mint.mint_info().await.expect("mint info");
        rpc_info.name = Some("rpc-managed".to_owned());
        mint.set_mint_info(rpc_info)
            .await
            .expect("set RPC-managed mint info");
        mint.set_quote_ttl(QuoteTTL::new(50, 60))
            .await
            .expect("set RPC-managed quote ttl");

        let later_document_info = MintBuilder::new(database)
            .with_name("document".to_owned())
            .current_mint_info();
        reconcile_canonical_configuration(&mint, later_document_info, QuoteTTL::new(70, 80), true)
            .await
            .expect("preserve RPC-managed canonical values");
        assert_eq!(
            mint.mint_info().await.expect("mint info").name.as_deref(),
            Some("rpc-managed")
        );
        assert_eq!(
            mint.quote_ttl().await.expect("quote ttl"),
            QuoteTTL::new(50, 60)
        );
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn preserve_mode_seeds_empty_mint_and_missing_quote_ttl() {
        use cdk_sqlite::mint::memory;

        let database = Arc::new(memory::empty().await.expect("in-memory database"));
        let mut builder = MintBuilder::new(database.clone());
        builder
            .configure_unit(CurrencyUnit::Sat, Default::default())
            .expect("configure unit");
        let mint = builder
            .build_with_seed(database.clone(), &[9; 32])
            .await
            .expect("build mint");

        // Fresh mint stores default mint info during build; clear preservation by exercising
        // the branch where quote TTL has not been persisted yet.
        let seeded_info = MintBuilder::new(database.clone())
            .with_name("seeded".to_owned())
            .current_mint_info();
        // Force mint info missing path using a separate mint without set info if possible.
        // If mint always has info after build, still cover missing-ttl path.
        if mint.mint_info().await.is_ok() {
            // Overwrite mint info without quote ttl persistence by using an empty info DB path:
            // re-build mint and never call set_quote_ttl.
            let database = Arc::new(memory::empty().await.expect("second database"));
            let mut builder = MintBuilder::new(database.clone());
            builder
                .configure_unit(CurrencyUnit::Sat, Default::default())
                .expect("configure unit");
            let mint = builder
                .build_with_seed(database.clone(), &[11; 32])
                .await
                .expect("build mint");
            assert!(!mint
                .quote_ttl_is_persisted()
                .await
                .expect("quote ttl persistence probe"));
            let info = MintBuilder::new(database)
                .with_name("preserve-ttl".to_owned())
                .current_mint_info();
            reconcile_canonical_configuration(&mint, info, QuoteTTL::new(1, 2), true)
                .await
                .expect("preserve with missing ttl");
            assert!(mint
                .quote_ttl_is_persisted()
                .await
                .expect("quote ttl should now be persisted"));
            assert_eq!(
                mint.quote_ttl().await.expect("quote ttl"),
                QuoteTTL::new(1, 2)
            );
        } else {
            reconcile_canonical_configuration(&mint, seeded_info, QuoteTTL::new(3, 4), true)
                .await
                .expect("seed mint info when missing");
            assert_eq!(
                mint.mint_info().await.expect("mint info").name.as_deref(),
                Some("seeded")
            );
        }
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn unapplied_configuration_preserves_existing_mint_pubkey() {
        use cdk::nuts::PublicKey;
        use cdk_sqlite::mint::memory;

        let database = Arc::new(memory::empty().await.expect("in-memory database"));
        let mut builder = MintBuilder::new(database.clone());
        builder
            .configure_unit(CurrencyUnit::Sat, Default::default())
            .expect("configure unit");
        let mint = builder
            .build_with_seed(database.clone(), &[13; 32])
            .await
            .expect("build mint");

        let pubkey = PublicKey::from_hex(
            "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
        )
        .expect("static pubkey");
        let mut stored = MintBuilder::new(database.clone())
            .with_name("stored".to_owned())
            .current_mint_info();
        stored.pubkey = Some(pubkey);
        mint.set_mint_info(stored)
            .await
            .expect("set stored mint info");

        let mut imported = MintBuilder::new(database)
            .with_name("imported".to_owned())
            .current_mint_info();
        imported.pubkey = None;
        reconcile_canonical_configuration(&mint, imported, QuoteTTL::new(7, 8), false)
            .await
            .expect("apply imported values");
        assert_eq!(
            mint.mint_info().await.expect("mint info").pubkey,
            Some(pubkey)
        );
        assert_eq!(
            mint.mint_info().await.expect("mint info").name.as_deref(),
            Some("imported")
        );
    }

    #[cfg(all(feature = "sqlite", feature = "fakewallet"))]
    #[tokio::test]
    async fn database_configuration_public_api_round_trip() {
        let work_dir = crate::test_utils::unique_temp_path("cdk_mintd_public_config_api");
        fs::create_dir_all(&work_dir).expect("create work dir");
        let secret_path = work_dir.join("mnemonic.secret");
        fs::write(&secret_path, TEST_MNEMONIC).expect("write mnemonic secret");

        #[cfg(feature = "sqlcipher")]
        let password = Some("test-password".to_string());
        #[cfg(not(feature = "sqlcipher"))]
        let password: Option<String> = None;

        let first = sqlite_configuration_document(&secret_path, "first-public");
        let second = first.replace("first-public", "second-public");

        validate_configuration_document(&first)
            .await
            .expect("validate first document");
        initialize_configuration(
            &work_dir,
            &first,
            MintInitializationMode::New,
            BdkWalletPolicy::RequireExisting,
            password.clone(),
        )
        .await
        .expect("initialize configuration");
        assert_eq!(
            stored_configuration_document(&work_dir, password.clone())
                .await
                .expect("read stored document"),
            first
        );

        let validate_only = apply_configuration(
            &work_dir,
            &second,
            true,
            BdkWalletPolicy::RequireExisting,
            password.clone(),
        )
        .await
        .expect("validate-only apply");
        assert!(!validate_only.restart_required);
        assert_eq!(
            stored_configuration_document(&work_dir, password.clone())
                .await
                .expect("document unchanged"),
            first
        );

        let applied = apply_configuration(
            &work_dir,
            &second,
            false,
            BdkWalletPolicy::RequireExisting,
            password.clone(),
        )
        .await
        .expect("apply replacement");
        assert!(applied.restart_required);
        assert_eq!(
            stored_configuration_document(&work_dir, password)
                .await
                .expect("replacement stored"),
            second
        );

        let bootstrap = load_database_bootstrap_settings().expect("bootstrap settings");
        assert_eq!(bootstrap.database.engine, DatabaseEngine::Sqlite);
        assert!(bootstrap.database.postgres.is_none());

        let _ = fs::remove_dir_all(&work_dir);
    }

    #[cfg(all(feature = "sqlite", feature = "fakewallet"))]
    #[tokio::test]
    async fn existing_mint_initialization_rejects_empty_database_with_matching_mnemonic() {
        let work_dir = crate::test_utils::unique_temp_path("cdk_mintd_empty_existing_init");
        fs::create_dir_all(&work_dir).expect("create work dir");
        let secret_path = work_dir.join("mnemonic.secret");
        fs::write(&secret_path, TEST_MNEMONIC).expect("write mnemonic secret");
        let document = sqlite_configuration_document(&secret_path, "empty-existing");

        #[cfg(feature = "sqlcipher")]
        let password = Some("test-password".to_string());
        #[cfg(not(feature = "sqlcipher"))]
        let password: Option<String> = None;

        let error = initialize_configuration(
            &work_dir,
            &document,
            MintInitializationMode::Existing,
            BdkWalletPolicy::RequireExisting,
            password,
        )
        .await
        .expect_err("an empty database must not be accepted as an existing mint");
        assert!(
            error
                .to_string()
                .contains("does not contain a mint identity"),
            "unexpected error: {error}"
        );

        let _ = fs::remove_dir_all(&work_dir);
    }

    #[cfg(all(feature = "sqlite", feature = "fakewallet"))]
    #[tokio::test]
    async fn initialization_mode_distinguishes_existing_mint_state() {
        let work_dir = crate::test_utils::unique_temp_path("cdk_mintd_existing_init");
        fs::create_dir_all(&work_dir).expect("create work dir");
        let secret_path = work_dir.join("mnemonic.secret");
        fs::write(&secret_path, TEST_MNEMONIC).expect("write mnemonic secret");
        let document = sqlite_configuration_document(&secret_path, "existing");

        #[cfg(feature = "sqlcipher")]
        let password = Some("test-password".to_string());
        #[cfg(not(feature = "sqlcipher"))]
        let password: Option<String> = None;

        let bootstrap = load_database_bootstrap_settings().expect("bootstrap settings");
        let (localstore, keystore, _kv, _configuration_store) =
            initial_setup(&work_dir, &bootstrap, password.clone())
                .await
                .expect("initialize database");
        let mut builder = MintBuilder::new(localstore);
        builder
            .configure_unit(CurrencyUnit::Sat, Default::default())
            .expect("configure sat unit");
        let mnemonic = Mnemonic::parse(TEST_MNEMONIC).expect("test mnemonic");
        let mint = builder
            .build_with_seed(keystore, &mnemonic.to_seed_normalized(""))
            .await
            .expect("create existing mint state");
        drop(mint);

        let error = initialize_configuration(
            &work_dir,
            &document,
            MintInitializationMode::New,
            BdkWalletPolicy::RequireExisting,
            password.clone(),
        )
        .await
        .expect_err("existing state must not be accepted as a new mint");
        assert!(
            error
                .to_string()
                .contains("contains existing mint identity or keyset state"),
            "unexpected error: {error}"
        );

        initialize_configuration(
            &work_dir,
            &document,
            MintInitializationMode::Existing,
            BdkWalletPolicy::RequireExisting,
            password,
        )
        .await
        .expect("matching existing mint state should initialize");

        let _ = fs::remove_dir_all(&work_dir);
    }

    #[cfg(all(feature = "sqlite", feature = "bdk"))]
    #[tokio::test]
    async fn existing_mint_requires_explicit_new_bdk_wallet_intent() {
        let work_dir = crate::test_utils::unique_temp_path("cdk_mintd_existing_bdk_init");
        fs::create_dir_all(&work_dir).expect("create work dir");
        let secret_path = work_dir.join("mnemonic.secret");
        fs::write(&secret_path, TEST_MNEMONIC).expect("write mnemonic secret");
        let document = sqlite_bdk_configuration_document(&secret_path, "existing-with-missing-bdk");

        #[cfg(feature = "sqlcipher")]
        let password = Some("test-password".to_string());
        #[cfg(not(feature = "sqlcipher"))]
        let password: Option<String> = None;

        let bootstrap = load_database_bootstrap_settings().expect("bootstrap settings");
        let (localstore, keystore, _kv, _configuration_store) =
            initial_setup(&work_dir, &bootstrap, password.clone())
                .await
                .expect("initialize database");
        let mut builder = MintBuilder::new(localstore);
        builder
            .configure_unit(CurrencyUnit::Sat, Default::default())
            .expect("configure sat unit");
        let mnemonic = Mnemonic::parse(TEST_MNEMONIC).expect("test mnemonic");
        drop(
            builder
                .build_with_seed(keystore, &mnemonic.to_seed_normalized(""))
                .await
                .expect("create existing mint state"),
        );

        let error = initialize_configuration(
            &work_dir,
            &document,
            MintInitializationMode::Existing,
            BdkWalletPolicy::RequireExisting,
            password.clone(),
        )
        .await
        .expect_err("missing BDK wallet must fail closed");
        assert!(
            error
                .to_string()
                .contains("Persisted BDK wallet database is missing"),
            "unexpected error: {error}"
        );

        initialize_configuration(
            &work_dir,
            &document,
            MintInitializationMode::Existing,
            BdkWalletPolicy::AllowNew,
            password.clone(),
        )
        .await
        .expect("explicit new-wallet intent should permit initialization");

        let error = apply_configuration(
            &work_dir,
            &document,
            true,
            BdkWalletPolicy::RequireExisting,
            password,
        )
        .await
        .expect_err("apply preflight must also reject a missing BDK wallet");
        assert!(error
            .to_string()
            .contains("Persisted BDK wallet database is missing"));
        assert!(!work_dir.join("bdk_wallet/bdk_wallet.sqlite").exists());

        let _ = fs::remove_dir_all(&work_dir);
    }

    #[test]
    fn load_database_bootstrap_settings_defaults_to_sqlite() {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        std::env::remove_var(env_vars::DATABASE_ENV_VAR);

        let settings = load_database_bootstrap_settings().expect("default bootstrap");
        assert_eq!(settings.database.engine, DatabaseEngine::Sqlite);
        assert!(settings.database.postgres.is_none());
        clear_mintd_env();
    }

    #[test]
    fn apply_seed_file_sets_mint_mnemonic_from_trimmed_file_contents() {
        let seed_file = temp_seed_file("seed_file_sets_seed");
        fs::write(&seed_file, format!("  {TEST_MNEMONIC}\n")).expect("seed file should be written");
        let mut settings = config::Settings {
            info: config::Info {
                seed: Some("raw seed from config".to_string()),
                mnemonic: Some("mnemonic from config".to_string()),
                ..Default::default()
            },
            signatory: Some(config::Signatory {
                enabled: true,
                address: "127.0.0.1".to_string(),
                port: 15060,
                tls_dir: Some("/tmp/certs".into()),
                allow_insecure: false,
            }),
            ..Default::default()
        };

        apply_seed_file(&mut settings, &seed_file).expect("seed file should be applied");

        assert_eq!(settings.info.seed, None);
        assert_eq!(settings.info.mnemonic, Some(TEST_MNEMONIC.to_string()));
        assert_eq!(
            settings
                .signatory
                .as_ref()
                .map(|signatory| signatory.address.clone()),
            Some("127.0.0.1".to_string())
        );
        assert_eq!(
            settings.signatory.as_ref().map(|signatory| signatory.port),
            Some(15060)
        );
        assert_eq!(
            settings
                .signatory
                .as_ref()
                .and_then(|signatory| signatory.tls_dir.clone()),
            Some("/tmp/certs".into())
        );

        let _ = fs::remove_file(&seed_file);
    }

    #[cfg(feature = "bdk")]
    #[test]
    fn apply_seed_file_sets_active_bdk_mnemonic() {
        use crate::config::{Bdk, Onchain, OnchainBackend};

        let seed_file = temp_seed_file("seed_file_sets_bdk_seed");
        fs::write(&seed_file, TEST_MNEMONIC).expect("seed file should be written");
        let mut settings = config::Settings {
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::Bdk,
                ..Default::default()
            }),
            bdk: Some(Bdk {
                mnemonic: Some("old bdk mnemonic".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };

        apply_seed_file(&mut settings, &seed_file).expect("seed file should be applied");

        assert_eq!(
            settings
                .bdk
                .expect("bdk settings should be present")
                .mnemonic,
            Some(TEST_MNEMONIC.to_string())
        );

        let _ = fs::remove_file(&seed_file);
    }

    #[cfg(feature = "ldk-node")]
    #[test]
    fn apply_seed_file_sets_active_ldk_node_mnemonic() {
        use crate::config::{LdkNode, PaymentBackend, PaymentBackendType};

        let seed_file = temp_seed_file("seed_file_sets_ldk_seed");
        fs::write(&seed_file, TEST_MNEMONIC).expect("seed file should be written");
        let mut settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::LdkNode,
                ..Default::default()
            }],
            ldk_node: Some(LdkNode {
                ldk_node_mnemonic: Some("old ldk mnemonic".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };

        apply_seed_file(&mut settings, &seed_file).expect("seed file should be applied");

        assert_eq!(
            settings
                .ldk_node
                .expect("ldk node settings should be present")
                .ldk_node_mnemonic,
            Some(TEST_MNEMONIC.to_string())
        );

        let _ = fs::remove_file(&seed_file);
    }

    #[test]
    fn apply_seed_file_rejects_empty_seed_file() {
        let seed_file = temp_seed_file("empty_seed_file");
        fs::write(&seed_file, "\n\t ").expect("seed file should be written");
        let mut settings = config::Settings::default();

        let err = apply_seed_file(&mut settings, &seed_file)
            .expect_err("empty seed file should be rejected");

        assert!(err.to_string().contains("is empty"));
        assert_eq!(settings.info.seed, None);

        let _ = fs::remove_file(&seed_file);
    }

    #[test]
    fn apply_seed_file_rejects_invalid_seed_phrase() {
        let seed_file = temp_seed_file("invalid_seed_file");
        fs::write(&seed_file, "not a valid seed phrase").expect("seed file should be written");
        let mut settings = config::Settings::default();

        let err = apply_seed_file(&mut settings, &seed_file)
            .expect_err("invalid seed phrase should be rejected");

        assert!(err.to_string().contains("Invalid seed phrase"));
        assert_eq!(settings.info.mnemonic, None);

        let _ = fs::remove_file(&seed_file);
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn load_settings_from_args_applies_seed_file_before_validation() {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();

        let temp_dir = crate::test_utils::unique_temp_path("seed_file_only_signing");
        fs::create_dir_all(&temp_dir).expect("temp directory should be created");
        let config_path = temp_dir.join("config.toml");
        fs::write(
            &config_path,
            r#"
[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
        )
        .expect("config file should be written");
        let seed_file = temp_dir.join("seed.txt");
        fs::write(&seed_file, TEST_MNEMONIC).expect("seed file should be written");

        let args = CLIArgs {
            work_dir: None,
            #[cfg(feature = "sqlcipher")]
            password: Some("test-password".to_string()),
            config: Some(config_path),
            seed_file: Some(seed_file),
            enable_logging: false,
            command: None,
        };

        let settings = load_settings_from_args(&temp_dir, &args)
            .expect("seed-file-only signing should pass validation");

        assert_eq!(settings.info.mnemonic.as_deref(), Some(TEST_MNEMONIC));
        let _ = fs::remove_dir_all(&temp_dir);
        clear_mintd_env();
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn fakewallet_dispatcher_uses_payment_backend_entry_unit() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{FakeWallet, PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::FakeWallet,
                unit: CurrencyUnit::Eur,
                ..Default::default()
            }],
            fake_wallet: Some(FakeWallet::default()),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder =
            configure_payment_backends(&settings, builder, None, &std::env::temp_dir(), None)
                .await
                .expect("dispatcher should succeed");

        let mint_info = builder.current_mint_info();
        let units: Vec<_> = mint_info
            .nuts
            .nut04
            .methods
            .iter()
            .map(|m| m.unit.clone())
            .collect();
        assert!(
            units.contains(&CurrencyUnit::Eur),
            "expected Eur, got {units:?}"
        );
        assert!(
            !units.contains(&CurrencyUnit::Sat),
            "Sat would only appear if supported_units leaked through; got {units:?}"
        );
    }

    #[test]
    fn backend_unit_validation_allows_matching_units() {
        validate_backend_unit(&CurrencyUnit::Eur, "EUR").expect("matching units should pass");
    }

    #[test]
    fn backend_unit_validation_allows_sat_msat_pair() {
        validate_backend_unit(&CurrencyUnit::Sat, "MSAT")
            .expect("sat/msat compatible units should pass");
        validate_backend_unit(&CurrencyUnit::Msat, "SAT")
            .expect("msat/sat compatible units should pass");
    }

    #[test]
    fn backend_unit_validation_rejects_unsupported_conversion() {
        let err = validate_backend_unit(&CurrencyUnit::Eur, "SAT")
            .expect_err("sat backend should not advertise eur");

        assert!(
            err.to_string().contains("only matching units"),
            "error should explain the supported conversions: {err}"
        );
    }

    #[cfg(feature = "cln")]
    #[test]
    fn expand_path_expands_bare_tilde_without_panic() {
        let expanded = expand_path("~");

        assert_eq!(expanded, home::home_dir());
    }

    #[cfg(feature = "cln")]
    #[test]
    fn expand_path_keeps_named_tilde_paths_literal() {
        let expanded = expand_path("~foo").expect("path should be returned");

        assert_eq!(expanded, PathBuf::from("~foo"));
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn duplicate_payment_backend_unit_method_pair_is_rejected() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{FakeWallet, PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![
                PaymentBackend {
                    backend: PaymentBackendType::FakeWallet,
                    unit: CurrencyUnit::Sat,
                    ..Default::default()
                },
                PaymentBackend {
                    backend: PaymentBackendType::FakeWallet,
                    unit: CurrencyUnit::Sat,
                    ..Default::default()
                },
            ],
            fake_wallet: Some(FakeWallet::default()),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let err = configure_payment_backends(&settings, builder, None, &std::env::temp_dir(), None)
            .await
            .expect_err("duplicate unit/method pair should be rejected");

        assert!(err.to_string().contains("Duplicate payment processor"));
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn empty_payment_backend_vec_returns_unchanged_builder() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        let settings = config::Settings {
            payment_backend: vec![],
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder =
            configure_payment_backends(&settings, builder, None, &std::env::temp_dir(), None)
                .await
                .expect("empty payment_backend should succeed");

        let mint_info = builder.current_mint_info();
        assert!(
            mint_info.nuts.nut04.methods.is_empty(),
            "no backends should be registered"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn payment_backend_none_logs_and_continues() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::None,
                unit: CurrencyUnit::Sat,
                ..Default::default()
            }],
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder =
            configure_payment_backends(&settings, builder, None, &std::env::temp_dir(), None)
                .await
                .expect("PaymentBackendType::None should succeed");

        let mint_info = builder.current_mint_info();
        assert!(
            mint_info.nuts.nut04.methods.is_empty(),
            "PaymentBackendType::None should not register any methods"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn onchain_backend_none_returns_unchanged() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{Onchain, OnchainBackend};

        let settings = config::Settings {
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::None,
                ..Default::default()
            }),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder =
            configure_onchain_backend(&settings, builder, None, &std::env::temp_dir(), None)
                .await
                .expect("OnchainBackend::None should succeed");

        let mint_info = builder.current_mint_info();
        assert!(
            mint_info.nuts.nut04.methods.is_empty(),
            "OnchainBackend::None should not register any methods"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn fakewallet_onchain_no_payment_backend_configures_onchain_methods() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{
            FakeWallet, Onchain, OnchainBackend, PaymentBackend, PaymentBackendType,
        };

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::None,
                ..Default::default()
            }],
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::FakeWallet,
                ..Default::default()
            }),
            fake_wallet: Some(FakeWallet::default()),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder =
            configure_onchain_backend(&settings, builder, None, &std::env::temp_dir(), None)
                .await
                .expect("fakewallet onchain should succeed");

        let mint_info = builder.current_mint_info();
        let methods: Vec<_> = mint_info
            .nuts
            .nut04
            .methods
            .iter()
            .map(|m| m.method.clone())
            .collect();
        assert!(
            methods.contains(&PaymentMethod::Known(KnownMethod::Onchain)),
            "expected onchain method, got {methods:?}"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "cln", feature = "sqlite"))]
    #[tokio::test]
    async fn fakewallet_onchain_with_real_payment_backend_bails() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{Onchain, OnchainBackend, PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::Cln,
                unit: CurrencyUnit::Sat,
                ..Default::default()
            }],
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::FakeWallet,
                ..Default::default()
            }),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let err = configure_onchain_backend(&settings, builder, None, &std::env::temp_dir(), None)
            .await
            .expect_err("fakewallet onchain with real payment backend should bail");

        assert!(
            err.to_string().contains("fakewallet"),
            "error should mention fakewallet: {err}"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn configure_mint_builder_no_backends_bails() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::None,
                ..Default::default()
            }],
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let err = configure_mint_builder(&settings, builder, None, &std::env::temp_dir(), None)
            .await
            .expect_err("no payment backends should bail");

        assert!(
            err.to_string().contains("At least one payment backend"),
            "error should mention missing backends: {err}"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite", feature = "bdk"))]
    #[tokio::test]
    async fn configure_mint_builder_fake_wallet_with_bdk_onchain_bails() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{
            Bdk, FakeWallet, Onchain, OnchainBackend, PaymentBackend, PaymentBackendType,
        };

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::FakeWallet,
                ..Default::default()
            }],
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::Bdk,
                ..Default::default()
            }),
            fake_wallet: Some(FakeWallet::default()),
            bdk: Some(Bdk {
                network: Some("mainnet".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let err = configure_mint_builder(&settings, builder, None, &std::env::temp_dir(), None)
            .await
            .expect_err("fake wallet with BDK onchain should bail");

        assert!(
            err.to_string().contains("fakewallet") && err.to_string().contains("bdk"),
            "error should mention backend pairing validation: {err}"
        );
    }

    #[cfg(all(feature = "management-rpc", feature = "bdk", feature = "sqlite"))]
    #[tokio::test]
    async fn bdk_onchain_exposes_wallet_info_provider() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{Bdk, Onchain, OnchainBackend};

        let work_dir = test_utils::unique_temp_path("cdk_mintd_wallet_info_provider");
        let settings = config::Settings {
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::Bdk,
                ..Default::default()
            }),
            bdk: Some(Bdk {
                network: Some("regtest".to_string()),
                chain_source_type: Some("esplora".to_string()),
                esplora_url: Some("http://127.0.0.1:1".to_string()),
                mnemonic: Some(
                    "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
                        .to_string(),
                ),
                ..Default::default()
            }),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.expect("in-memory database"));
        let builder = MintBuilder::new(localstore.clone());
        let (builder, provider) = configure_onchain_backend_with_wallet_info(
            &settings,
            builder,
            None,
            &work_dir,
            Some(localstore),
        )
        .await
        .expect("configure BDK backend");

        assert!(builder
            .current_mint_info()
            .nuts
            .nut04
            .methods
            .iter()
            .any(|method| method.method == PaymentMethod::Known(KnownMethod::Onchain)));

        let provider = provider.expect("wallet info provider");
        let first_address = provider
            .create_deposit_address()
            .await
            .expect("create first operator deposit address");
        let second_address = provider
            .create_deposit_address()
            .await
            .expect("create second operator deposit address");
        assert_ne!(first_address, second_address);

        let addresses = provider
            .list_addresses(0, 20)
            .await
            .expect("list wallet addresses");
        assert_eq!(addresses.total, 2);
        assert!(addresses
            .addresses
            .iter()
            .any(|address| address.address == first_address));
        assert!(addresses
            .addresses
            .iter()
            .any(|address| address.address == second_address));

        let balance = provider.get_balance().await.expect("get wallet balance");
        assert_eq!(balance.network, "regtest");
        assert_eq!(balance.total_sat, 0);

        drop(builder);
        let _ = std::fs::remove_dir_all(work_dir);
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn configure_backend_for_methods_registers_websockets_and_fee() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{FakeWallet, PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::FakeWallet,
                unit: CurrencyUnit::Sat,
                ..Default::default()
            }],
            fake_wallet: Some(FakeWallet::default()),
            info: config::Info {
                input_fee_ppk: Some(100),
                ..Default::default()
            },
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);

        let fake_wallet = settings.fake_wallet.clone().expect("fake wallet config");
        let fake = fake_wallet
            .setup(
                &settings,
                CurrencyUnit::Sat,
                None,
                &std::env::temp_dir(),
                None,
            )
            .await
            .expect("fake wallet setup");

        let mint_melt_limits = cdk::mint::MintMeltLimits {
            mint_min: 1.into(),
            mint_max: 500_000.into(),
            melt_min: 1.into(),
            melt_max: 500_000.into(),
        };

        let builder = configure_backend_for_methods(
            &settings,
            builder,
            CurrencyUnit::Sat,
            mint_melt_limits,
            Arc::new(fake),
            vec![PaymentMethod::Known(KnownMethod::Bolt11)],
        )
        .await
        .expect("configure_backend_for_methods should succeed");

        let mint_info = builder.current_mint_info();
        assert!(
            !mint_info.nuts.nut04.methods.is_empty(),
            "bolt11 method should be registered"
        );
        assert!(
            !mint_info.nuts.nut17.supported.is_empty(),
            "websocket support should be configured"
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn fakewallet_onchain_with_fake_payment_backend_does_not_duplicate() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{
            FakeWallet, Onchain, OnchainBackend, PaymentBackend, PaymentBackendType,
        };

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::FakeWallet,
                unit: CurrencyUnit::Sat,
                ..Default::default()
            }],
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::FakeWallet,
                ..Default::default()
            }),
            fake_wallet: Some(FakeWallet::default()),
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let builder = configure_onchain_backend(
            &settings,
            builder,
            None,
            &std::env::temp_dir(),
            None,
        )
        .await
        .expect("fakewallet onchain with fake payment backend should succeed without duplicating");

        let mint_info = builder.current_mint_info();
        assert!(
            mint_info.nuts.nut04.methods.is_empty(),
            "when has_payment_backend is true and no real payment backend, fakewallet onchain should skip; got {:?}",
            mint_info.nuts.nut04.methods
        );
    }

    #[cfg(all(feature = "fakewallet", feature = "sqlite"))]
    #[tokio::test]
    async fn fakewallet_onchain_missing_fake_wallet_config_bails() {
        use cdk::mint::MintBuilder;
        use cdk_sqlite::mint::memory;

        use crate::config::{Onchain, OnchainBackend, PaymentBackend, PaymentBackendType};

        let settings = config::Settings {
            payment_backend: vec![PaymentBackend {
                backend: PaymentBackendType::None,
                ..Default::default()
            }],
            onchain: Some(Onchain {
                onchain_backend: OnchainBackend::FakeWallet,
                ..Default::default()
            }),
            fake_wallet: None,
            ..Default::default()
        };

        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let err = configure_onchain_backend(&settings, builder, None, &std::env::temp_dir(), None)
            .await
            .expect_err("missing fake_wallet config should bail");

        assert!(
            err.to_string().contains("Fake wallet config"),
            "error should mention missing config: {err}"
        );
    }

    #[test]
    fn test_postgres_auth_url_validation() {
        // Test that the auth database config requires explicit configuration

        // Test empty URL
        let auth_config = config::PostgresAuthConfig {
            url: "".to_string(),
            ..Default::default()
        };
        assert!(auth_config.url.is_empty());

        // Test non-empty URL
        let auth_config = config::PostgresAuthConfig {
            url: "postgresql://user:password@localhost:5432/auth_db".to_string(),
            ..Default::default()
        };
        assert!(!auth_config.url.is_empty());
    }

    #[test]
    fn test_extract_supported_payment_methods_unique_ordered() {
        let mut mint_info = cdk::nuts::MintInfo::default();
        mint_info.nuts.nut04.methods = vec![
            MintMethodSettings {
                method: PaymentMethod::Known(KnownMethod::Bolt11),
                unit: CurrencyUnit::Sat,
                method_name: None,
                min_amount: None,
                max_amount: None,
                options: None,
            },
            MintMethodSettings {
                method: PaymentMethod::Known(KnownMethod::Bolt12),
                unit: CurrencyUnit::Sat,
                method_name: None,
                min_amount: None,
                max_amount: None,
                options: None,
            },
            MintMethodSettings {
                method: PaymentMethod::Known(KnownMethod::Bolt11),
                unit: CurrencyUnit::Msat,
                method_name: None,
                min_amount: None,
                max_amount: None,
                options: None,
            },
            MintMethodSettings {
                method: PaymentMethod::Custom("paypal".to_string()),
                unit: CurrencyUnit::Usd,
                method_name: None,
                min_amount: None,
                max_amount: None,
                options: None,
            },
            MintMethodSettings {
                method: PaymentMethod::Custom("paypal".to_string()),
                unit: CurrencyUnit::Eur,
                method_name: None,
                min_amount: None,
                max_amount: None,
                options: None,
            },
        ];

        let methods = extract_supported_payment_methods(&mint_info);

        assert_eq!(methods, vec!["bolt11", "bolt12", "paypal"]);
    }

    fn clear_mintd_env() {
        for var in [
            "CDK_MINTD_DATABASE",
            "CDK_MINTD_DATABASE_URL",
            "CDK_MINTD_POSTGRES_URL",
            "CDK_MINTD_POSTGRES_TLS_MODE",
            "CDK_MINTD_POSTGRES_MAX_CONNECTIONS",
            "CDK_MINTD_POSTGRES_CONNECTION_TIMEOUT_SECONDS",
            "CDK_MINTD_SEED",
            "CDK_MINTD_MNEMONIC",
            "CDK_MINTD_SIGNATORY_ENABLED",
            "CDK_MINTD_SIGNATORY_ADDRESS",
            "CDK_MINTD_SIGNATORY_PORT",
            "CDK_MINTD_SIGNATORY_TLS_DIR",
            "CDK_MINTD_SIGNATORY_ALLOW_INSECURE",
            "CDK_MINTD_LISTEN_HOST",
            "CDK_MINTD_LISTEN_PORT",
            "CDK_MINTD_PAYMENT_BACKEND",
            "CDK_MINTD_PAYMENT_BACKEND_MIN_MINT",
            "CDK_MINTD_PAYMENT_BACKEND_MAX_MINT",
            "CDK_MINTD_PAYMENT_BACKEND_MIN_MELT",
            "CDK_MINTD_PAYMENT_BACKEND_MAX_MELT",
            "CDK_MINTD_AUTH_ENABLED",
            "CDK_MINTD_AUTH_OPENID_DISCOVERY",
            "CDK_MINTD_AUTH_OPENID_CLIENT_ID",
            "CDK_MINTD_AUTH_MINT_MAX_BAT",
            "CDK_MINTD_AUTH_MINT",
            "CDK_MINTD_AUTH_GET_MINT_QUOTE",
            "CDK_MINTD_AUTH_CHECK_MINT_QUOTE",
            "CDK_MINTD_AUTH_MELT",
            "CDK_MINTD_AUTH_GET_MELT_QUOTE",
            "CDK_MINTD_AUTH_CHECK_MELT_QUOTE",
            "CDK_MINTD_AUTH_SWAP",
            "CDK_MINTD_AUTH_RESTORE",
            "CDK_MINTD_AUTH_CHECK_PROOF_STATE",
            "CDK_MINTD_AUTH_WEBSOCKET",
            "CDK_MINTD_AUTH_POSTGRES_URL",
            "CDK_MINTD_AUTH_POSTGRES_TLS_MODE",
            "CDK_MINTD_AUTH_POSTGRES_MAX_CONNECTIONS",
            "CDK_MINTD_AUTH_POSTGRES_CONNECTION_TIMEOUT_SECONDS",
            "CDK_MINTD_CLN_RPC_PATH",
            "CDK_MINTD_CLN_FEE_PERCENT",
            "CDK_MINTD_LND_ADDRESS",
            "CDK_MINTD_LND_CERT_FILE",
            "CDK_MINTD_LND_MACAROON_FILE",
            "CDK_MINTD_LND_FEE_PERCENT",
            "CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS",
            "CDK_MINTD_FAKE_WALLET_FEE_PERCENT",
            "CDK_MINTD_FAKE_WALLET_RESERVE_FEE_MIN",
            "CDK_MINTD_FAKE_WALLET_MIN_DELAY",
            "CDK_MINTD_FAKE_WALLET_MAX_DELAY",
            "CDK_MINTD_GRPC_PAYMENT_PROCESSOR_SUPPORTED_UNITS",
            "CDK_MINTD_GRPC_PAYMENT_PROCESSOR_ADDRESS",
            "CDK_MINTD_GRPC_PAYMENT_PROCESSOR_PORT",
            "CDK_MINTD_PROMETHEUS_ENABLED",
            "CDK_MINTD_PROMETHEUS_ADDRESS",
            "CDK_MINTD_PROMETHEUS_PORT",
            "CDK_MINTD_MINT_MANAGEMENT_ENABLED",
            "CDK_MINTD_MANAGEMENT_ADDRESS",
            "CDK_MINTD_MANAGEMENT_PORT",
        ] {
            std::env::remove_var(var);
        }
    }

    fn load_settings_from_toml(name: &str, config_content: &str) -> Result<config::Settings> {
        use std::fs;

        let temp_dir = crate::test_utils::unique_temp_path(name);
        let _ = fs::remove_dir_all(&temp_dir);
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
        let config_path = temp_dir.join("config.toml");
        fs::write(&config_path, config_content).expect("Failed to write config file");

        let result = load_settings(&temp_dir, Some(config_path));

        let _ = fs::remove_dir_all(&temp_dir);

        result
    }

    fn assert_load_settings_error(config_content: &str, expected: &str) {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        let err = load_settings_from_toml("cdk_mintd_invalid_config", config_content)
            .expect_err("Settings should fail validation");
        assert!(
            err.to_string().contains(expected),
            "expected error containing `{expected}`, got `{err}`"
        );
    }

    #[cfg(all(feature = "prometheus", feature = "fakewallet"))]
    #[test]
    fn test_load_settings_merges_partial_postgres_toml_with_env() {
        use std::{env, fs};

        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        env::remove_var(crate::env_vars::DATABASE_URL_ENV_VAR);
        env::remove_var(crate::env_vars::ENV_POSTGRES_URL);
        env::remove_var(crate::env_vars::ENV_PROMETHEUS_ENABLED);
        env::remove_var(crate::env_vars::ENV_PROMETHEUS_ADDRESS);
        env::remove_var(crate::env_vars::ENV_PROMETHEUS_PORT);

        let postgres_url = "postgresql://user:password@localhost:5432/cdk_mint";
        env::set_var(crate::env_vars::ENV_POSTGRES_URL, postgres_url);

        let temp_dir = crate::test_utils::unique_temp_path("cdk_mintd_partial_config");
        let _ = fs::remove_dir_all(&temp_dir);
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
        let config_path = temp_dir.join("config.toml");

        let config_content = r#"
[info]
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"

[database]
engine = "postgres"

[database.postgres]
tls_mode = "require"
max_connections = 30
connection_timeout_seconds = 15

[payment_backend]
backend = "fakewallet"

[prometheus]
enabled = true
address = "0.0.0.0"
port = 9090
"#;
        fs::write(&config_path, config_content).expect("Failed to write config file");

        let settings =
            load_settings(&temp_dir, Some(config_path)).expect("Failed to load settings");

        let postgres = settings
            .database
            .postgres
            .as_ref()
            .expect("Postgres config should be present");
        assert_eq!(postgres.url, postgres_url);
        assert_eq!(postgres.tls_mode.as_deref(), Some("require"));

        let prometheus = settings
            .prometheus
            .as_ref()
            .expect("Prometheus config should be loaded from TOML");
        assert!(prometheus.enabled);
        assert_eq!(prometheus.address.as_deref(), Some("0.0.0.0"));
        assert_eq!(prometheus.port, Some(9090));

        env::remove_var(crate::env_vars::ENV_POSTGRES_URL);
        let _ = fs::remove_dir_all(&temp_dir);
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_postgres_url_after_merge() {
        use std::{env, fs};

        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        env::remove_var(crate::env_vars::DATABASE_URL_ENV_VAR);
        env::remove_var(crate::env_vars::ENV_POSTGRES_URL);

        let temp_dir = crate::test_utils::unique_temp_path("cdk_mintd_invalid_config");
        let _ = fs::remove_dir_all(&temp_dir);
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
        let config_path = temp_dir.join("config.toml");

        let config_content = r#"
[info]
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"

[database]
engine = "postgres"

[database.postgres]
tls_mode = "require"

[payment_backend]
backend = "fakewallet"
"#;
        fs::write(&config_path, config_content).expect("Failed to write config file");

        let err = load_settings(&temp_dir, Some(config_path))
            .expect_err("Settings should fail validation without a Postgres URL");
        assert!(err.to_string().contains("PostgreSQL URL is required"));

        let _ = fs::remove_dir_all(&temp_dir);
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_short_seed() {
        assert_load_settings_error(
            r#"
[info]
seed = "tooshort"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            "Seed in [info].seed is too short",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_signing_source() {
        assert_load_settings_error(
            r#"
[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            "No signing source configured",
        );
    }

    #[test]
    fn test_load_settings_reports_missing_payment_backend() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"
"#
            ),
            "At least one payment backend",
        );
    }

    #[cfg(feature = "cln")]
    #[test]
    fn test_load_settings_reports_missing_cln_config() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "cln"
"#
            ),
            "CLN backend selected but [cln] config section is missing",
        );
    }

    #[cfg(feature = "lnd")]
    #[test]
    fn test_load_settings_reports_missing_lnd_config() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "lnd"
"#
            ),
            "LND backend selected but [lnd] config section is missing",
        );
    }

    #[cfg(feature = "grpc-processor")]
    #[test]
    fn test_load_settings_reports_missing_grpc_supported_units() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "grpcprocessor"

[grpc_processor]
addr = "http://127.0.0.1"
"#
            ),
            "gRPC payment processor supported_units must contain at least one unit",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_fakewallet_delay_range() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[fake_wallet]
min_delay_time = 10
max_delay_time = 1
"#
            ),
            "Fake wallet min_delay_time cannot be greater than max_delay_time",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_auth_openid_config() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[auth]
auth_enabled = true
"#
            ),
            "Auth openid_discovery must be set",
        );
    }

    #[test]
    fn test_load_settings_reports_toml_parse_errors() {
        assert_load_settings_error(
            r#"
[info
mnemonic = "not valid toml"
"#,
            "Failed to read config file",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_payment_backend_limit_range() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
min_mint = 10
max_mint = 1
"#
            ),
            "Payment backend min_mint cannot be greater than max_mint",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_merges_partial_onchain_config_with_defaults() {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();

        let settings = load_settings_from_toml(
            "cdk_mintd_partial_onchain_config",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[onchain]
onchain_backend = "fakewallet"

[fake_wallet]
"#
            ),
        )
        .expect("partial on-chain config should use defaults");

        let onchain = settings.onchain.expect("on-chain config should be present");
        assert_eq!(onchain.min_mint, 1.into());
        assert_eq!(onchain.max_mint, 500_000.into());
        assert_eq!(onchain.min_melt, 1.into());
        assert_eq!(onchain.max_melt, 500_000.into());
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_onchain_mint_limit_range() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[onchain]
onchain_backend = "fakewallet"
min_mint = 10
max_mint = 1
"#
            ),
            "On-chain min_mint cannot be greater than max_mint",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_onchain_melt_limit_range() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[onchain]
onchain_backend = "fakewallet"
min_melt = 10
max_melt = 1
"#
            ),
            "On-chain min_melt cannot be greater than max_melt",
        );
    }

    #[cfg(all(feature = "prometheus", feature = "fakewallet"))]
    #[test]
    fn test_load_settings_reports_invalid_prometheus_address() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[prometheus]
enabled = true
address = "localhost"
port = 9090
"#
            ),
            "Invalid Prometheus address",
        );
    }

    #[cfg(all(feature = "management-rpc", feature = "fakewallet"))]
    #[test]
    fn test_load_settings_reports_invalid_management_rpc_address() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[mint_management_rpc]
enabled = true
address = "localhost"
port = 8086
"#
            ),
            "Invalid mint management RPC address",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_valid_config() {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        load_settings_from_toml(
            "cdk_mintd_valid",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
        )
        .expect("valid config should load without error");
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_valid_config_with_insecure_signatory() {
        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();
        load_settings_from_toml(
            "cdk_mintd_valid_signatory",
            r#"
[signatory]
enabled = true
allow_insecure = true

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
        )
        .expect("valid config with an insecure signatory should load without error");
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_rejects_signatory_without_tls() {
        assert_load_settings_error(
            r#"
[signatory]
enabled = true

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            "gRPC signatory TLS is not configured",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_rejects_empty_seed_before_mnemonic() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
seed = ""
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
            "Seed in [info].seed must not be empty",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_mnemonic() {
        assert_load_settings_error(
            r#"
[info]
mnemonic = "not a valid mnemonic phrase at all"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            "Invalid mnemonic",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_listen_address() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"
listen_host = "999.999.999.999"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
            "Invalid mint listen address",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_auth_openid_client_id() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[auth]
auth_enabled = true
openid_discovery = "https://issuer.example.com/.well-known/openid-configuration"
"#
            ),
            "Auth openid_client_id must be set",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_invalid_melt_limit_range() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
min_melt = 10
max_melt = 1
"#
            ),
            "Payment backend min_melt cannot be greater than max_melt",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_fakewallet_supported_units() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"

[fake_wallet]
supported_units = []
"#
            ),
            "Fake wallet supported_units must contain at least one unit",
        );
    }

    #[cfg(feature = "lnd")]
    #[test]
    fn test_load_settings_reports_missing_lnd_cert_file() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "lnd"

[lnd]
address = "127.0.0.1:10009"
"#
            ),
            "LND cert_file must be set",
        );
    }

    #[cfg(feature = "lnd")]
    #[test]
    fn test_load_settings_reports_missing_lnd_macaroon_file() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "lnd"

[lnd]
address = "127.0.0.1:10009"
cert_file = "/path/to/tls.cert"
"#
            ),
            "LND macaroon_file must be set",
        );
    }

    #[cfg(feature = "grpc-processor")]
    #[test]
    fn test_load_settings_reports_missing_grpc_processor_address() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "grpcprocessor"

[grpc_processor]
supported_units = ["sat"]
address = ""
"#
            ),
            "gRPC payment processor address must be set",
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_load_settings_reports_missing_auth_postgres_url() {
        assert_load_settings_error(
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "postgres"

[database.postgres]
url = "postgresql://user:password@localhost:5432/cdk_mint"

[payment_backend]
backend = "fakewallet"

[auth]
auth_enabled = true
openid_discovery = "https://issuer.example.com/.well-known/openid-configuration"
openid_client_id = "mintd"
"#
            ),
            "Auth database PostgreSQL URL is required",
        );
    }

    fn load_settings_with_env(
        name: &str,
        config_content: &str,
        setup_env: impl FnOnce(),
    ) -> Result<config::Settings> {
        use std::fs;

        let _env_lock = crate::test_utils::env_lock();
        clear_mintd_env();

        let temp_dir = crate::test_utils::unique_temp_path(name);
        let _ = fs::remove_dir_all(&temp_dir);
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
        let config_path = temp_dir.join("config.toml");
        fs::write(&config_path, config_content).expect("Failed to write config file");

        setup_env();

        let result = load_settings(&temp_dir, Some(config_path));
        let _ = fs::remove_dir_all(&temp_dir);
        clear_mintd_env();
        result
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn env_only_auth_preserves_protected_endpoint_defaults() {
        let settings = load_settings_with_env(
            "cdk_mintd_env_auth_defaults",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
            || {
                std::env::set_var("CDK_MINTD_AUTH_ENABLED", "true");
                std::env::set_var(
                    "CDK_MINTD_AUTH_OPENID_DISCOVERY",
                    "https://issuer.example.com/.well-known/openid-configuration",
                );
                std::env::set_var("CDK_MINTD_AUTH_OPENID_CLIENT_ID", "mintd");
            },
        )
        .expect("environment-only auth configuration should load");

        let auth = settings.auth.expect("auth should be enabled");
        assert_eq!(auth.mint, config::AuthType::Blind);
        assert_eq!(auth.swap, config::AuthType::Blind);
        assert_eq!(auth.restore, config::AuthType::Blind);
        assert_eq!(auth.websocket_auth, config::AuthType::Blind);
    }

    #[cfg(feature = "lnd")]
    #[test]
    fn invalid_lnd_fee_percent_from_env_is_rejected() {
        for (name, fee_percent) in [
            ("nan", "NaN"),
            ("negative", "-1"),
            ("not-a-number", "invalid"),
        ] {
            let error = load_settings_with_env(
                &format!("cdk_mintd_lnd_fee_percent_{name}"),
                &format!(
                    r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"

[payment_backend]
backend = "lnd"
"#
                ),
                || {
                    std::env::set_var("CDK_MINTD_LND_ADDRESS", "https://127.0.0.1:10009");
                    std::env::set_var("CDK_MINTD_LND_CERT_FILE", "/certs/tls.cert");
                    std::env::set_var("CDK_MINTD_LND_MACAROON_FILE", "/data/admin.macaroon");
                    std::env::set_var("CDK_MINTD_LND_FEE_PERCENT", fee_percent);
                },
            )
            .expect_err("invalid LND fee percentage should fail startup validation");

            assert!(
                error.to_string().contains("CDK_MINTD_LND_FEE_PERCENT"),
                "unexpected error for {fee_percent}: {error}"
            );
        }
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_env_var_provides_mnemonic_when_toml_has_none() {
        let settings = load_settings_with_env(
            "cdk_mintd_env_mnemonic",
            r#"
[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            || std::env::set_var("CDK_MINTD_MNEMONIC", TEST_MNEMONIC),
        )
        .expect("valid config with env mnemonic should load");

        let mnemonic = settings
            .info
            .mnemonic
            .expect("mnemonic should be set from env");
        assert_eq!(mnemonic, TEST_MNEMONIC);
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_env_var_provides_seed_when_toml_has_none() {
        let seed = "a".repeat(32);
        let settings = load_settings_with_env(
            "cdk_mintd_env_seed",
            r#"
[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#,
            || std::env::set_var("CDK_MINTD_SEED", &seed),
        )
        .expect("valid config with env seed should load");

        let loaded_seed = settings.info.seed.expect("seed should be set from env");
        assert_eq!(loaded_seed, seed);
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_env_var_provides_payment_backend_when_toml_has_none() {
        let settings = load_settings_with_env(
            "cdk_mintd_env_payment_backend_only",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"

[database]
engine = "sqlite"
"#
            ),
            || {
                std::env::set_var("CDK_MINTD_PAYMENT_BACKEND", "fakewallet");
                std::env::set_var("CDK_MINTD_PAYMENT_BACKEND_MIN_MINT", "10");
            },
        )
        .expect("env-only payment backend config should load");

        assert_eq!(settings.payment_backend.len(), 1);
        assert_eq!(
            settings.payment_backend[0].backend,
            config::PaymentBackendType::FakeWallet
        );
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_env_var_overrides_toml_listen_host() {
        let settings = load_settings_with_env(
            "cdk_mintd_env_override_listen",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"
listen_host = "127.0.0.1"

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
            || std::env::set_var("CDK_MINTD_LISTEN_HOST", "0.0.0.0"),
        )
        .expect("config with env override should load");

        assert_eq!(settings.info.listen_host, "0.0.0.0");
    }

    #[cfg(feature = "fakewallet")]
    #[test]
    fn test_env_var_overrides_toml_listen_port() {
        let settings = load_settings_with_env(
            "cdk_mintd_env_override_port",
            &format!(
                r#"
[info]
mnemonic = "{TEST_MNEMONIC}"
listen_port = 8080

[database]
engine = "sqlite"

[payment_backend]
backend = "fakewallet"
"#
            ),
            || std::env::set_var("CDK_MINTD_LISTEN_PORT", "9090"),
        )
        .expect("config with env port override should load");

        assert_eq!(settings.info.listen_port, 9090);
    }
}