perf-sentinel-core 0.4.3

Core library for perf-sentinel: polyglot performance anti-pattern detector
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
//! Configuration parsing for `.perf-sentinel.toml`.
//!
//! Supports both the new sectioned format (`[thresholds]`, `[detection]`, `[green]`, `[daemon]`)
//! and the legacy flat format for backward compatibility.

use std::borrow::Cow;
use std::collections::HashMap;

use serde::Deserialize;

use std::time::Duration;

use crate::detect::Confidence;
use crate::score::carbon::DEFAULT_EMBODIED_CARBON_PER_REQUEST_GCO2;
use crate::score::cloud_energy::config::{CloudEnergyConfig, ServiceCloudConfig};
use crate::score::scaphandre::ScaphandreConfig;

/// Top-level configuration for perf-sentinel.
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)] // Config aggregates all toggles from .perf-sentinel.toml
pub struct Config {
    // --- Thresholds ---
    /// Maximum allowed critical N+1 SQL findings before quality gate fails.
    pub n_plus_one_sql_critical_max: u32,
    /// Maximum allowed warning+ N+1 HTTP findings before quality gate fails.
    pub n_plus_one_http_warning_max: u32,
    /// Maximum allowed I/O waste ratio before quality gate fails.
    pub io_waste_ratio_max: f64,

    // --- Detection ---
    /// N+1 detection threshold: minimum repeated similar queries to flag.
    pub n_plus_one_threshold: u32,
    /// Sliding window duration in milliseconds for N+1 detection.
    pub window_duration_ms: u64,
    /// Threshold in milliseconds above which an operation is considered slow.
    pub slow_query_threshold_ms: u64,
    /// Minimum occurrences of a slow template to flag as a finding.
    pub slow_query_min_occurrences: u32,
    /// Maximum child spans per parent before flagging excessive fanout.
    pub max_fanout: u32,
    /// Minimum HTTP outbound calls per trace to flag as chatty service.
    pub chatty_service_min_calls: u32,
    /// Peak concurrent SQL spans per service to flag pool saturation.
    pub pool_saturation_concurrent_threshold: u32,
    /// Minimum sequential independent sibling calls to flag as serialized.
    pub serialized_min_sequential: u32,

    // --- Green ---
    /// Whether `GreenOps` scoring is enabled.
    pub green_enabled: bool,
    /// Fallback region for COâ‚‚ scoring (e.g. `"eu-west-3"`).
    pub green_default_region: Option<String>,
    /// Per-service region overrides. Keys lowercased at load time.
    pub green_service_regions: HashMap<String, String>,
    /// SCI `M` term: embodied carbon per request (gCOâ‚‚eq).
    pub green_embodied_carbon_per_request_gco2: f64,
    /// Use 24-hour carbon intensity profiles when available.
    pub green_use_hourly_profiles: bool,
    /// Scaphandre RAPL scraper config (daemon only).
    pub green_scaphandre: Option<ScaphandreConfig>,
    /// Cloud CPU% + `SPECpower` config (daemon only).
    pub green_cloud_energy: Option<CloudEnergyConfig>,
    /// Whether to use per-operation energy coefficients (SQL verb weighting,
    /// HTTP payload size tiers) in the proxy model. Default: `true`.
    pub green_per_operation_coefficients: bool,
    /// Whether to compute a network transport energy term for cross-region
    /// HTTP calls. Default: `false` (opt-in).
    pub green_include_network_transport: bool,
    /// Energy per byte for network transport (kWh/byte).
    /// Default: 0.04 kWh/GB (Mytton et al. 2024).
    pub green_network_energy_per_byte_kwh: f64,
    /// Path to user-supplied hourly profiles JSON file. `None` when not
    /// configured (uses only embedded profiles).
    pub green_hourly_profiles_file: Option<String>,
    /// Pre-parsed custom hourly profiles, loaded at config parse time.
    /// `None` when `hourly_profiles_file` is not set or failed to load.
    pub green_custom_hourly_profiles:
        Option<std::sync::Arc<HashMap<String, crate::score::carbon::HourlyProfile>>>,
    /// Path to a calibration TOML file generated by `perf-sentinel calibrate`.
    pub green_calibration_file: Option<String>,
    /// Pre-loaded calibration data, parsed at config load time.
    /// `None` when `calibration_file` is not set or failed to load.
    pub green_calibration: Option<crate::calibrate::CalibrationData>,
    /// Electricity Maps real-time carbon intensity config (daemon only).
    pub green_electricity_maps: Option<crate::score::electricity_maps::ElectricityMapsConfig>,

    // --- Daemon ---
    /// Address for the daemon to listen on.
    pub listen_addr: String,
    /// Port for OTLP HTTP receiver.
    pub listen_port: u16,
    /// Port for OTLP gRPC receiver.
    pub listen_port_grpc: u16,
    /// Unix socket path for JSON ingestion.
    pub json_socket: String,
    /// Maximum number of active traces in streaming mode.
    pub max_active_traces: usize,
    /// Trace TTL in milliseconds for streaming mode eviction.
    pub trace_ttl_ms: u64,
    /// Sampling rate for incoming traces (0.0 - 1.0).
    pub sampling_rate: f64,
    /// Maximum events kept per trace (ring buffer size).
    pub max_events_per_trace: usize,
    /// Maximum payload size in bytes for JSON deserialization.
    pub max_payload_size: usize,
    /// Deployment environment label used by the daemon to stamp findings
    /// with a [`Confidence`] value. Defaults to
    /// [`DaemonEnvironment::Staging`]; set to
    /// [`DaemonEnvironment::Production`] when running on production traffic
    /// so downstream consumers (perf-lint) can boost severity. Ignored in
    /// `analyze` batch mode, which always emits [`Confidence::CiBatch`].
    pub daemon_environment: DaemonEnvironment,
    /// Path to PEM-encoded TLS certificate chain for the OTLP receivers.
    /// When set alongside [`tls_key_path`], both gRPC and HTTP listeners
    /// use TLS. When absent, listeners use plain TCP (default).
    pub tls_cert_path: Option<String>,
    /// Path to PEM-encoded TLS private key for the OTLP receivers.
    pub tls_key_path: Option<String>,
    /// Maximum number of findings retained by the daemon query API.
    pub max_retained_findings: usize,
    /// Whether the daemon query API is enabled.
    pub daemon_api_enabled: bool,
    /// Whether cross-trace correlation is enabled (opt-in, default false).
    pub correlation_enabled: bool,
    /// Cross-trace correlation config. Only used when `correlation_enabled` is true.
    pub correlation_config: crate::detect::correlate_cross::CorrelationConfig,
}

/// Deployment environment for the daemon's `watch` mode.
///
/// Maps 1:1 to [`Confidence`] via [`Config::confidence`]:
/// - [`Self::Staging`] → [`Confidence::DaemonStaging`]
/// - [`Self::Production`] → [`Confidence::DaemonProduction`]
///
/// Parsed from the `[daemon] environment` TOML field as case-insensitive
/// `"staging"` or `"production"`. Any other value is rejected at load time
/// with a clear validation error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DaemonEnvironment {
    /// Staging traffic, medium confidence. Default.
    #[default]
    Staging,
    /// Production traffic, high confidence.
    Production,
}

impl DaemonEnvironment {
    /// Returns the lowercase string label used in the TOML config.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Staging => "staging",
            Self::Production => "production",
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            // Thresholds
            n_plus_one_sql_critical_max: 0,
            n_plus_one_http_warning_max: 3,
            io_waste_ratio_max: 0.30,
            // Detection
            n_plus_one_threshold: 5,
            window_duration_ms: 500,
            slow_query_threshold_ms: 500,
            slow_query_min_occurrences: 3,
            max_fanout: 20,
            chatty_service_min_calls: 15,
            pool_saturation_concurrent_threshold: 10,
            serialized_min_sequential: 3,
            // Green
            green_enabled: true,
            green_default_region: None,
            green_service_regions: HashMap::new(),
            green_embodied_carbon_per_request_gco2: DEFAULT_EMBODIED_CARBON_PER_REQUEST_GCO2,
            green_use_hourly_profiles: true,
            green_scaphandre: None,
            green_cloud_energy: None,
            green_per_operation_coefficients: true,
            green_include_network_transport: false,
            green_network_energy_per_byte_kwh:
                crate::score::carbon::DEFAULT_NETWORK_ENERGY_PER_BYTE_KWH,
            green_hourly_profiles_file: None,
            green_custom_hourly_profiles: None,
            green_calibration_file: None,
            green_calibration: None,
            green_electricity_maps: None,
            // Daemon
            listen_addr: "127.0.0.1".to_string(),
            listen_port: 4318,
            listen_port_grpc: 4317,
            json_socket: "/tmp/perf-sentinel.sock".to_string(),
            max_active_traces: 10_000,
            trace_ttl_ms: 30_000,
            sampling_rate: 1.0,
            max_events_per_trace: 1_000,
            max_payload_size: 1_048_576, // 1 MB
            daemon_environment: DaemonEnvironment::Staging,
            tls_cert_path: None,
            tls_key_path: None,
            max_retained_findings: 10_000,
            daemon_api_enabled: true,
            correlation_enabled: false,
            correlation_config: crate::detect::correlate_cross::CorrelationConfig::default(),
        }
    }
}

impl Config {
    /// Map the daemon environment to a [`Confidence`] value.
    ///
    /// Used by `daemon::run` to stamp findings after detection. `analyze`
    /// batch mode does not call this; it hardcodes [`Confidence::CiBatch`]
    /// in `pipeline::analyze_with_traces` instead.
    #[must_use]
    pub const fn confidence(&self) -> Confidence {
        match self.daemon_environment {
            DaemonEnvironment::Staging => Confidence::DaemonStaging,
            DaemonEnvironment::Production => Confidence::DaemonProduction,
        }
    }

    /// Build a [`CarbonContext`] from the green config fields.
    ///
    /// Returns a context with `energy_snapshot: None`. The daemon clones
    /// this and patches in the measured energy snapshot per tick; the
    /// batch pipeline uses it as-is (no scrapers in batch mode).
    #[must_use]
    pub fn carbon_context(&self) -> crate::score::carbon::CarbonContext {
        crate::score::carbon::CarbonContext {
            default_region: self.green_default_region.clone(),
            service_regions: self.green_service_regions.clone(),
            embodied_per_request_gco2: self.green_embodied_carbon_per_request_gco2,
            use_hourly_profiles: self.green_use_hourly_profiles,
            energy_snapshot: None,
            per_operation_coefficients: self.green_per_operation_coefficients,
            include_network_transport: self.green_include_network_transport,
            network_energy_per_byte_kwh: self.green_network_energy_per_byte_kwh,
            custom_hourly_profiles: self.green_custom_hourly_profiles.clone(),
            calibration: self.green_calibration.clone(),
            real_time_intensity: None, // set per-tick in daemon via build_tick_ctx
        }
    }
}

// --- Internal raw deserialization types ---

#[derive(Deserialize, Default)]
#[serde(default)]
struct RawConfig {
    // Sections (new format)
    thresholds: ThresholdsSection,
    detection: DetectionSection,
    green: GreenSection,
    daemon: DaemonSection,

    // Legacy flat fields (backward compatibility)
    max_payload_size: Option<usize>,
    n_plus_one_threshold: Option<u32>,
    listen_addr: Option<String>,
    listen_port: Option<u16>,
    window_duration_ms: Option<u64>,
    trace_ttl_ms: Option<u64>,
    max_active_traces: Option<usize>,
    max_events_per_trace: Option<usize>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
#[allow(clippy::struct_field_names)] // fields like `n_plus_one_sql_critical_max` repeat the struct context but match the TOML keys
struct ThresholdsSection {
    n_plus_one_sql_critical_max: Option<u32>,
    n_plus_one_http_warning_max: Option<u32>,
    io_waste_ratio_max: Option<f64>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct DetectionSection {
    window_duration_ms: Option<u64>,
    n_plus_one_min_occurrences: Option<u32>,
    slow_query_threshold_ms: Option<u64>,
    slow_query_min_occurrences: Option<u32>,
    max_fanout: Option<u32>,
    chatty_service_min_calls: Option<u32>,
    pool_saturation_concurrent_threshold: Option<u32>,
    serialized_min_sequential: Option<u32>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct GreenSection {
    enabled: Option<bool>,
    default_region: Option<String>,
    service_regions: HashMap<String, String>,
    embodied_carbon_per_request_gco2: Option<f64>,
    /// toggle for the hourly carbon intensity profile path.
    /// Default `true`. Maps to `Config::green_use_hourly_profiles`.
    use_hourly_profiles: Option<bool>,
    /// Scaphandre scraper section. Absent when Scaphandre
    /// is not configured.
    scaphandre: ScaphandreSection,
    /// Cloud energy section. Absent when cloud energy is not configured.
    cloud: CloudSection,
    per_operation_coefficients: Option<bool>,
    include_network_transport: Option<bool>,
    network_energy_per_byte_kwh: Option<f64>,
    /// Path to a JSON file with user-supplied hourly carbon profiles.
    hourly_profiles_file: Option<String>,
    /// Path to a calibration TOML file from `perf-sentinel calibrate`.
    calibration_file: Option<String>,
    /// Electricity Maps API section.
    electricity_maps: ElectricityMapsSection,
}

/// Raw deserialization target for `[green.scaphandre]`.
///
/// Converted to a `ScaphandreConfig` during `RawConfig → Config` only
/// when `endpoint` is set: an empty table (no fields) leaves
/// `Config::green_scaphandre = None`.
#[derive(Deserialize, Default)]
#[serde(default)]
struct ScaphandreSection {
    endpoint: Option<String>,
    scrape_interval_secs: Option<u64>,
    process_map: HashMap<String, String>,
}

/// Raw deserialization target for `[green.cloud]`.
///
/// Converted to a `CloudEnergyConfig` during `RawConfig -> Config` only
/// when `prometheus_endpoint` is set.
#[derive(Deserialize, Default)]
#[serde(default)]
struct CloudSection {
    prometheus_endpoint: Option<String>,
    scrape_interval_secs: Option<u64>,
    default_provider: Option<String>,
    default_instance_type: Option<String>,
    cpu_metric: Option<String>,
    services: HashMap<String, CloudServiceRaw>,
}

/// Raw deserialization for a single entry in `[green.cloud.services]`.
///
/// Supports two forms:
/// - Instance type: `{ provider = "aws", instance_type = "m5.large" }`
/// - Manual watts: `{ idle_watts = 45, max_watts = 120 }`
#[derive(Deserialize, Default)]
#[serde(default)]
struct CloudServiceRaw {
    provider: Option<String>,
    instance_type: Option<String>,
    idle_watts: Option<f64>,
    max_watts: Option<f64>,
    cpu_query: Option<String>,
}

/// Raw deserialization target for `[green.electricity_maps]`.
///
/// Converted to an `ElectricityMapsConfig` during `RawConfig -> Config`
/// only when `api_key` is set (directly or via env var).
#[derive(Deserialize, Default)]
#[serde(default)]
struct ElectricityMapsSection {
    api_key: Option<String>,
    endpoint: Option<String>,
    poll_interval_secs: Option<u64>,
    region_map: HashMap<String, String>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct DaemonSection {
    listen_address: Option<String>,
    listen_port_http: Option<u16>,
    listen_port_grpc: Option<u16>,
    json_socket: Option<String>,
    max_active_traces: Option<usize>,
    trace_ttl_ms: Option<u64>,
    sampling_rate: Option<f64>,
    max_events_per_trace: Option<usize>,
    max_payload_size: Option<usize>,
    /// `"staging"` (default) or `"production"`. Validated
    /// in `Config::validate`; invalid values fail at load time with a
    /// clear error. Case-insensitive.
    environment: Option<String>,
    /// Path to PEM-encoded TLS certificate chain.
    tls_cert_path: Option<String>,
    /// Path to PEM-encoded TLS private key.
    tls_key_path: Option<String>,
    /// Maximum number of findings kept by the daemon query API.
    max_retained_findings: Option<usize>,
    /// Whether the daemon query API is enabled.
    api_enabled: Option<bool>,
    /// Cross-trace correlation section.
    correlation: CorrelationSection,
}

/// Raw deserialization target for `[daemon.correlation]`.
#[derive(Deserialize, Default)]
#[serde(default)]
struct CorrelationSection {
    enabled: Option<bool>,
    window_minutes: Option<u64>,
    lag_threshold_ms: Option<u64>,
    min_co_occurrences: Option<u32>,
    min_confidence: Option<f64>,
    max_tracked_pairs: Option<usize>,
}

const TOML_PATH_STRING_KEYS: &[&str] = &[
    "hourly_profiles_file",
    "calibration_file",
    "json_socket",
    "tls_cert_path",
    "tls_key_path",
];

/// Rewrite path-like config fields so Windows-style backslashes are treated
/// as literal separators instead of TOML escapes.
///
/// See `docs/design/07-CLI-CONFIG-RELEASE.md` > "Windows path normalization"
/// for the full algorithm, the UNC rule, and the fallback design.
fn normalize_toml_path_strings(content: &str) -> Cow<'_, str> {
    let mut changed = false;
    let mut normalized = String::with_capacity(content.len());

    for line in content.split_inclusive('\n') {
        let rewritten = normalize_toml_path_line(line);
        changed |= matches!(rewritten, Cow::Owned(_));
        normalized.push_str(rewritten.as_ref());
    }

    if changed {
        Cow::Owned(normalized)
    } else {
        Cow::Borrowed(content)
    }
}

fn normalize_toml_path_line(line: &str) -> Cow<'_, str> {
    let leading_ws = line.len() - line.trim_start_matches([' ', '\t']).len();
    let trimmed = &line[leading_ws..];
    let Some(eq_idx) = trimmed.find('=') else {
        return Cow::Borrowed(line);
    };

    let key = trimmed[..eq_idx].trim();
    if !TOML_PATH_STRING_KEYS.contains(&key) {
        return Cow::Borrowed(line);
    }

    let after_eq = &trimmed[eq_idx + 1..];
    let value_ws = after_eq.len() - after_eq.trim_start_matches([' ', '\t']).len();
    let value_start = leading_ws + eq_idx + 1 + value_ws;
    let value = &line[value_start..];
    if !value.starts_with('"') {
        return Cow::Borrowed(line);
    }

    let Some(closing_quote) = find_basic_string_end(value) else {
        return Cow::Borrowed(line);
    };
    let inner = &value[1..closing_quote];
    let Cow::Owned(normalized_inner) = escape_toml_path_backslashes(inner) else {
        return Cow::Borrowed(line);
    };

    // Push the opening `"` explicitly so `value_start` is never used as
    // the end of an inclusive byte range. See design doc 07 > "Windows
    // path normalization" for the UTF-8 invariant.
    let mut out =
        String::with_capacity(line.len() + normalized_inner.len().saturating_sub(inner.len()));
    out.push_str(&line[..value_start]);
    out.push('"');
    out.push_str(&normalized_inner);
    out.push_str(&value[closing_quote..]);
    Cow::Owned(out)
}

/// Return the byte offset of the closing `"` that terminates a TOML basic
/// string starting at `value[0]` or `None` if the string is unterminated.
///
/// Linear: the `run` counter avoids an O(n²) lookbehind on inputs full of
/// `\`. See design doc 07 > "Windows path normalization" for context.
fn find_basic_string_end(value: &str) -> Option<usize> {
    debug_assert!(value.starts_with('"'));

    let bytes = value.as_bytes();
    let mut run: usize = 0;
    let mut idx = 1;
    while idx < bytes.len() {
        match bytes[idx] {
            b'"' if run.is_multiple_of(2) => return Some(idx),
            b'\\' => run += 1,
            _ => run = 0,
        }
        idx += 1;
    }
    None
}

/// Escape single backslashes inside a TOML basic-string path so its value
/// round-trips as a literal separator.
///
/// See design doc 07 > "Windows path normalization" for the per-run rules
/// (single `\`, escape pairs, raw UNC prefix). Returns `Cow::Borrowed(inner)`
/// when no rewrite is needed.
fn escape_toml_path_backslashes(inner: &str) -> Cow<'_, str> {
    if !inner.contains('\\') {
        return Cow::Borrowed(inner);
    }

    let bytes = inner.as_bytes();
    let mut out = String::with_capacity(inner.len() + 4);
    let mut changed = false;
    let mut idx = 0;

    while idx < bytes.len() {
        if bytes[idx] != b'\\' {
            idx = copy_until_backslash(inner, bytes, idx, &mut out);
            continue;
        }

        let run_start = idx;
        idx = skip_backslash_run(bytes, idx);
        let run_len = idx - run_start;
        let emit_len = backslash_emit_len(run_start, run_len, bytes.get(idx).copied());
        changed |= emit_len != run_len;
        for _ in 0..emit_len {
            out.push('\\');
        }
    }

    if changed {
        Cow::Owned(out)
    } else {
        Cow::Borrowed(inner)
    }
}

/// Copy bytes from `start` up to (but not including) the next `\` into
/// `out`, and return the index where the run of `\` begins (or
/// `bytes.len()` if no more `\` is found).
fn copy_until_backslash(inner: &str, bytes: &[u8], start: usize, out: &mut String) -> usize {
    let mut idx = start;
    while idx < bytes.len() && bytes[idx] != b'\\' {
        idx += 1;
    }
    out.push_str(&inner[start..idx]);
    idx
}

/// Skip a run of consecutive `\` starting at `start` and return the index
/// of the first non-`\` byte (or `bytes.len()`).
fn skip_backslash_run(bytes: &[u8], start: usize) -> usize {
    let mut idx = start;
    while idx < bytes.len() && bytes[idx] == b'\\' {
        idx += 1;
    }
    idx
}

/// Decide how many `\` to emit for a run of `run_len` backslashes
/// starting at byte offset `run_start`. `next_byte` is the byte
/// immediately after the run (used to disambiguate UNC prefixes).
fn backslash_emit_len(run_start: usize, run_len: usize, next_byte: Option<u8>) -> usize {
    let raw_unc_prefix = run_start == 0 && run_len == 2 && next_byte != Some(b'\\');
    if raw_unc_prefix {
        4
    } else if run_len == 1 {
        2
    } else {
        run_len
    }
}

impl From<RawConfig> for Config {
    #[allow(clippy::too_many_lines)] // Flat config-to-typed mapping: splitting would scatter field assignments
    fn from(raw: RawConfig) -> Self {
        let defaults = Self::default();

        // Sections take priority over flat fields, flat fields over defaults.
        Self {
            // Thresholds
            n_plus_one_sql_critical_max: raw
                .thresholds
                .n_plus_one_sql_critical_max
                .unwrap_or(defaults.n_plus_one_sql_critical_max),
            n_plus_one_http_warning_max: raw
                .thresholds
                .n_plus_one_http_warning_max
                .unwrap_or(defaults.n_plus_one_http_warning_max),
            io_waste_ratio_max: raw
                .thresholds
                .io_waste_ratio_max
                .unwrap_or(defaults.io_waste_ratio_max),

            // Detection: section > flat > default
            n_plus_one_threshold: raw
                .detection
                .n_plus_one_min_occurrences
                .or(raw.n_plus_one_threshold)
                .unwrap_or(defaults.n_plus_one_threshold),
            window_duration_ms: raw
                .detection
                .window_duration_ms
                .or(raw.window_duration_ms)
                .unwrap_or(defaults.window_duration_ms),
            slow_query_threshold_ms: raw
                .detection
                .slow_query_threshold_ms
                .unwrap_or(defaults.slow_query_threshold_ms),
            slow_query_min_occurrences: raw
                .detection
                .slow_query_min_occurrences
                .unwrap_or(defaults.slow_query_min_occurrences),
            max_fanout: raw.detection.max_fanout.unwrap_or(defaults.max_fanout),
            chatty_service_min_calls: raw
                .detection
                .chatty_service_min_calls
                .unwrap_or(defaults.chatty_service_min_calls),
            pool_saturation_concurrent_threshold: raw
                .detection
                .pool_saturation_concurrent_threshold
                .unwrap_or(defaults.pool_saturation_concurrent_threshold),
            serialized_min_sequential: raw
                .detection
                .serialized_min_sequential
                .unwrap_or(defaults.serialized_min_sequential),

            // Green
            green_enabled: raw.green.enabled.unwrap_or(defaults.green_enabled),
            green_default_region: raw.green.default_region,
            // Lowercase service_regions keys so resolve_region's
            // lowercase lookup matches regardless of config casing.
            green_service_regions: raw
                .green
                .service_regions
                .into_iter()
                .map(|(k, v)| (k.to_ascii_lowercase(), v))
                .collect(),
            green_embodied_carbon_per_request_gco2: raw
                .green
                .embodied_carbon_per_request_gco2
                .unwrap_or(defaults.green_embodied_carbon_per_request_gco2),
            green_use_hourly_profiles: raw
                .green
                .use_hourly_profiles
                .unwrap_or(defaults.green_use_hourly_profiles),
            green_scaphandre: raw.green.scaphandre.endpoint.as_ref().map(|endpoint| {
                ScaphandreConfig {
                    endpoint: endpoint.clone(),
                    // Default scrape interval 5s; clamped in validate_green
                    // to the [1, 3600] range.
                    scrape_interval: Duration::from_secs(
                        raw.green.scaphandre.scrape_interval_secs.unwrap_or(5),
                    ),
                    process_map: raw.green.scaphandre.process_map.clone(),
                }
            }),
            green_cloud_energy: convert_cloud_section(&raw.green.cloud),
            green_per_operation_coefficients: raw
                .green
                .per_operation_coefficients
                .unwrap_or(defaults.green_per_operation_coefficients),
            green_include_network_transport: raw
                .green
                .include_network_transport
                .unwrap_or(defaults.green_include_network_transport),
            green_network_energy_per_byte_kwh: raw
                .green
                .network_energy_per_byte_kwh
                .unwrap_or(defaults.green_network_energy_per_byte_kwh),
            green_hourly_profiles_file: raw.green.hourly_profiles_file.clone(),
            green_custom_hourly_profiles: raw.green.hourly_profiles_file.as_ref().and_then(
                |path| {
                    if has_control_char(path) {
                        tracing::warn!(
                            "hourly_profiles_file path contains control characters, skipping"
                        );
                        return None;
                    }
                    let p = std::path::Path::new(path);
                    match crate::score::carbon::load_custom_profiles(p) {
                        Ok(profiles) => Some(std::sync::Arc::new(profiles)),
                        Err(e) => {
                            // Not logged at warn: validate_green() will
                            // surface a hard error for this case.
                            tracing::debug!(
                                error = %e,
                                "Custom hourly profiles failed to load"
                            );
                            None
                        }
                    }
                },
            ),

            green_calibration_file: raw.green.calibration_file.clone(),
            green_calibration: raw.green.calibration_file.as_ref().and_then(|path| {
                if has_control_char(path) {
                    tracing::warn!("calibration_file path contains control characters, skipping");
                    return None;
                }
                match crate::calibrate::load_calibration_file(path) {
                    Ok(data) => Some(data),
                    Err(e) => {
                        tracing::debug!(
                            error = %e,
                            "Calibration file failed to load"
                        );
                        None
                    }
                }
            }),
            green_electricity_maps: convert_electricity_maps_section(&raw.green.electricity_maps),

            // Daemon: section > flat > default
            listen_addr: raw
                .daemon
                .listen_address
                .or(raw.listen_addr)
                .unwrap_or(defaults.listen_addr),
            listen_port: raw
                .daemon
                .listen_port_http
                .or(raw.listen_port)
                .unwrap_or(defaults.listen_port),
            listen_port_grpc: raw
                .daemon
                .listen_port_grpc
                .unwrap_or(defaults.listen_port_grpc),
            json_socket: raw.daemon.json_socket.unwrap_or(defaults.json_socket),
            max_active_traces: raw
                .daemon
                .max_active_traces
                .or(raw.max_active_traces)
                .unwrap_or(defaults.max_active_traces),
            trace_ttl_ms: raw
                .daemon
                .trace_ttl_ms
                .or(raw.trace_ttl_ms)
                .unwrap_or(defaults.trace_ttl_ms),
            sampling_rate: raw.daemon.sampling_rate.unwrap_or(defaults.sampling_rate),
            max_events_per_trace: raw
                .daemon
                .max_events_per_trace
                .or(raw.max_events_per_trace)
                .unwrap_or(defaults.max_events_per_trace),
            max_payload_size: raw
                .daemon
                .max_payload_size
                .or(raw.max_payload_size)
                .unwrap_or(defaults.max_payload_size),
            // parse environment into the typed enum. Invalid
            // strings are rejected later in Config::validate so parse
            // Fallback to Staging is safe: load_from_str() pre-validates
            // this field before calling Config::from(). Direct callers
            // (only tests) get Staging as a safe default.
            daemon_environment: match raw.daemon.environment.as_deref() {
                None => defaults.daemon_environment,
                Some(s) => parse_daemon_environment(s).unwrap_or(DaemonEnvironment::Staging),
            },
            tls_cert_path: raw.daemon.tls_cert_path,
            tls_key_path: raw.daemon.tls_key_path,
            max_retained_findings: raw
                .daemon
                .max_retained_findings
                .unwrap_or(defaults.max_retained_findings),
            daemon_api_enabled: raw
                .daemon
                .api_enabled
                .unwrap_or(defaults.daemon_api_enabled),
            correlation_enabled: raw
                .daemon
                .correlation
                .enabled
                .unwrap_or(defaults.correlation_enabled),
            correlation_config: {
                let c = &raw.daemon.correlation;
                let d = crate::detect::correlate_cross::CorrelationConfig::default();
                crate::detect::correlate_cross::CorrelationConfig {
                    window_ms: c
                        .window_minutes
                        .map_or(d.window_ms, |m| m.saturating_mul(60_000)),
                    lag_threshold_ms: c.lag_threshold_ms.unwrap_or(d.lag_threshold_ms),
                    min_co_occurrences: c.min_co_occurrences.unwrap_or(d.min_co_occurrences),
                    min_confidence: c.min_confidence.unwrap_or(d.min_confidence),
                    max_tracked_pairs: c.max_tracked_pairs.unwrap_or(d.max_tracked_pairs),
                }
            },
        }
    }
}

/// Parse a case-insensitive environment string into [`DaemonEnvironment`].
///
/// Returns `None` for any value that is not `"staging"` or `"production"`.
/// Called from [`Config::from`] (which falls back to default on error,
/// deferring the real rejection to [`Config::validate`]).
fn parse_daemon_environment(value: &str) -> Option<DaemonEnvironment> {
    match value.trim().to_ascii_lowercase().as_str() {
        "staging" => Some(DaemonEnvironment::Staging),
        "production" => Some(DaemonEnvironment::Production),
        _ => None,
    }
}

/// Convert the raw `[green.cloud]` TOML section into a typed config.
///
/// Returns `None` when `prometheus_endpoint` is absent (section empty
/// or not present). Per-service entries are classified as either
/// `InstanceType` or `ManualWatts` based on which fields are set.
fn convert_cloud_section(raw: &CloudSection) -> Option<CloudEnergyConfig> {
    let endpoint = raw.prometheus_endpoint.as_ref()?;
    let mut services = HashMap::with_capacity(raw.services.len());
    for (name, svc) in &raw.services {
        let config = if svc.idle_watts.is_some() || svc.max_watts.is_some() {
            // Manual watts mode: both must be present (validated later).
            ServiceCloudConfig::ManualWatts {
                idle_watts: svc.idle_watts.unwrap_or(0.0),
                max_watts: svc.max_watts.unwrap_or(0.0),
                cpu_query: svc.cpu_query.clone(),
            }
        } else {
            ServiceCloudConfig::InstanceType {
                provider: svc.provider.clone(),
                instance_type: svc.instance_type.clone().unwrap_or_default(),
                cpu_query: svc.cpu_query.clone(),
            }
        };
        services.insert(name.clone(), config);
    }
    Some(CloudEnergyConfig {
        prometheus_endpoint: endpoint.clone(),
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(15)),
        default_provider: raw.default_provider.clone(),
        default_instance_type: raw.default_instance_type.clone(),
        cpu_metric: raw.cpu_metric.clone(),
        services,
    })
}

/// Convert the raw `[green.electricity_maps]` TOML section into a typed config.
///
/// Returns `None` when no `api_key` is set (neither in config nor env var).
fn convert_electricity_maps_section(
    raw: &ElectricityMapsSection,
) -> Option<crate::score::electricity_maps::ElectricityMapsConfig> {
    convert_electricity_maps_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_EMAPS_TOKEN").ok()
    })
}

/// Test-friendly inner form: takes the env-var lookup as a closure so tests
/// can pass `|| None` instead of mutating the global process env. Avoids the
/// `unsafe` that Rust 2024 requires on `std::env::remove_var` (`set_var` and
/// `remove_var` are data races with other threads inside the same process,
/// including the `cargo test` harness).
fn convert_electricity_maps_section_with_env(
    raw: &ElectricityMapsSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<crate::score::electricity_maps::ElectricityMapsConfig> {
    // Auth token: env var takes precedence over config file.
    let from_env = env_lookup();
    let token = from_env.clone().or_else(|| raw.api_key.clone())?;

    if token.is_empty() {
        return None;
    }

    // Nudge users toward the env var when the token is in the config file.
    if from_env.is_none() && raw.api_key.is_some() {
        tracing::warn!(
            "[green.electricity_maps] api_key is set in the config file. \
             Prefer the PERF_SENTINEL_EMAPS_TOKEN environment variable \
             to avoid committing secrets to version control."
        );
    }

    let poll_secs = raw.poll_interval_secs.unwrap_or(300);
    let api_endpoint = raw
        .endpoint
        .clone()
        .unwrap_or_else(|| "https://api.electricitymaps.com/v3".to_string());
    Some(crate::score::electricity_maps::ElectricityMapsConfig {
        api_endpoint,
        auth_token: token,
        poll_interval: Duration::from_secs(poll_secs),
        // Lowercase region keys so scoring loop lookups match regardless
        // of config casing (same pattern as service_regions).
        region_map: raw
            .region_map
            .iter()
            .map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))
            .collect(),
    })
}

fn check_range<T: PartialOrd + std::fmt::Display>(
    name: &str,
    val: &T,
    min: &T,
    max: &T,
) -> Result<(), String> {
    if val < min {
        return Err(format!("{name} must be >= {min}, got {val}"));
    }
    if val > max {
        return Err(format!("{name} must be <= {max}, got {val}"));
    }
    Ok(())
}

fn check_min<T: PartialOrd + std::fmt::Display>(
    name: &str,
    val: &T,
    min: &T,
) -> Result<(), String> {
    if val < min {
        return Err(format!("{name} must be >= {min}, got {val}"));
    }
    Ok(())
}

/// Emit a single startup warning when `val` is inside the hard bounds but
/// outside the recommended "comfort zone" `[comfort_lo, comfort_hi]`.
///
/// See design doc 07 > "Comfort-zone warnings" for the rationale and the
/// list of bands per field.
fn warn_outside_comfort_zone<T>(
    name: &str,
    val: &T,
    comfort_lo: &T,
    comfort_hi: &T,
    note_low: &str,
    note_high: &str,
) where
    T: PartialOrd + std::fmt::Display,
{
    if val < comfort_lo {
        tracing::warn!(
            field = %name,
            value = %val,
            recommended_min = %comfort_lo,
            "{name} = {val} is below the recommended floor {comfort_lo}; {note_low}"
        );
    } else if val > comfort_hi {
        tracing::warn!(
            field = %name,
            value = %val,
            recommended_max = %comfort_hi,
            "{name} = {val} is above the recommended ceiling {comfort_hi}; {note_high}"
        );
    }
}

/// `true` if `s` contains any ASCII control character (< 0x20 or DEL).
fn has_control_char(s: &str) -> bool {
    s.bytes().any(|b| b < 0x20 || b == 0x7F)
}

/// Validate the authority portion of an HTTP(S) URI.
/// Rejects credentials, empty host, control characters, and invalid port.
/// Handles IPv6 bracket notation (`[::1]`, `[::1]:8080`).
fn validate_http_authority(url: &str, label: &str) -> Result<(), String> {
    let after_scheme = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))
        .unwrap_or(url);
    let authority = after_scheme.split('/').next().unwrap_or(after_scheme);
    if authority.is_empty() {
        return Err(format!("{label} '{url}' has no host"));
    }
    if authority.contains('@') {
        return Err(format!(
            "{label} must not contain credentials (userinfo): '{url}'"
        ));
    }
    if has_control_char(authority) {
        return Err(format!("{label} '{url}' contains control characters"));
    }
    // Port validation: skip for bare IPv6 without port (`[::1]`), handle
    // bracketed IPv6 with port (`[::1]:8080`) via the `]:` delimiter.
    if authority.starts_with('[') {
        // IPv6 bracket notation: port follows `]:` if present.
        if let Some(bracket_end) = authority.find(']') {
            let after_bracket = &authority[bracket_end + 1..];
            if let Some(port_str) = after_bracket.strip_prefix(':')
                && !port_str.is_empty()
                && port_str.parse::<u16>().is_err()
            {
                return Err(format!("{label} '{url}' has an invalid port"));
            }
        }
    } else if let Some(port_str) = authority.rsplit(':').next()
        && authority.contains(':')
        && port_str.parse::<u16>().is_err()
    {
        return Err(format!("{label} '{url}' has an invalid port"));
    }
    Ok(())
}

impl Config {
    /// Validate that config values are within acceptable bounds.
    ///
    /// # Errors
    ///
    /// Returns a `String` description of the first invalid value found.
    /// The caller (`load_from_str`) wraps this in `ConfigError::Validation`.
    pub fn validate(&self) -> Result<(), String> {
        self.validate_daemon_limits()?;
        self.validate_detection_params()?;
        self.validate_rates()?;
        self.validate_listen_addr()?;
        self.validate_tls()?;
        self.validate_green()?;
        Ok(())
    }

    /// Validate TLS configuration: both paths must be set or both absent.
    /// When set, verify the files exist and warn if the key is
    /// world-readable on Unix.
    fn validate_tls(&self) -> Result<(), String> {
        match (&self.tls_cert_path, &self.tls_key_path) {
            (Some(cert), Some(key)) => {
                if has_control_char(cert) {
                    return Err("[daemon] tls_cert_path contains control characters".to_string());
                }
                if has_control_char(key) {
                    return Err("[daemon] tls_key_path contains control characters".to_string());
                }
                if !std::path::Path::new(cert).exists() {
                    return Err(format!("[daemon] tls_cert_path '{cert}' does not exist"));
                }
                if !std::path::Path::new(key).exists() {
                    return Err(format!("[daemon] tls_key_path '{key}' does not exist"));
                }
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    if let Ok(meta) = std::fs::metadata(key) {
                        let mode = meta.permissions().mode();
                        if mode & 0o077 != 0 {
                            tracing::warn!(
                                "TLS key file '{key}' is readable by group/others \
                                 (mode {mode:o}). Consider restricting to owner-only \
                                 (chmod 600)."
                            );
                        }
                    }
                }
                tracing::info!("TLS enabled for daemon OTLP receivers (cert: {cert})");
                Ok(())
            }
            (None, None) => Ok(()),
            (Some(_), None) => {
                Err("[daemon] tls_cert_path is set but tls_key_path is missing".to_string())
            }
            (None, Some(_)) => {
                Err("[daemon] tls_key_path is set but tls_cert_path is missing".to_string())
            }
        }
    }

    fn validate_green(&self) -> Result<(), String> {
        Self::validate_embodied_carbon(self.green_embodied_carbon_per_request_gco2)?;
        Self::validate_default_region(self.green_default_region.as_deref())?;
        Self::validate_service_regions(&self.green_service_regions)?;
        if let Some(cfg) = &self.green_scaphandre {
            Self::validate_scaphandre(cfg)?;
        }
        if let Some(cfg) = &self.green_cloud_energy {
            Self::validate_cloud_energy(cfg)?;
        }
        Self::validate_network_energy(self.green_network_energy_per_byte_kwh)?;
        self.validate_hourly_profiles_file()?;
        if let Some(cfg) = &self.green_electricity_maps {
            Self::validate_electricity_maps(cfg)?;
        }
        Ok(())
    }

    fn validate_embodied_carbon(value: f64) -> Result<(), String> {
        if !value.is_finite() {
            return Err(format!(
                "embodied_carbon_per_request_gco2 must be finite, got {value}"
            ));
        }
        if value < 0.0 {
            return Err(format!(
                "embodied_carbon_per_request_gco2 must be >= 0.0, got {value}"
            ));
        }
        Ok(())
    }

    /// Validate the optional `[green] default_region`. Config is trusted
    /// input, so typos surface loudly here rather than silently producing
    /// zeroed COâ‚‚ rows downstream. Same validator used at the OTLP
    /// ingestion boundary (there, invalid values are silently dropped).
    fn validate_default_region(region: Option<&str>) -> Result<(), String> {
        let Some(region) = region else {
            return Ok(());
        };
        if crate::score::carbon::is_valid_region_id(region) {
            return Ok(());
        }
        Err(format!(
            "[green] default_region '{region}' contains invalid characters; \
             expected ASCII alphanumeric + '-' or '_', length 1-64"
        ))
    }

    /// Validate the `[green.service_regions]` map: cardinality cap, plus
    /// region-id syntax on every key/value pair.
    fn validate_service_regions(map: &HashMap<String, String>) -> Result<(), String> {
        /// Maximum number of entries in `[green.service_regions]`.
        /// Bounds the config-load memory footprint against fat-finger or
        /// malicious configs. 1024 is 4× `MAX_REGIONS` (256) and comfortably
        /// above any realistic multi-cloud deployment size.
        const MAX_SERVICE_REGIONS: usize = 1024;
        if map.len() > MAX_SERVICE_REGIONS {
            return Err(format!(
                "[green.service_regions] has {} entries; maximum is {MAX_SERVICE_REGIONS}",
                map.len()
            ));
        }
        for (service, region) in map {
            if !crate::score::carbon::is_valid_region_id(service) {
                return Err(format!(
                    "[green.service_regions] invalid service name '{service}'; \
                     expected ASCII alphanumeric + '-' or '_', length 1-64"
                ));
            }
            if !crate::score::carbon::is_valid_region_id(region) {
                return Err(format!(
                    "[green.service_regions] invalid region '{region}' for service '{service}'; \
                     expected ASCII alphanumeric + '-' or '_', length 1-64"
                ));
            }
        }
        Ok(())
    }

    fn validate_network_energy(value: f64) -> Result<(), String> {
        if !value.is_finite() || value < 0.0 {
            return Err(format!(
                "network_energy_per_byte_kwh must be finite and >= 0.0, got {value}"
            ));
        }
        Ok(())
    }

    /// Validate `[green] hourly_profiles_file`: reject control characters
    /// in the path (log injection) and require that the file actually
    /// loaded when the field is configured.
    fn validate_hourly_profiles_file(&self) -> Result<(), String> {
        let Some(path) = &self.green_hourly_profiles_file else {
            return Ok(());
        };
        if has_control_char(path) {
            return Err("[green] hourly_profiles_file contains control characters".to_string());
        }
        if self.green_custom_hourly_profiles.is_none() {
            return Err(format!(
                "[green] hourly_profiles_file '{path}' was configured but \
                 failed to load. Remove the field to use embedded profiles only."
            ));
        }
        Ok(())
    }

    /// Validate a parsed `[green.electricity_maps]` config section.
    fn validate_electricity_maps(
        cfg: &crate::score::electricity_maps::ElectricityMapsConfig,
    ) -> Result<(), String> {
        if cfg.auth_token.is_empty() {
            return Err(
                "[green.electricity_maps] api_key or PERF_SENTINEL_EMAPS_TOKEN is required"
                    .to_string(),
            );
        }
        if has_control_char(&cfg.auth_token) {
            return Err(
                "[green.electricity_maps] auth token contains control characters".to_string(),
            );
        }
        validate_http_authority(&cfg.api_endpoint, "[green.electricity_maps] endpoint")?;
        // Warn (but do not fail) when a non-empty auth token travels to an
        // http:// endpoint. The Electricity Maps production API is served
        // over https in practice; an http:// endpoint usually means a local
        // test server or a misconfiguration. Flag it so users do not
        // silently ship credentials in cleartext.
        if cfg.api_endpoint.starts_with("http://") && !cfg.auth_token.is_empty() {
            tracing::warn!(
                "[green.electricity_maps] auth token will be sent over http:// \
                 (no TLS). Use https:// for production or set the endpoint to \
                 a loopback/private address if this is intentional."
            );
        }
        let secs = cfg.poll_interval.as_secs();
        check_range(
            "[green.electricity_maps] poll_interval_secs",
            &secs,
            &60,
            &86400,
        )?;
        if cfg.region_map.is_empty() {
            return Err(
                "[green.electricity_maps] region_map must contain at least one entry".to_string(),
            );
        }
        for (region, zone) in &cfg.region_map {
            if zone.is_empty() {
                return Err(format!(
                    "[green.electricity_maps.region_map] zone for '{region}' is empty"
                ));
            }
            if has_control_char(zone)
                || zone.contains('&')
                || zone.contains('#')
                || zone.contains('=')
                || zone.contains('?')
                || zone.contains('%')
                || zone.contains(' ')
                || zone.contains('+')
            {
                return Err(format!(
                    "[green.electricity_maps.region_map] zone '{zone}' for '{region}' \
                     contains invalid characters"
                ));
            }
            if has_control_char(region) {
                return Err(format!(
                    "[green.electricity_maps.region_map] region key '{region}' \
                     contains control characters"
                ));
            }
        }
        Ok(())
    }

    /// Validate a parsed `[green.scaphandre]` config section.
    ///
    /// Rejects: empty endpoint, non-`http://` scheme, credentials in
    /// authority, control characters, invalid port, `scrape_interval_secs`
    /// outside [1, 3600], and `process_map` keys/values that are empty,
    /// >256 chars, or contain control characters.
    fn validate_scaphandre(cfg: &ScaphandreConfig) -> Result<(), String> {
        if cfg.endpoint.is_empty() {
            return Err(
                "[green.scaphandre] endpoint is required when the section is present".to_string(),
            );
        }
        if !cfg.endpoint.starts_with("http://") && !cfg.endpoint.starts_with("https://") {
            return Err(format!(
                "[green.scaphandre] endpoint '{}' must start with 'http://' or 'https://'",
                cfg.endpoint
            ));
        }
        validate_http_authority(&cfg.endpoint, "[green.scaphandre] endpoint")?;
        let secs = cfg.scrape_interval.as_secs();
        if !(1..=3600).contains(&secs) {
            return Err(format!(
                "[green.scaphandre] scrape_interval_secs must be in [1, 3600], got {secs}"
            ));
        }
        // process_map keys are perf-sentinel service names and values are
        // Scaphandre `exe` labels. Validate both are non-empty and of
        // reasonable length; don't run them through is_valid_region_id
        // because service names may contain dots, slashes, etc.
        for (service, exe) in &cfg.process_map {
            if service.is_empty() || service.len() > 256 {
                return Err(format!(
                    "[green.scaphandre] process_map service name '{service}' must be 1-256 chars"
                ));
            }
            if has_control_char(service) {
                return Err(format!(
                    "[green.scaphandre] process_map service name '{service}' \
                     contains control characters"
                ));
            }
            if exe.is_empty() || exe.len() > 256 {
                return Err(format!(
                    "[green.scaphandre] process_map exe for service '{service}' \
                     must be 1-256 chars, got '{exe}'"
                ));
            }
            if has_control_char(exe) {
                return Err(format!(
                    "[green.scaphandre] process_map exe for service '{service}' \
                     contains control characters"
                ));
            }
        }
        Ok(())
    }

    /// Validate a parsed `[green.cloud]` config section.
    fn validate_cloud_energy(cfg: &CloudEnergyConfig) -> Result<(), String> {
        Self::validate_cloud_endpoint(cfg)?;
        Self::validate_cloud_services(cfg)
    }

    /// Validate `[green.cloud]` endpoint, scrape interval, provider, and instance type.
    fn validate_cloud_endpoint(cfg: &CloudEnergyConfig) -> Result<(), String> {
        if cfg.prometheus_endpoint.is_empty() {
            return Err(
                "[green.cloud] prometheus_endpoint is required when the section is present"
                    .to_string(),
            );
        }
        if !cfg.prometheus_endpoint.starts_with("http://")
            && !cfg.prometheus_endpoint.starts_with("https://")
        {
            return Err(format!(
                "[green.cloud] prometheus_endpoint '{}' must start with 'http://' or 'https://'",
                cfg.prometheus_endpoint
            ));
        }
        validate_http_authority(
            &cfg.prometheus_endpoint,
            "[green.cloud] prometheus_endpoint",
        )?;
        let secs = cfg.scrape_interval.as_secs();
        if !(1..=3600).contains(&secs) {
            return Err(format!(
                "[green.cloud] scrape_interval_secs must be in [1, 3600], got {secs}"
            ));
        }
        if let Some(ref p) = cfg.default_provider
            && !matches!(p.as_str(), "aws" | "gcp" | "azure")
        {
            return Err(format!(
                "[green.cloud] default_provider must be 'aws', 'gcp', or 'azure', got '{p}'"
            ));
        }
        if let Some(ref it) = cfg.default_instance_type
            && !crate::score::cloud_energy::table::is_known_instance_type(it)
        {
            tracing::warn!(
                instance_type = %it,
                "[green.cloud] default_instance_type is not in the embedded \
                 SPECpower table; the provider default watts will be used"
            );
        }
        if let Some(ref m) = cfg.cpu_metric
            && has_control_char(m)
        {
            return Err("[green.cloud] cpu_metric contains control characters".to_string());
        }
        Ok(())
    }

    /// Validate per-service entries in `[green.cloud.services]`: cardinality
    /// cap, name/control-char checks, watts ranges, instance type lookup.
    fn validate_cloud_services(cfg: &CloudEnergyConfig) -> Result<(), String> {
        const MAX_CLOUD_SERVICES: usize = 256;
        if cfg.services.len() > MAX_CLOUD_SERVICES {
            return Err(format!(
                "[green.cloud.services] has {} entries; maximum is {MAX_CLOUD_SERVICES}",
                cfg.services.len()
            ));
        }
        for (service, svc_cfg) in &cfg.services {
            Self::validate_cloud_service_name(service)?;
            Self::validate_cloud_service_cpu_query(service, svc_cfg)?;
            match svc_cfg {
                ServiceCloudConfig::ManualWatts {
                    idle_watts,
                    max_watts,
                    ..
                } => Self::validate_manual_watts(service, *idle_watts, *max_watts)?,
                ServiceCloudConfig::InstanceType {
                    provider,
                    instance_type,
                    ..
                } => Self::validate_instance_type_variant(
                    service,
                    provider.as_deref(),
                    instance_type,
                )?,
            }
        }
        Ok(())
    }

    /// Shape + control-char check on a cloud service name.
    fn validate_cloud_service_name(service: &str) -> Result<(), String> {
        if service.is_empty() || service.len() > 256 {
            return Err(format!(
                "[green.cloud.services] service name '{service}' must be 1-256 chars"
            ));
        }
        if has_control_char(service) {
            return Err(format!(
                "[green.cloud.services] service name '{service}' contains control characters"
            ));
        }
        Ok(())
    }

    /// Reject control characters in a service's optional per-service
    /// `cpu_query` override (log-injection / Prometheus-label-injection
    /// guard).
    fn validate_cloud_service_cpu_query(
        service: &str,
        svc_cfg: &ServiceCloudConfig,
    ) -> Result<(), String> {
        let Some(q) = svc_cfg.cpu_query() else {
            return Ok(());
        };
        if has_control_char(q) {
            return Err(format!(
                "[green.cloud.services.{service}] cpu_query contains control characters"
            ));
        }
        Ok(())
    }

    /// Validate a [`ServiceCloudConfig::ManualWatts`] arm: both values
    /// finite and non-negative, and `max_watts >= idle_watts`.
    fn validate_manual_watts(service: &str, idle_watts: f64, max_watts: f64) -> Result<(), String> {
        if !idle_watts.is_finite() || idle_watts < 0.0 {
            return Err(format!(
                "[green.cloud.services.{service}] idle_watts must be finite and >= 0, \
                 got {idle_watts}"
            ));
        }
        if !max_watts.is_finite() || max_watts < 0.0 {
            return Err(format!(
                "[green.cloud.services.{service}] max_watts must be finite and >= 0, \
                 got {max_watts}"
            ));
        }
        if max_watts < idle_watts {
            return Err(format!(
                "[green.cloud.services.{service}] max_watts ({max_watts}) must be \
                 >= idle_watts ({idle_watts})"
            ));
        }
        Ok(())
    }

    /// Validate a [`ServiceCloudConfig::InstanceType`] arm: provider
    /// allow-list, control-char rejection on `instance_type`, and a
    /// soft warning when the type is not in the embedded `SPECpower`
    /// table (not an error, the provider default is used instead).
    fn validate_instance_type_variant(
        service: &str,
        provider: Option<&str>,
        instance_type: &str,
    ) -> Result<(), String> {
        if let Some(p) = provider
            && !matches!(p, "aws" | "gcp" | "azure")
        {
            return Err(format!(
                "[green.cloud.services.{service}] provider must be 'aws', 'gcp', \
                 or 'azure', got '{p}'"
            ));
        }
        if has_control_char(instance_type) {
            return Err(format!(
                "[green.cloud.services.{service}] instance_type contains control characters"
            ));
        }
        if !instance_type.is_empty()
            && !crate::score::cloud_energy::table::is_known_instance_type(instance_type)
        {
            tracing::warn!(
                service = %service,
                instance_type = %instance_type,
                "[green.cloud.services] instance_type is not in the embedded \
                 SPECpower table; provider default watts will be used"
            );
        }
        Ok(())
    }

    fn validate_daemon_limits(&self) -> Result<(), String> {
        check_range(
            "max_payload_size",
            &self.max_payload_size,
            &1024,
            &(100 * 1024 * 1024),
        )?;
        check_range("max_active_traces", &self.max_active_traces, &1, &1_000_000)?;
        check_range(
            "max_events_per_trace",
            &self.max_events_per_trace,
            &1,
            &100_000,
        )?;
        // 0 is documented as "disable the findings store entirely". Cap
        // the upper end at 10M so a typo can't OOM the daemon.
        check_range(
            "max_retained_findings",
            &self.max_retained_findings,
            &0,
            &10_000_000,
        )?;
        check_range("trace_ttl_ms", &self.trace_ttl_ms, &100, &3_600_000)?;
        check_range("listen_port_http", &self.listen_port, &1, &65535)?;
        check_range("listen_port_grpc", &self.listen_port_grpc, &1, &65535)?;
        self.warn_unusual_daemon_limits();
        Ok(())
    }

    /// Soft startup warnings for daemon-limit values inside the hard
    /// bounds but outside their recommended comfort zone.
    ///
    /// See design doc 07 > "Comfort-zone warnings" for the band table
    /// and the rationale.
    fn warn_unusual_daemon_limits(&self) {
        warn_outside_comfort_zone(
            "max_payload_size",
            &self.max_payload_size,
            &(256 * 1024),
            &(16 * 1024 * 1024),
            "tiny payloads may reject legitimate OTLP batches",
            "large payloads increase ingest latency and memory pressure",
        );
        warn_outside_comfort_zone(
            "max_active_traces",
            &self.max_active_traces,
            &1_000,
            &100_000,
            "aggressive LRU eviction is likely under load",
            "memory footprint grows roughly linearly with this cap",
        );
        warn_outside_comfort_zone(
            "max_events_per_trace",
            &self.max_events_per_trace,
            &100,
            &10_000,
            "complex traces will be truncated by the per-trace ring buffer",
            "very wide ring buffers rarely improve detection quality",
        );
        // Skip the comfort-zone check when the store is intentionally
        // disabled (max_retained_findings == 0); warning on that would
        // be noise.
        if self.max_retained_findings > 0 {
            warn_outside_comfort_zone(
                "max_retained_findings",
                &self.max_retained_findings,
                &100,
                &100_000,
                "old findings will be evicted before /api/findings can serve them",
                "the findings store will hold a large in-memory backlog",
            );
        }
        warn_outside_comfort_zone(
            "trace_ttl_ms",
            &self.trace_ttl_ms,
            &1_000,
            &600_000,
            "TTL below 1s flushes traces before slow spans land",
            "TTL above 10min keeps near-dead traces in the active set",
        );
    }

    fn validate_detection_params(&self) -> Result<(), String> {
        check_min("n_plus_one_threshold", &self.n_plus_one_threshold, &1)?;
        check_min("window_duration_ms", &self.window_duration_ms, &1)?;
        check_min("slow_query_threshold_ms", &self.slow_query_threshold_ms, &1)?;
        check_min(
            "slow_query_min_occurrences",
            &self.slow_query_min_occurrences,
            &1,
        )?;
        check_range("max_fanout", &self.max_fanout, &1, &100_000)?;
        warn_outside_comfort_zone(
            "max_fanout",
            &self.max_fanout,
            &5,
            &1_000,
            "very low fanout floods the findings store with noise",
            "very high fanout suppresses most fan-out detections",
        );
        check_min(
            "chatty_service_min_calls",
            &self.chatty_service_min_calls,
            &1,
        )?;
        check_min(
            "pool_saturation_concurrent_threshold",
            &self.pool_saturation_concurrent_threshold,
            &2,
        )?;
        check_min(
            "serialized_min_sequential",
            &self.serialized_min_sequential,
            &2,
        )?;
        Ok(())
    }

    fn validate_rates(&self) -> Result<(), String> {
        if !(0.0..=1.0).contains(&self.sampling_rate) {
            return Err(format!(
                "sampling_rate must be in [0.0, 1.0], got {}",
                self.sampling_rate
            ));
        }
        if !(0.0..=1.0).contains(&self.io_waste_ratio_max) {
            return Err(format!(
                "io_waste_ratio_max must be in [0.0, 1.0], got {}",
                self.io_waste_ratio_max
            ));
        }
        Ok(())
    }

    /// Warn (but do not reject) non-loopback listen addresses.
    ///
    /// The default is `127.0.0.1` (loopback). Advanced users may override
    /// to `0.0.0.0` for container deployments behind a reverse proxy.
    /// We warn loudly rather than rejecting, because the user's intent is
    /// explicit (they changed the config) and a hard reject would force
    /// workarounds (e.g., iptables) that are harder to audit.
    #[allow(clippy::unnecessary_wraps)]
    fn validate_listen_addr(&self) -> Result<(), String> {
        if self.listen_addr != "127.0.0.1" && self.listen_addr != "::1" {
            tracing::warn!(
                "Daemon configured to listen on non-loopback address: {}. \
                 Endpoints have no authentication, use a reverse proxy or \
                 network policy for security.",
                self.listen_addr
            );
        }
        Ok(())
    }
}

/// Load configuration from a TOML string.
///
/// Supports both the sectioned format and the legacy flat format.
/// Validates that all values are within acceptable bounds after parsing.
///
/// # Errors
///
/// Returns `ConfigError::Parse` if the TOML is malformed, or
/// `ConfigError::Validation` if a field value is out of bounds.
pub fn load_from_str(content: &str) -> Result<Config, ConfigError> {
    let normalized = normalize_toml_path_strings(content);
    let raw: RawConfig = match toml::from_str(normalized.as_ref()) {
        Ok(raw) => raw,
        Err(norm_err) => {
            if matches!(normalized, Cow::Owned(_)) {
                // Path normalization fallback. See design doc 07 >
                // "Windows path normalization" for the rationale.
                tracing::debug!(
                    normalized_error = %norm_err,
                    "path normalization produced invalid TOML; retrying with original input"
                );
                toml::from_str(content).map_err(ConfigError::Parse)?
            } else {
                return Err(ConfigError::Parse(norm_err));
            }
        }
    };
    // Validate before the lossy `Config::from` conversion: a typo like
    // `envrionment = "prod"` would otherwise silently downgrade to
    // Staging instead of erroring.
    if let Some(env_str) = raw.daemon.environment.as_deref()
        && parse_daemon_environment(env_str).is_none()
    {
        return Err(ConfigError::Validation(format!(
            "[daemon] environment '{env_str}' is invalid; \
             expected 'staging' or 'production' (case-insensitive)"
        )));
    }
    let config = Config::from(raw);
    config.validate().map_err(ConfigError::Validation)?;
    Ok(config)
}

/// Errors that can occur during configuration loading.
///
/// `#[non_exhaustive]` so that adding future variants (e.g. a new
/// validation failure when a new config section lands) stays a
/// SemVer-minor change.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// TOML parsing error.
    #[error("config parse error: {0}")]
    Parse(#[from] toml::de::Error),
    /// Validation error (out-of-range values).
    #[error("config validation error: {0}")]
    Validation(String),
}

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

    #[test]
    fn default_config_has_safe_defaults() {
        let config = Config::default();
        assert_eq!(config.max_payload_size, 1_048_576);
        assert_eq!(config.listen_addr, "127.0.0.1");
        assert_eq!(config.n_plus_one_threshold, 5);
        assert_eq!(config.window_duration_ms, 500);
        assert_eq!(config.trace_ttl_ms, 30_000);
        assert_eq!(config.max_active_traces, 10_000);
        assert_eq!(config.max_events_per_trace, 1_000);
    }

    #[test]
    fn parse_empty_toml_gives_defaults() {
        let config = load_from_str("").unwrap();
        assert_eq!(config.max_payload_size, 1_048_576);
    }

    #[test]
    fn parse_partial_toml() {
        let config = load_from_str("n_plus_one_threshold = 10").unwrap();
        assert_eq!(config.n_plus_one_threshold, 10);
        assert_eq!(config.max_payload_size, 1_048_576); // default preserved
    }

    #[test]
    fn parse_window_config() {
        let config = load_from_str(
            "window_duration_ms = 1000\ntrace_ttl_ms = 60000\nmax_active_traces = 5000",
        )
        .unwrap();
        assert_eq!(config.window_duration_ms, 1000);
        assert_eq!(config.trace_ttl_ms, 60_000);
        assert_eq!(config.max_active_traces, 5000);
    }

    #[test]
    fn parse_sectioned_format() {
        let toml = r#"
[thresholds]
n_plus_one_sql_critical_max = 2
n_plus_one_http_warning_max = 5
io_waste_ratio_max = 0.50

[detection]
window_duration_ms = 1000
n_plus_one_min_occurrences = 10

[green]
enabled = false

[daemon]
listen_address = "0.0.0.0"
listen_port_http = 9418
listen_port_grpc = 9417
json_socket = "/var/run/perf-sentinel.sock"
max_active_traces = 20000
trace_ttl_ms = 60000
sampling_rate = 0.5
max_events_per_trace = 500
max_payload_size = 2097152
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.n_plus_one_sql_critical_max, 2);
        assert_eq!(config.n_plus_one_http_warning_max, 5);
        assert!((config.io_waste_ratio_max - 0.50).abs() < f64::EPSILON);
        assert_eq!(config.n_plus_one_threshold, 10);
        assert_eq!(config.window_duration_ms, 1000);
        assert!(!config.green_enabled);
        assert_eq!(config.listen_addr, "0.0.0.0");
        assert_eq!(config.listen_port, 9418);
        assert_eq!(config.listen_port_grpc, 9417);
        assert_eq!(config.json_socket, "/var/run/perf-sentinel.sock");
        assert_eq!(config.max_active_traces, 20_000);
        assert_eq!(config.trace_ttl_ms, 60_000);
        assert!((config.sampling_rate - 0.5).abs() < f64::EPSILON);
        assert_eq!(config.max_events_per_trace, 500);
        assert_eq!(config.max_payload_size, 2_097_152);
    }

    #[test]
    fn parse_windows_style_json_socket_path_in_basic_string() {
        let config = load_from_str(
            r#"
[daemon]
json_socket = "C:\temp\perf-sentinel.sock"
"#,
        )
        .unwrap();
        assert_eq!(config.json_socket, r"C:\temp\perf-sentinel.sock");
    }

    #[test]
    fn parse_escaped_windows_style_json_socket_path_stays_stable() {
        let config = load_from_str(
            r#"
[daemon]
json_socket = "C:\\temp\\perf-sentinel.sock"
"#,
        )
        .unwrap();
        assert_eq!(config.json_socket, r"C:\temp\perf-sentinel.sock");
    }

    #[test]
    fn parse_windows_style_json_socket_path_with_trailing_comment() {
        // Covers `find_basic_string_end` stopping before `#`, a common
        // hand-edited config shape the initial test matrix missed.
        let config = load_from_str(
            "[daemon]\n\
             json_socket = \"C:\\temp\\sock\" # inline note\n",
        )
        .unwrap();
        assert_eq!(config.json_socket, r"C:\temp\sock");
    }

    #[test]
    fn parse_unc_json_socket_path_preserves_double_leading_backslash() {
        // Raw UNC `\\server\share\sock` must round-trip verbatim. The
        // `raw_unc_prefix` branch in `escape_toml_path_backslashes`
        // emits 4 leading `\` so TOML decode yields 2.
        let config = load_from_str(
            r#"
[daemon]
json_socket = "\\server\share\sock"
"#,
        )
        .unwrap();
        assert_eq!(config.json_socket, r"\\server\share\sock");
    }

    #[test]
    fn parse_pre_escaped_unc_json_socket_path_is_stable() {
        let config = load_from_str(
            r#"
[daemon]
json_socket = "\\\\server\\share\\sock"
"#,
        )
        .unwrap();
        assert_eq!(config.json_socket, r"\\server\share\sock");
    }

    #[test]
    fn literal_string_windows_path_bypasses_normalization() {
        // TOML literal strings (`'...'`) already treat `\` literally.
        // Our normalizer must not touch them; checked indirectly by
        // confirming the parser accepts a path with lone `\` inside `'`.
        let config = load_from_str(
            r"
[daemon]
json_socket = 'C:\temp\sock'
",
        )
        .unwrap();
        assert_eq!(config.json_socket, r"C:\temp\sock");
    }

    #[test]
    fn normalization_applies_to_tls_cert_and_key_paths() {
        // TLS paths are validated as filesystem entries, so a non-existent
        // literal yields ConfigError::Validation. The test passes iff the
        // error message surfaces the expected *normalized* path, i.e. our
        // rewriter reached both keys before validation ran.
        let err = load_from_str(
            r#"
[daemon]
tls_cert_path = "C:\certs\server.crt"
tls_key_path = "C:\certs\server.key"
"#,
        )
        .unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains(r"C:\certs\server.crt") || msg.contains(r"C:\certs\server.key"),
            "expected normalized TLS path in error, got: {msg}"
        );
    }

    #[test]
    fn normalization_applies_to_all_registered_path_keys() {
        // Guard against a copy-paste bug in `TOML_PATH_STRING_KEYS`:
        // exercise each key via the unit-level normalizer rather than
        // the full loader (hourly/calibration files would otherwise
        // trigger disk I/O or validation noise).
        for key in TOML_PATH_STRING_KEYS {
            let line = format!("{key} = \"C:\\temp\\x\"\n");
            let rewritten = normalize_toml_path_strings(&line);
            assert!(
                matches!(rewritten, Cow::Owned(_)),
                "{key}: expected normalization to rewrite bare Windows path"
            );
            assert!(
                rewritten.as_ref().contains(r#""C:\\temp\\x""#),
                "{key}: normalized output missing escaped path, got {rewritten}"
            );
        }
    }

    #[test]
    fn normalization_leaves_toml_escape_sequences_literal_in_path_keys() {
        // `\t` and `\n` inside a path key are treated as literal
        // backslash-sequences, not TOML escapes. This is by design for
        // `TOML_PATH_STRING_KEYS` and documented in the helper's rustdoc.
        let config = load_from_str(
            r#"
[daemon]
json_socket = "C:\new\tmp\sock"
"#,
        )
        .unwrap();
        assert_eq!(config.json_socket, r"C:\new\tmp\sock");
    }

    #[test]
    fn load_from_str_falls_back_when_original_error_is_unrelated_to_path() {
        // Force the normalization branch (Cow::Owned) via a Windows path,
        // then introduce a type mismatch on a strictly-typed key
        // (`listen_port` is `u16`). Both the normalized and the original
        // parse fail; we just assert we surface a ConfigError::Parse
        // rather than silently masking the issue.
        let err = load_from_str(
            r#"
[daemon]
json_socket = "C:\temp\sock"
sampling_rate = "not a number"
"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ConfigError::Parse(_)),
            "expected ConfigError::Parse, got {err:?}"
        );
    }

    #[test]
    fn find_basic_string_end_handles_escaped_inner_quote() {
        // `"a\"b"`: the first `"` at byte 3 is escaped, real end at byte
        // 5. Guards the linear `run`-counter rewrite against regressions
        // that would terminate too early.
        let value = r#""a\"b""#;
        assert_eq!(find_basic_string_end(value), Some(5));
    }

    #[test]
    fn find_basic_string_end_survives_very_long_backslash_run() {
        // Previously the lookbehind was O(n²); this is a smoke test
        // that a pathological input completes in well under the test
        // timeout. If this regresses to quadratic, it still passes,
        // but the timing would blow up.
        let mut input = String::from("\"");
        input.extend(std::iter::repeat_n('\\', 10_000));
        input.push('"');
        // 10_000 backslashes → 5_000 `\\` pairs → closing `"` valid.
        assert_eq!(find_basic_string_end(&input), Some(10_001));
    }

    #[test]
    fn section_overrides_flat_field() {
        let toml = r"
n_plus_one_threshold = 7
window_duration_ms = 800

[detection]
n_plus_one_min_occurrences = 12
";
        let config = load_from_str(toml).unwrap();
        // Section takes priority over flat field
        assert_eq!(config.n_plus_one_threshold, 12);
        // Flat field used when section does not override
        assert_eq!(config.window_duration_ms, 800);
    }

    #[test]
    fn new_fields_have_correct_defaults() {
        let config = Config::default();
        assert_eq!(config.n_plus_one_sql_critical_max, 0);
        assert_eq!(config.n_plus_one_http_warning_max, 3);
        assert!((config.io_waste_ratio_max - 0.30).abs() < f64::EPSILON);
        assert!(config.green_enabled);
        assert_eq!(config.listen_port_grpc, 4317);
        assert_eq!(config.json_socket, "/tmp/perf-sentinel.sock");
        assert!((config.sampling_rate - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn default_config_validates() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn rejects_sampling_rate_above_one() {
        let result = load_from_str("[daemon]\nsampling_rate = 5.0");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("sampling_rate"), "got: {err}");
    }

    #[test]
    fn rejects_negative_sampling_rate() {
        let result = load_from_str("[daemon]\nsampling_rate = -0.1");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_io_waste_ratio_max_above_one() {
        let result = load_from_str("[thresholds]\nio_waste_ratio_max = 1.5");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("io_waste_ratio_max"), "got: {err}");
    }

    #[test]
    fn rejects_zero_max_payload_size() {
        let result = load_from_str("[daemon]\nmax_payload_size = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_n_plus_one_threshold() {
        let result = load_from_str("n_plus_one_threshold = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_active_traces() {
        let result = load_from_str("max_active_traces = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_events_per_trace() {
        let result = load_from_str("max_events_per_trace = 0");
        assert!(result.is_err());
    }

    #[test]
    fn slow_query_defaults() {
        let config = Config::default();
        assert_eq!(config.slow_query_threshold_ms, 500);
        assert_eq!(config.slow_query_min_occurrences, 3);
        assert!(config.green_default_region.is_none());
        assert!(config.green_service_regions.is_empty());
        assert!(
            (config.green_embodied_carbon_per_request_gco2
                - DEFAULT_EMBODIED_CARBON_PER_REQUEST_GCO2)
                .abs()
                < f64::EPSILON
        );
    }

    #[test]
    fn parse_slow_query_config() {
        let toml = r"
[detection]
slow_query_threshold_ms = 1000
slow_query_min_occurrences = 5
";
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.slow_query_threshold_ms, 1000);
        assert_eq!(config.slow_query_min_occurrences, 5);
    }

    #[test]
    fn parse_green_default_region() {
        let toml = r#"
[green]
enabled = true
default_region = "eu-west-3"
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.green_default_region.as_deref(), Some("eu-west-3"));
    }

    #[test]
    fn parse_green_service_regions() {
        let toml = r#"
[green]
enabled = true
default_region = "eu-west-3"

[green.service_regions]
"order-svc" = "us-east-1"
"chat-svc" = "ap-southeast-1"
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.green_service_regions.len(), 2);
        assert_eq!(
            config
                .green_service_regions
                .get("order-svc")
                .map(String::as_str),
            Some("us-east-1")
        );
        assert_eq!(
            config
                .green_service_regions
                .get("chat-svc")
                .map(String::as_str),
            Some("ap-southeast-1")
        );
    }

    #[test]
    fn parse_green_embodied_carbon_override() {
        let toml = r"
[green]
enabled = true
embodied_carbon_per_request_gco2 = 0.005
";
        let config = load_from_str(toml).unwrap();
        assert!((config.green_embodied_carbon_per_request_gco2 - 0.005).abs() < f64::EPSILON);
    }

    #[test]
    fn rejects_negative_embodied_carbon() {
        let result = load_from_str("[green]\nembodied_carbon_per_request_gco2 = -0.001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("embodied_carbon_per_request_gco2"),
            "got: {err}"
        );
    }

    #[test]
    fn accepts_zero_embodied_carbon() {
        let toml = r"
[green]
embodied_carbon_per_request_gco2 = 0.0
";
        let config = load_from_str(toml).unwrap();
        assert!((config.green_embodied_carbon_per_request_gco2 - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn empty_service_regions_default() {
        let toml = r#"
[green]
default_region = "eu-west-3"
"#;
        let config = load_from_str(toml).unwrap();
        assert!(config.green_service_regions.is_empty());
    }

    // ----- Region validation + lowercase + both-set -----

    #[test]
    fn rejects_invalid_default_region_characters() {
        // Space in region name: log-injection protection at config load.
        let result = load_from_str("[green]\ndefault_region = \"eu west 3\"");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("default_region"),
            "error should mention default_region, got: {err}"
        );
    }

    #[test]
    fn rejects_oversized_default_region() {
        // 65 chars, just over the 64-char cap.
        let long_region = "a".repeat(65);
        let toml = format!("[green]\ndefault_region = \"{long_region}\"");
        let result = load_from_str(&toml);
        assert!(result.is_err());
    }

    #[test]
    fn rejects_default_region_with_newline_escape() {
        // In a TOML basic string, `\n` is an escape sequence for a real
        // newline byte. The validator must reject the resulting control
        // char to block log-forging via default_region.
        let result = load_from_str("[green]\ndefault_region = \"eu-west-3\\n\"");
        assert!(result.is_err());
        assert!(
            result.unwrap_err().to_string().contains("default_region"),
            "error should mention default_region"
        );
    }

    #[test]
    fn rejects_default_region_with_literal_newline() {
        // Multi-line basic string with an actual newline byte in the
        // value. Also rejected at load time.
        let result = load_from_str("[green]\ndefault_region = \"\"\"eu-west-3\n\"\"\"");
        assert!(result.is_err());
    }

    #[test]
    fn accepts_known_regions() {
        // Sanity: all known region names pass the validator.
        for region in ["eu-west-3", "us-east-1", "fr", "mars-1", "unknown"] {
            let toml = format!("[green]\ndefault_region = \"{region}\"");
            let config = load_from_str(&toml)
                .unwrap_or_else(|e| panic!("region '{region}' should be accepted, got error: {e}"));
            assert_eq!(config.green_default_region.as_deref(), Some(region));
        }
    }

    #[test]
    fn rejects_invalid_service_regions_service_name() {
        let toml = r#"
[green.service_regions]
"bad service" = "us-east-1"
"#;
        let result = load_from_str(toml);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("service_regions"),
            "error should mention service_regions, got: {err}"
        );
    }

    #[test]
    fn rejects_invalid_service_regions_region_value() {
        let toml = r#"
[green.service_regions]
"order-svc" = "us east 1"
"#;
        let result = load_from_str(toml);
        assert!(result.is_err());
    }

    #[test]
    fn rejects_oversized_service_regions_map() {
        // Fat-finger or malicious config with too many entries gets
        // rejected at load time with a clear error mentioning the cap.
        use std::fmt::Write as _;
        let mut toml = String::from("[green.service_regions]\n");
        for i in 0..1025 {
            let _ = writeln!(toml, "\"svc-{i:04}\" = \"eu-west-3\"");
        }
        let result = load_from_str(&toml);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("service_regions") && err.contains("1025"),
            "error should mention service_regions and the count, got: {err}"
        );
    }

    #[test]
    fn accepts_service_regions_at_exactly_the_cap() {
        // Boundary check: exactly 1024 entries should pass.
        use std::fmt::Write as _;
        let mut toml = String::from("[green.service_regions]\n");
        for i in 0..1024 {
            let _ = writeln!(toml, "\"svc-{i:04}\" = \"eu-west-3\"");
        }
        let config = load_from_str(&toml).expect("1024 entries should be accepted");
        assert_eq!(config.green_service_regions.len(), 1024);
    }

    #[test]
    fn service_regions_keys_are_lowercased_on_load() {
        // Config loader lowercases keys so resolve_region's
        // case-insensitive lookup works transparently.
        let toml = r#"
[green.service_regions]
"Order-Svc" = "us-east-1"
"CHAT-SVC" = "ap-southeast-1"
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.green_service_regions.len(), 2);
        // Keys are lowercased regardless of TOML casing.
        assert_eq!(
            config
                .green_service_regions
                .get("order-svc")
                .map(String::as_str),
            Some("us-east-1")
        );
        assert_eq!(
            config
                .green_service_regions
                .get("chat-svc")
                .map(String::as_str),
            Some("ap-southeast-1")
        );
        // The original casings should NOT be present.
        assert!(!config.green_service_regions.contains_key("Order-Svc"));
    }

    #[test]
    fn rejects_zero_slow_query_threshold() {
        let result = load_from_str("[detection]\nslow_query_threshold_ms = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_slow_query_min_occurrences() {
        let result = load_from_str("[detection]\nslow_query_min_occurrences = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_fanout() {
        let result = load_from_str("[detection]\nmax_fanout = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_max_fanout_over_100k() {
        let result = load_from_str("[detection]\nmax_fanout = 100001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_fanout"), "got: {err}");
    }

    #[test]
    fn accepts_max_fanout_at_100k() {
        let result = load_from_str("[detection]\nmax_fanout = 100000");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_payload_size_over_100mb() {
        let result = load_from_str("[daemon]\nmax_payload_size = 104857601");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_payload_size"), "got: {err}");
    }

    #[test]
    fn accepts_max_payload_size_at_100mb() {
        let result = load_from_str("[daemon]\nmax_payload_size = 104857600");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_active_traces_over_1m() {
        let result = load_from_str("[daemon]\nmax_active_traces = 1000001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_active_traces"), "got: {err}");
    }

    #[test]
    fn accepts_max_active_traces_at_1m() {
        let result = load_from_str("[daemon]\nmax_active_traces = 1000000");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_events_per_trace_over_100k() {
        let result = load_from_str("[daemon]\nmax_events_per_trace = 100001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_events_per_trace"), "got: {err}");
    }

    #[test]
    fn accepts_max_events_per_trace_at_100k() {
        let result = load_from_str("[daemon]\nmax_events_per_trace = 100000");
        assert!(result.is_ok());
    }

    // --- comfort-zone warnings (parse OK, hard caps unchanged) ---

    #[test]
    fn config_defaults_sit_inside_every_comfort_zone() {
        // Locks the invariant that the canonical defaults never trigger
        // a startup warning. If a default is moved, this test forces an
        // explicit re-check of the matching comfort band.
        let cfg = Config::default();
        assert!(
            (256 * 1024..=16 * 1024 * 1024).contains(&cfg.max_payload_size),
            "default max_payload_size {} is outside its comfort zone",
            cfg.max_payload_size
        );
        assert!(
            (1_000..=100_000).contains(&cfg.max_active_traces),
            "default max_active_traces {} is outside its comfort zone",
            cfg.max_active_traces
        );
        assert!(
            (100..=10_000).contains(&cfg.max_events_per_trace),
            "default max_events_per_trace {} is outside its comfort zone",
            cfg.max_events_per_trace
        );
        assert!(
            (100..=100_000).contains(&cfg.max_retained_findings),
            "default max_retained_findings {} is outside its comfort zone",
            cfg.max_retained_findings
        );
        assert!(
            (1_000..=600_000).contains(&cfg.trace_ttl_ms),
            "default trace_ttl_ms {} is outside its comfort zone",
            cfg.trace_ttl_ms
        );
        assert!(
            (5..=1_000).contains(&cfg.max_fanout),
            "default max_fanout {} is outside its comfort zone",
            cfg.max_fanout
        );
    }

    #[test]
    fn accepts_max_active_traces_below_comfort_floor_with_warning() {
        // 500 < comfort floor (1_000) but well within hard floor (1).
        let result = load_from_str("[daemon]\nmax_active_traces = 500");
        assert!(result.is_ok(), "expected parse OK, got {result:?}");
    }

    #[test]
    fn accepts_max_active_traces_above_comfort_ceiling_with_warning() {
        // 500_000 > comfort ceiling (100_000) but within hard ceiling (1_000_000).
        let result = load_from_str("[daemon]\nmax_active_traces = 500000");
        assert!(result.is_ok(), "expected parse OK, got {result:?}");
    }

    #[test]
    fn accepts_max_events_per_trace_outside_comfort_zone() {
        // 10 < comfort floor (100); 50_000 > comfort ceiling (10_000).
        // Both inside hard bounds [1, 100_000].
        for value in [10, 50_000] {
            let result = load_from_str(&format!("[daemon]\nmax_events_per_trace = {value}\n"));
            assert!(result.is_ok(), "expected {value} to parse, got {result:?}");
        }
    }

    #[test]
    fn accepts_trace_ttl_outside_comfort_but_inside_hard_bounds() {
        // 200ms < comfort floor (1s); 1_800_000 (30min) > comfort ceiling (10min).
        for value in [200_u64, 1_800_000_u64] {
            let result = load_from_str(&format!("[daemon]\ntrace_ttl_ms = {value}\n"));
            assert!(result.is_ok(), "expected {value} to parse, got {result:?}");
        }
    }

    #[test]
    fn accepts_max_fanout_outside_comfort_but_inside_hard_bounds() {
        // 2 < comfort floor (5); 5_000 > comfort ceiling (1_000).
        for value in [2, 5_000] {
            let result = load_from_str(&format!("[detection]\nmax_fanout = {value}\n"));
            assert!(result.is_ok(), "expected {value} to parse, got {result:?}");
        }
    }

    #[test]
    fn accepts_max_payload_size_outside_comfort_but_inside_hard_bounds() {
        // 64 KiB < comfort floor (256 KiB); 32 MiB > comfort ceiling (16 MiB).
        for value in [64 * 1024_u64, 32 * 1024 * 1024_u64] {
            let result = load_from_str(&format!("[daemon]\nmax_payload_size = {value}\n"));
            assert!(result.is_ok(), "expected {value} to parse, got {result:?}");
        }
    }

    // --- max_retained_findings hard cap (was unbounded before) ---

    #[test]
    fn accepts_zero_max_retained_findings_disables_store() {
        // `0` is a documented way to disable the findings store and
        // reclaim its memory. It must keep parsing.
        let result = load_from_str("[daemon]\nmax_retained_findings = 0");
        assert!(result.is_ok(), "expected 0 to parse, got {result:?}");
    }

    #[test]
    fn rejects_max_retained_findings_above_10m() {
        let result = load_from_str("[daemon]\nmax_retained_findings = 10000001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_retained_findings"), "got: {err}");
    }

    #[test]
    fn accepts_max_retained_findings_at_10m_hard_ceiling() {
        let result = load_from_str("[daemon]\nmax_retained_findings = 10000000");
        assert!(result.is_ok());
    }

    #[test]
    fn accepts_max_retained_findings_outside_comfort_but_inside_hard_bounds() {
        // 50 < comfort floor (100); 500_000 > comfort ceiling (100_000).
        for value in [50, 500_000] {
            let result = load_from_str(&format!("[daemon]\nmax_retained_findings = {value}\n"));
            assert!(result.is_ok(), "expected {value} to parse, got {result:?}");
        }
    }

    #[test]
    fn rejects_trace_ttl_below_100() {
        let result = load_from_str("[daemon]\ntrace_ttl_ms = 50");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_window_duration() {
        let result = load_from_str("[detection]\nwindow_duration_ms = 0");
        assert!(result.is_err());
    }

    #[test]
    fn green_disabled_parses() {
        let config = load_from_str("[green]\nenabled = false").unwrap();
        assert!(!config.green_enabled);
    }

    // -- Port validation --

    #[test]
    fn rejects_port_zero() {
        let result = load_from_str("[daemon]\nlisten_port_http = 0");
        assert!(result.is_err());
    }

    #[test]
    fn accepts_port_one() {
        let config = load_from_str("[daemon]\nlisten_port_http = 1").unwrap();
        assert_eq!(config.listen_port, 1);
    }

    #[test]
    fn accepts_port_65535() {
        let config = load_from_str("[daemon]\nlisten_port_http = 65535").unwrap();
        assert_eq!(config.listen_port, 65535);
    }

    #[test]
    fn rejects_grpc_port_zero() {
        let result = load_from_str("[daemon]\nlisten_port_grpc = 0");
        assert!(result.is_err());
    }

    // -- trace_ttl_ms upper bound --

    #[test]
    fn rejects_trace_ttl_above_1h() {
        let result = load_from_str("[daemon]\ntrace_ttl_ms = 3600001");
        assert!(result.is_err());
    }

    #[test]
    fn accepts_trace_ttl_at_1h() {
        let config = load_from_str("[daemon]\ntrace_ttl_ms = 3600000").unwrap();
        assert_eq!(config.trace_ttl_ms, 3_600_000);
    }

    #[test]
    fn accepts_trace_ttl_at_100ms() {
        let config = load_from_str("[daemon]\ntrace_ttl_ms = 100").unwrap();
        assert_eq!(config.trace_ttl_ms, 100);
    }

    // -- Sampling rate edge cases --

    #[test]
    fn accepts_sampling_rate_zero() {
        let config = load_from_str("[daemon]\nsampling_rate = 0.0").unwrap();
        assert!((config.sampling_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn accepts_sampling_rate_one() {
        let config = load_from_str("[daemon]\nsampling_rate = 1.0").unwrap();
        assert!((config.sampling_rate - 1.0).abs() < f64::EPSILON);
    }

    // --- [daemon] environment parsing ---

    #[test]
    fn daemon_environment_defaults_to_staging() {
        let config = Config::default();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Staging);
        assert_eq!(config.confidence(), Confidence::DaemonStaging);
    }

    #[test]
    fn daemon_environment_omitted_uses_default() {
        let config = load_from_str("[daemon]\nmax_active_traces = 100").unwrap();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Staging);
    }

    #[test]
    fn daemon_environment_staging() {
        let config = load_from_str("[daemon]\nenvironment = \"staging\"").unwrap();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Staging);
        assert_eq!(config.confidence(), Confidence::DaemonStaging);
    }

    #[test]
    fn daemon_environment_production() {
        let config = load_from_str("[daemon]\nenvironment = \"production\"").unwrap();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Production);
        assert_eq!(config.confidence(), Confidence::DaemonProduction);
    }

    #[test]
    fn daemon_environment_case_insensitive() {
        let config = load_from_str("[daemon]\nenvironment = \"PRODUCTION\"").unwrap();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Production);
        let config = load_from_str("[daemon]\nenvironment = \"Staging\"").unwrap();
        assert_eq!(config.daemon_environment, DaemonEnvironment::Staging);
    }

    #[test]
    fn daemon_environment_rejects_unknown() {
        let result = load_from_str("[daemon]\nenvironment = \"prod\"");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("environment"), "got: {err}");
        assert!(err.contains("staging"), "error should mention valid values");
        assert!(
            err.contains("production"),
            "error should mention valid values"
        );
    }

    #[test]
    fn daemon_environment_rejects_empty() {
        let result = load_from_str("[daemon]\nenvironment = \"\"");
        assert!(result.is_err());
    }

    #[test]
    fn daemon_environment_rejects_dev() {
        let result = load_from_str("[daemon]\nenvironment = \"dev\"");
        assert!(result.is_err());
    }

    #[test]
    fn daemon_environment_as_str() {
        assert_eq!(DaemonEnvironment::Staging.as_str(), "staging");
        assert_eq!(DaemonEnvironment::Production.as_str(), "production");
    }

    // --- [green] use_hourly_profiles ---

    #[test]
    fn green_use_hourly_profiles_defaults_to_true() {
        let config = Config::default();
        assert!(config.green_use_hourly_profiles);
    }

    #[test]
    fn green_use_hourly_profiles_omitted_uses_default() {
        let config = load_from_str("[green]\nenabled = true\n").unwrap();
        assert!(config.green_use_hourly_profiles);
    }

    #[test]
    fn green_use_hourly_profiles_explicit_false() {
        let config = load_from_str("[green]\nuse_hourly_profiles = false\n").unwrap();
        assert!(!config.green_use_hourly_profiles);
    }

    #[test]
    fn green_use_hourly_profiles_explicit_true() {
        let config = load_from_str("[green]\nuse_hourly_profiles = true\n").unwrap();
        assert!(config.green_use_hourly_profiles);
    }

    // --- [green] hourly_profiles_file ---

    #[test]
    fn hourly_profiles_file_absent_by_default() {
        let config = Config::default();
        assert!(config.green_hourly_profiles_file.is_none());
        assert!(config.green_custom_hourly_profiles.is_none());
    }

    #[test]
    fn hourly_profiles_file_control_chars_rejected() {
        let config = load_from_str("[green]\nhourly_profiles_file = \"/tmp/profiles\\n.json\"\n");
        // The control character check happens during loading (sets None)
        // and then validate_green rejects the config.
        if let Ok(c) = config {
            let err = c.validate().unwrap_err();
            assert!(
                err.contains("control characters") || err.contains("failed to load"),
                "expected control char or load failure error, got: {err}"
            );
        } else {
            // TOML parse error is also acceptable
        }
    }

    #[test]
    fn hourly_profiles_file_nonexistent_path_rejected() {
        let result =
            load_from_str("[green]\nhourly_profiles_file = \"/nonexistent/profiles.json\"\n");
        let err = result.unwrap_err();
        assert!(
            format!("{err}").contains("failed to load"),
            "expected load failure error, got: {err}"
        );
    }

    #[test]
    fn hourly_profiles_windows_path_reports_load_failure_not_parse_error() {
        let err = load_from_str(
            r#"
[green]
hourly_profiles_file = "C:\temp\profiles.json"
"#,
        )
        .unwrap_err();
        assert!(
            format!("{err}").contains("failed to load"),
            "expected load failure error, got: {err}"
        );
    }

    // --- [green.scaphandre] parsing ---

    #[test]
    fn scaphandre_absent_by_default() {
        let config = Config::default();
        assert!(config.green_scaphandre.is_none());
    }

    #[test]
    fn scaphandre_empty_section_parses_to_none() {
        // An empty [green.scaphandre] table (no endpoint) is treated
        // as "Scaphandre not configured": the scraper is not spawned.
        let config = load_from_str("[green.scaphandre]\n").unwrap();
        assert!(config.green_scaphandre.is_none());
    }

    #[test]
    fn scaphandre_endpoint_only() {
        let config =
            load_from_str("[green.scaphandre]\nendpoint = \"http://localhost:8080/metrics\"\n")
                .unwrap();
        let cfg = config.green_scaphandre.unwrap();
        assert_eq!(cfg.endpoint, "http://localhost:8080/metrics");
        // Default interval is 5 s.
        assert_eq!(cfg.scrape_interval.as_secs(), 5);
        assert!(cfg.process_map.is_empty());
    }

    #[test]
    fn scaphandre_full_config() {
        let toml = r#"
[green.scaphandre]
endpoint = "http://localhost:9090/metrics"
scrape_interval_secs = 10

[green.scaphandre.process_map]
"order-svc" = "java"
"chat-svc" = "dotnet"
"#;
        let config = load_from_str(toml).unwrap();
        let cfg = config.green_scaphandre.unwrap();
        assert_eq!(cfg.endpoint, "http://localhost:9090/metrics");
        assert_eq!(cfg.scrape_interval.as_secs(), 10);
        assert_eq!(
            cfg.process_map.get("order-svc").map(String::as_str),
            Some("java")
        );
        assert_eq!(
            cfg.process_map.get("chat-svc").map(String::as_str),
            Some("dotnet")
        );
    }

    #[test]
    fn scaphandre_accepts_https_endpoint() {
        let result =
            load_from_str("[green.scaphandre]\nendpoint = \"https://secure:8080/metrics\"\n");
        assert!(result.is_ok(), "HTTPS endpoints should be accepted");
    }

    #[test]
    fn scaphandre_rejects_zero_interval() {
        let result = load_from_str(
            "[green.scaphandre]\nendpoint = \"http://localhost/metrics\"\nscrape_interval_secs = 0\n",
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("scrape_interval_secs"), "got: {err}");
    }

    #[test]
    fn scaphandre_rejects_huge_interval() {
        let result = load_from_str(
            "[green.scaphandre]\nendpoint = \"http://localhost/metrics\"\nscrape_interval_secs = 99999\n",
        );
        assert!(result.is_err());
    }

    #[test]
    fn scaphandre_rejects_empty_exe_in_process_map() {
        let toml = r#"
[green.scaphandre]
endpoint = "http://localhost/metrics"

[green.scaphandre.process_map]
"order-svc" = ""
"#;
        let result = load_from_str(toml);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("process_map"), "got: {err}");
    }

    #[test]
    fn scaphandre_accepts_interval_at_boundary_1s() {
        let config = load_from_str(
            "[green.scaphandre]\nendpoint = \"http://localhost/metrics\"\nscrape_interval_secs = 1\n",
        )
        .unwrap();
        assert_eq!(
            config
                .green_scaphandre
                .as_ref()
                .unwrap()
                .scrape_interval
                .as_secs(),
            1
        );
    }

    #[test]
    fn scaphandre_accepts_interval_at_boundary_3600s() {
        let config = load_from_str(
            "[green.scaphandre]\nendpoint = \"http://localhost/metrics\"\nscrape_interval_secs = 3600\n",
        )
        .unwrap();
        assert_eq!(
            config
                .green_scaphandre
                .as_ref()
                .unwrap()
                .scrape_interval
                .as_secs(),
            3600
        );
    }

    // ------------------------------------------------------------------
    // [green.cloud] config tests
    // ------------------------------------------------------------------

    #[test]
    fn cloud_section_absent_yields_none() {
        let toml = "[green]\nenabled = true\n";
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        assert!(cfg.green_cloud_energy.is_none());
    }

    #[test]
    fn cloud_section_endpoint_only_parses_with_defaults() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://prom:9090"
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let cloud = cfg.green_cloud_energy.unwrap();
        assert_eq!(cloud.prometheus_endpoint, "http://prom:9090");
        assert_eq!(cloud.scrape_interval.as_secs(), 15);
        assert!(cloud.default_provider.is_none());
        assert!(cloud.services.is_empty());
    }

    #[test]
    fn cloud_section_full_config_with_both_service_types() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://prom:9090"
scrape_interval_secs = 30
default_provider = "aws"

[green.cloud.services.svc-a]
provider = "gcp"
instance_type = "n2-standard-8"

[green.cloud.services.svc-b]
idle_watts = 45
max_watts = 120
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        assert!(cfg.validate().is_ok());
        let cloud = cfg.green_cloud_energy.as_ref().unwrap();
        assert_eq!(cloud.scrape_interval.as_secs(), 30);
        assert_eq!(cloud.default_provider.as_deref(), Some("aws"));
        assert_eq!(cloud.services.len(), 2);
    }

    #[test]
    fn cloud_accepts_https_endpoint() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "https://prom:9090"
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        assert!(cfg.validate().is_ok(), "HTTPS endpoints should be accepted");
    }

    #[test]
    fn cloud_rejects_credentials_in_endpoint() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://user:pass@prom:9090"
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("credentials"), "error: {err}");
    }

    #[test]
    fn cloud_rejects_invalid_scrape_interval() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://prom:9090"
scrape_interval_secs = 0
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("scrape_interval"), "error: {err}");
    }

    #[test]
    fn cloud_rejects_invalid_provider() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://prom:9090"
default_provider = "alibaba"
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("default_provider"), "error: {err}");
    }

    #[test]
    fn cloud_rejects_max_watts_less_than_idle() {
        let toml = r#"
[green.cloud]
prometheus_endpoint = "http://prom:9090"

[green.cloud.services.bad-svc]
idle_watts = 100
max_watts = 50
"#;
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("max_watts"), "error: {err}");
    }

    #[test]
    fn cloud_rejects_service_name_with_control_chars() {
        let toml = "
[green.cloud]
prometheus_endpoint = \"http://prom:9090\"

[green.cloud.services.\"bad\\nsvc\"]
idle_watts = 10
max_watts = 50
";
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("control characters"), "error: {err}");
    }

    #[test]
    fn config_per_operation_coefficients_default_true() {
        let cfg = Config::default();
        assert!(cfg.green_per_operation_coefficients);
    }

    #[test]
    fn config_include_network_transport_default_false() {
        let cfg = Config::default();
        assert!(!cfg.green_include_network_transport);
    }

    #[test]
    fn config_network_energy_per_byte_kwh_default() {
        let cfg = Config::default();
        assert!(
            (cfg.green_network_energy_per_byte_kwh
                - crate::score::carbon::DEFAULT_NETWORK_ENERGY_PER_BYTE_KWH)
                .abs()
                < f64::EPSILON
        );
    }

    #[test]
    fn config_network_energy_per_byte_kwh_rejects_negative() {
        let toml = r"
[green]
network_energy_per_byte_kwh = -0.001
";
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("network_energy_per_byte_kwh"), "error: {err}");
    }

    #[test]
    fn config_network_energy_per_byte_kwh_rejects_nan() {
        let cfg = Config {
            green_network_energy_per_byte_kwh: f64::NAN,
            ..Config::default()
        };
        let err = cfg.validate().unwrap_err();
        assert!(err.contains("network_energy_per_byte_kwh"), "error: {err}");
    }

    #[test]
    fn config_per_operation_coefficients_from_toml() {
        let toml = r"
[green]
per_operation_coefficients = false
";
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        assert!(!cfg.green_per_operation_coefficients);
    }

    #[test]
    fn config_include_network_transport_from_toml() {
        let toml = r"
[green]
include_network_transport = true
network_energy_per_byte_kwh = 0.00000000008
";
        let cfg: Config = toml::from_str::<RawConfig>(toml).unwrap().into();
        assert!(cfg.green_include_network_transport);
        assert!((cfg.green_network_energy_per_byte_kwh - 0.000_000_000_08).abs() < f64::EPSILON);
    }

    // --- validate_http_authority error paths ---

    #[test]
    fn validate_http_authority_rejects_empty_host() {
        assert!(validate_http_authority("http://", "test").is_err());
    }

    #[test]
    fn validate_http_authority_rejects_credentials() {
        let err = validate_http_authority("http://user:pass@host/", "test").unwrap_err();
        assert!(err.contains("credentials"));
    }

    #[test]
    fn validate_http_authority_rejects_control_char() {
        // Embed a tab (0x09) in the host.
        let err = validate_http_authority("http://bad\thost/", "test").unwrap_err();
        assert!(err.contains("control"));
    }

    #[test]
    fn validate_http_authority_rejects_invalid_ipv4_port() {
        let err = validate_http_authority("http://host:abc/", "test").unwrap_err();
        assert!(err.contains("port"));
    }

    #[test]
    fn validate_http_authority_accepts_bare_ipv6() {
        // `[::1]` without port: should not error on the port-parse branch.
        assert!(validate_http_authority("http://[::1]/metrics", "test").is_ok());
    }

    #[test]
    fn validate_http_authority_accepts_ipv6_with_port() {
        assert!(validate_http_authority("http://[::1]:8080/metrics", "test").is_ok());
    }

    #[test]
    fn validate_http_authority_rejects_ipv6_with_invalid_port() {
        let err = validate_http_authority("http://[::1]:abc/metrics", "test").unwrap_err();
        assert!(err.contains("port"));
    }

    #[test]
    fn validate_http_authority_accepts_https_scheme() {
        assert!(validate_http_authority("https://host:443/", "test").is_ok());
    }

    // --- validate_green error paths ---

    #[test]
    fn validate_green_rejects_nonfinite_embodied_carbon() {
        let toml = "[green]\nembodied_carbon_per_request_gco2 = nan\n";
        let err = load_from_str(toml).unwrap_err();
        assert!(format!("{err:?}").contains("finite"));
    }

    #[test]
    fn validate_green_rejects_hourly_profiles_file_that_fails_to_load() {
        let toml = r#"
[green]
hourly_profiles_file = "/tmp/does-not-exist-perfsentinel-test.json"
"#;
        let err = load_from_str(toml).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("hourly_profiles_file") || msg.contains("failed to load"));
    }

    // --- convert_electricity_maps_section branches ---

    // Local imports used by all the electricity_maps tests below.
    // `HashMap` and `Duration` are already in scope via `use super::*;`
    // at the top of this module, but Qodana flags the fully-qualified
    // forms as unnecessary; using the short names reads cleaner anyway.
    use crate::score::electricity_maps::ElectricityMapsConfig;

    #[test]
    fn electricity_maps_empty_api_key_returns_none() {
        // When the api_key is explicitly an empty string and no env var is
        // set, the conversion returns None (subsystem stays inactive).
        let raw = ElectricityMapsSection {
            api_key: Some(String::new()),
            endpoint: None,
            poll_interval_secs: None,
            region_map: HashMap::new(),
        };
        // Pass a stubbed env-lookup that returns None so the test is
        // independent of the ambient process environment (no `unsafe`
        // env mutation, no races with other tests in the same binary).
        assert!(convert_electricity_maps_section_with_env(&raw, || None).is_none());
    }

    #[test]
    fn electricity_maps_warn_when_api_key_in_config_file() {
        // `api_key` set, env var unset → returns Some(...) but emits a
        // warning about preferring the env var. The warning path is
        // exercised; we just verify the conversion succeeds.
        let mut region_map = HashMap::new();
        region_map.insert("eu-west-3".to_string(), "FR".to_string());
        let raw = ElectricityMapsSection {
            api_key: Some("file-token".to_string()),
            endpoint: None,
            poll_interval_secs: Some(600),
            region_map,
        };
        let cfg = convert_electricity_maps_section_with_env(&raw, || None).expect("should convert");
        assert_eq!(cfg.auth_token, "file-token");
        assert_eq!(cfg.poll_interval, Duration::from_mins(10));
        // default endpoint fallback
        assert_eq!(cfg.api_endpoint, "https://api.electricitymaps.com/v3");
        // region key was lowercased (it was already lowercase, so idempotent)
        assert!(cfg.region_map.contains_key("eu-west-3"));
    }

    #[test]
    fn electricity_maps_region_map_keys_lowercased() {
        let mut region_map = HashMap::new();
        region_map.insert("EU-WEST-3".to_string(), "FR".to_string());
        region_map.insert("Us-East-1".to_string(), "US-MIDA-PJM".to_string());
        let raw = ElectricityMapsSection {
            api_key: Some("tok".to_string()),
            endpoint: Some("https://custom.api/v3".to_string()),
            poll_interval_secs: Some(120),
            region_map,
        };
        let cfg = convert_electricity_maps_section_with_env(&raw, || None).expect("should convert");
        assert!(cfg.region_map.contains_key("eu-west-3"));
        assert!(cfg.region_map.contains_key("us-east-1"));
        assert_eq!(cfg.api_endpoint, "https://custom.api/v3");
    }

    #[test]
    fn electricity_maps_env_var_takes_precedence_over_config_file() {
        // Env-lookup returns a token → it wins over `api_key` in the file.
        // Covers the from_env branch of convert_electricity_maps_section_with_env
        // without touching the real process environment.
        let mut region_map = HashMap::new();
        region_map.insert("eu-west-3".to_string(), "FR".to_string());
        let raw = ElectricityMapsSection {
            api_key: Some("from-file".to_string()),
            endpoint: None,
            poll_interval_secs: None,
            region_map,
        };
        let cfg = convert_electricity_maps_section_with_env(&raw, || Some("from-env".to_string()))
            .expect("env-supplied token should produce a valid config");
        assert_eq!(cfg.auth_token, "from-env");
    }

    // --- validate_electricity_maps error paths ---

    #[test]
    fn validate_electricity_maps_rejects_control_char_in_token() {
        let cfg = ElectricityMapsConfig {
            api_endpoint: "https://api.electricitymaps.com/v3".to_string(),
            auth_token: "tok\x07en".to_string(), // contains a control char
            poll_interval: Duration::from_mins(5),
            region_map: {
                let mut m = HashMap::new();
                m.insert("eu-west-3".to_string(), "FR".to_string());
                m
            },
        };
        let err = Config::validate_electricity_maps(&cfg).unwrap_err();
        assert!(err.contains("control"));
    }

    #[test]
    fn validate_electricity_maps_rejects_empty_region_map() {
        let cfg = ElectricityMapsConfig {
            api_endpoint: "https://api.electricitymaps.com/v3".to_string(),
            auth_token: "tok".to_string(),
            poll_interval: Duration::from_mins(5),
            region_map: HashMap::new(),
        };
        let err = Config::validate_electricity_maps(&cfg).unwrap_err();
        assert!(err.contains("region_map"));
    }

    #[test]
    fn validate_electricity_maps_rejects_empty_zone() {
        let mut region_map = HashMap::new();
        region_map.insert("eu-west-3".to_string(), String::new());
        let cfg = ElectricityMapsConfig {
            api_endpoint: "https://api.electricitymaps.com/v3".to_string(),
            auth_token: "tok".to_string(),
            poll_interval: Duration::from_mins(5),
            region_map,
        };
        let err = Config::validate_electricity_maps(&cfg).unwrap_err();
        assert!(err.contains("empty"));
    }

    #[test]
    fn validate_electricity_maps_rejects_invalid_poll_interval() {
        let mut region_map = HashMap::new();
        region_map.insert("eu-west-3".to_string(), "FR".to_string());
        let cfg = ElectricityMapsConfig {
            api_endpoint: "https://api.electricitymaps.com/v3".to_string(),
            auth_token: "tok".to_string(),
            poll_interval: Duration::from_secs(10), // below 60
            region_map,
        };
        let err = Config::validate_electricity_maps(&cfg).unwrap_err();
        assert!(err.contains("poll_interval"));
    }

    // ---------------------------------------------------------------
    // TLS validation
    // ---------------------------------------------------------------

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_accepts_both_absent() {
        let cfg = Config::default();
        assert!(cfg.validate_tls().is_ok());
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_rejects_cert_without_key() {
        let mut cfg = Config::default();
        cfg.tls_cert_path = Some("/tmp/cert.pem".to_string());
        let err = cfg.validate_tls().unwrap_err();
        assert!(err.contains("tls_key_path is missing"), "{err}");
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_rejects_key_without_cert() {
        let mut cfg = Config::default();
        cfg.tls_key_path = Some("/tmp/key.pem".to_string());
        let err = cfg.validate_tls().unwrap_err();
        assert!(err.contains("tls_cert_path is missing"), "{err}");
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_rejects_nonexistent_cert() {
        let mut cfg = Config::default();
        cfg.tls_cert_path = Some("/nonexistent/cert.pem".to_string());
        cfg.tls_key_path = Some("/nonexistent/key.pem".to_string());
        let err = cfg.validate_tls().unwrap_err();
        assert!(err.contains("does not exist"), "{err}");
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_accepts_existing_files() {
        let dir = tempfile::tempdir().unwrap();
        let cert = dir.path().join("cert.pem");
        let key = dir.path().join("key.pem");
        std::fs::write(&cert, b"fake cert").unwrap();
        std::fs::write(&key, b"fake key").unwrap();

        let mut cfg = Config::default();
        cfg.tls_cert_path = Some(cert.to_str().unwrap().to_string());
        cfg.tls_key_path = Some(key.to_str().unwrap().to_string());
        assert!(cfg.validate_tls().is_ok());
    }

    #[test]
    fn tls_config_fields_round_trip_through_toml() {
        let dir = tempfile::tempdir().unwrap();
        let cert = dir.path().join("cert.pem");
        let key = dir.path().join("key.pem");
        std::fs::write(&cert, b"fake cert").unwrap();
        std::fs::write(&key, b"fake key").unwrap();
        let toml = format!(
            "[daemon]\ntls_cert_path = \"{}\"\ntls_key_path = \"{}\"",
            cert.display(),
            key.display()
        );
        let cfg = load_from_str(&toml).unwrap();
        assert_eq!(cfg.tls_cert_path.as_deref(), Some(cert.to_str().unwrap()));
        assert_eq!(cfg.tls_key_path.as_deref(), Some(key.to_str().unwrap()));
    }

    #[test]
    fn tls_config_defaults_to_none() {
        let cfg = load_from_str("").unwrap();
        assert!(cfg.tls_cert_path.is_none());
        assert!(cfg.tls_key_path.is_none());
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_rejects_control_chars_in_cert_path() {
        let mut cfg = Config::default();
        cfg.tls_cert_path = Some("/tmp/cert\x00.pem".to_string());
        cfg.tls_key_path = Some("/tmp/key.pem".to_string());
        let err = cfg.validate_tls().unwrap_err();
        assert!(err.contains("control characters"), "{err}");
    }

    #[test]
    #[allow(clippy::field_reassign_with_default)]
    fn validate_tls_rejects_control_chars_in_key_path() {
        let mut cfg = Config::default();
        cfg.tls_cert_path = Some("/tmp/cert.pem".to_string());
        cfg.tls_key_path = Some("/tmp/key\n.pem".to_string());
        let err = cfg.validate_tls().unwrap_err();
        assert!(err.contains("control characters"), "{err}");
    }
}