KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
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
use crate::SimpleReactorsBVP::solver_backend::{
    ReactorBvpAotBuildPolicy, ReactorBvpAotBuildProfile, ReactorBvpAotCompiler,
    ReactorBvpAotConfig, ReactorBvpAotExecutionPolicy, ReactorBvpExecutionBackend,
    ReactorBvpMatrixBackend, ReactorBvpSolverConfig, ReactorBvpSymbolicBackend,
};
use crate::SimpleReactorsBVP::task_value_conversion::try_value_as_usize;
use RustedSciThe::command_interpreter::task_parser::{DocumentMap, Value};
use log::info;
use std::collections::HashMap;

/// Migration notes produced while folding a raw document into the typed GUI model.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct BvpGuiMigrationReport {
    pub warnings: Vec<String>,
}

impl BvpGuiMigrationReport {
    fn push_warning(&mut self, message: impl Into<String>) {
        self.warnings.push(message.into());
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpScheme {
    #[default]
    Forward,
    Trapezoid,
}

impl BvpScheme {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "forward" => Some(Self::Forward),
            "trapezoid" => Some(Self::Trapezoid),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Forward => "forward",
            Self::Trapezoid => "trapezoid",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpStrategy {
    #[default]
    Damped,
    Frozen,
    Naive,
}

impl BvpStrategy {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "damped" => Some(Self::Damped),
            "frozen" => Some(Self::Frozen),
            "naive" => Some(Self::Naive),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Damped => "Damped",
            Self::Frozen => "Frozen",
            Self::Naive => "Naive",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpSolverFamily {
    #[default]
    Damped,
    Frozen,
    Sci,
    CorrectionNewton,
}

impl BvpSolverFamily {
    pub(crate) fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "damped" | "bvp_damp" => Some(Self::Damped),
            "frozen" => Some(Self::Frozen),
            "sci" | "bvp_sci" => Some(Self::Sci),
            "correction_newton" | "bvp_correction_newton" | "correctionnewton" => {
                Some(Self::CorrectionNewton)
            }
            _ => None,
        }
    }

    pub(crate) fn as_document_value(self) -> &'static str {
        match self {
            Self::Damped => "damped",
            Self::Frozen => "frozen",
            Self::Sci => "sci",
            Self::CorrectionNewton => "correction_newton",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpCorrectionNewtonAssembly {
    #[default]
    ExprLegacy,
    AtomView,
}

impl BvpCorrectionNewtonAssembly {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "expr" | "exprlegacy" | "expr_legacy" | "legacy" => Some(Self::ExprLegacy),
            "atom" | "atomview" | "atom_view" | "atomviewnative" | "atom_view_native" => {
                Some(Self::AtomView)
            }
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::ExprLegacy => "expr_legacy",
            Self::AtomView => "atom_view_native",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpCorrectionNewtonExecution {
    #[default]
    Lambdify,
    Aot,
}

impl BvpCorrectionNewtonExecution {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "lambdify" => Some(Self::Lambdify),
            "aot" => Some(Self::Aot),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Lambdify => "lambdify",
            Self::Aot => "aot",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpCorrectionNewtonLayout {
    Dense,
    #[default]
    Sparse,
    BandedAuto,
}

impl BvpCorrectionNewtonLayout {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "dense" => Some(Self::Dense),
            "sparse" => Some(Self::Sparse),
            "banded" | "banded_auto" | "bandedauto" => Some(Self::BandedAuto),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Dense => "dense",
            Self::Sparse => "sparse",
            Self::BandedAuto => "banded_auto",
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpCorrectionNewtonConfig {
    pub assembly: BvpCorrectionNewtonAssembly,
    pub execution: BvpCorrectionNewtonExecution,
    pub matrix_layout: BvpCorrectionNewtonLayout,
    pub absolute_tolerance: f64,
    pub default_relative_tolerance: f64,
    pub max_iterations: usize,
    pub max_jacobian_age: usize,
    pub max_damping_trials: usize,
}

impl Default for BvpCorrectionNewtonConfig {
    fn default() -> Self {
        Self {
            assembly: BvpCorrectionNewtonAssembly::ExprLegacy,
            execution: BvpCorrectionNewtonExecution::Lambdify,
            matrix_layout: BvpCorrectionNewtonLayout::Sparse,
            absolute_tolerance: 1e-5,
            default_relative_tolerance: 1e-5,
            max_iterations: 100,
            max_jacobian_age: 5,
            max_damping_trials: 7,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpTelemetryMode {
    #[default]
    Off,
    Counters,
    Timings,
    Detailed,
}

impl BvpTelemetryMode {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "off" => Some(Self::Off),
            "counters" => Some(Self::Counters),
            "timings" => Some(Self::Timings),
            "detailed" => Some(Self::Detailed),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Counters => "counters",
            Self::Timings => "timings",
            Self::Detailed => "detailed",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpBandedLinearSolver {
    #[default]
    Auto,
    Faithful,
    BlockTridiagonal,
    BlockTridiagonalConsistent,
    FaerSparse,
    GeneralPartialPivot,
}

impl BvpBandedLinearSolver {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "auto" => Some(Self::Auto),
            "faithful" => Some(Self::Faithful),
            "block_tridiagonal" => Some(Self::BlockTridiagonal),
            "block_tridiagonal_consistent" => Some(Self::BlockTridiagonalConsistent),
            "faer_sparse" => Some(Self::FaerSparse),
            "general_partial_pivot" => Some(Self::GeneralPartialPivot),
            _ => None,
        }
    }

    fn as_document_value(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Faithful => "faithful",
            Self::BlockTridiagonal => "block_tridiagonal",
            Self::BlockTridiagonalConsistent => "block_tridiagonal_consistent",
            Self::FaerSparse => "faer_sparse",
            Self::GeneralPartialPivot => "general_partial_pivot",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpGridRefinementMethod {
    #[default]
    Pearson,
    GrcarSmooke,
    Twopnt,
    Easy,
    DoublePoints,
}

impl BvpGridRefinementMethod {
    fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "pearson" => Some(Self::Pearson),
            "grcar_smooke" | "grcarsmooke" => Some(Self::GrcarSmooke),
            "twopnt" => Some(Self::Twopnt),
            "easy" => Some(Self::Easy),
            "double_points" | "doublepoints" => Some(Self::DoublePoints),
            _ => None,
        }
    }

    fn as_document_key(self) -> &'static str {
        match self {
            Self::Pearson => "pearson",
            Self::GrcarSmooke => "grcarsmooke",
            Self::Twopnt => "twopnt",
            Self::Easy => "easy",
            Self::DoublePoints => "doubleoints",
        }
    }

    fn default_params(self) -> Vec<f64> {
        match self {
            Self::Pearson => vec![0.05, 2.5],
            Self::GrcarSmooke => vec![0.05, 0.05, 1.25],
            Self::Twopnt => vec![0.05, 0.05, 1.25],
            Self::Easy => vec![0.05],
            Self::DoublePoints => Vec::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpGridRefinementConfig {
    pub method: BvpGridRefinementMethod,
    pub params: Vec<f64>,
}

impl Default for BvpGridRefinementConfig {
    fn default() -> Self {
        let method = BvpGridRefinementMethod::default();
        Self {
            params: method.default_params(),
            method,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpAdaptiveGridConfig {
    pub enabled: bool,
    pub version: usize,
    pub max_refinements: usize,
    pub grid_refinement: BvpGridRefinementConfig,
}

impl Default for BvpAdaptiveGridConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            version: 1,
            max_refinements: 3,
            grid_refinement: BvpGridRefinementConfig::default(),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BvpInitialGuessMode {
    #[default]
    Universal,
    PerVariable,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpInitialGuessConfig {
    pub mode: BvpInitialGuessMode,
    pub universal: f64,
    pub c: f64,
    pub j: f64,
    pub teta: f64,
    pub q: f64,
}

impl Default for BvpInitialGuessConfig {
    fn default() -> Self {
        Self {
            mode: BvpInitialGuessMode::Universal,
            universal: 1e-2,
            c: 1e-2,
            j: 1e-2,
            teta: 1e-2,
            q: 1e-2,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpRelativeToleranceConfig {
    pub c: f64,
    pub j: f64,
    pub teta: f64,
    pub q: f64,
}

impl Default for BvpRelativeToleranceConfig {
    fn default() -> Self {
        Self {
            c: 1e-7,
            j: 1e-7,
            teta: 1e-7,
            q: 1e-7,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpStrategyParamsConfig {
    pub max_jac: Option<usize>,
    pub max_damp_iter: Option<usize>,
    pub damp_factor: Option<f64>,
}

impl Default for BvpStrategyParamsConfig {
    fn default() -> Self {
        Self {
            max_jac: Some(3),
            max_damp_iter: Some(10),
            damp_factor: Some(0.5),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpAdvancedSolverConfig {
    pub rel_tolerance: BvpRelativeToleranceConfig,
    pub strategy_params: BvpStrategyParamsConfig,
}

impl Default for BvpAdvancedSolverConfig {
    fn default() -> Self {
        Self {
            rel_tolerance: BvpRelativeToleranceConfig::default(),
            strategy_params: BvpStrategyParamsConfig::default(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpCoreSolverConfig {
    pub family: BvpSolverFamily,
    pub scheme: BvpScheme,
    pub strategy: BvpStrategy,
    pub telemetry: BvpTelemetryMode,
    pub linear_sys_method: Option<String>,
    pub abs_tolerance: f64,
    pub max_iterations: usize,
    pub loglevel: Option<String>,
    pub banded_linear_solver: BvpBandedLinearSolver,
    pub refinement_steps: usize,
}

impl Default for BvpCoreSolverConfig {
    fn default() -> Self {
        Self {
            family: BvpSolverFamily::Damped,
            scheme: BvpScheme::Forward,
            strategy: BvpStrategy::Damped,
            telemetry: BvpTelemetryMode::Off,
            linear_sys_method: None,
            abs_tolerance: 1e-7,
            max_iterations: 100,
            loglevel: Some("off".to_string()),
            banded_linear_solver: BvpBandedLinearSolver::Auto,
            refinement_steps: 5,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpPostprocessingConfig {
    pub plot: bool,
    pub gnuplot: bool,
    pub save_to_csv: bool,
    pub filename: String,
    pub save: bool,
    pub return_to_dimension: bool,
    pub no_plots_in_terminal: bool,
    pub gui_plot: bool,
}

impl Default for BvpPostprocessingConfig {
    fn default() -> Self {
        Self {
            plot: true,
            gnuplot: false,
            save_to_csv: false,
            filename: String::new(),
            save: false,
            return_to_dimension: false,
            no_plots_in_terminal: true,
            gui_plot: true,
        }
    }
}

/// Typed snapshot of the BVP GUI structured state.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BvpGuiConfig {
    pub core: BvpCoreSolverConfig,
    pub backend: ReactorBvpSolverConfig,
    pub correction_newton: BvpCorrectionNewtonConfig,
    pub advanced_solver: BvpAdvancedSolverConfig,
    pub initial_guess: BvpInitialGuessConfig,
    pub adaptive_grid: BvpAdaptiveGridConfig,
    pub postprocessing: BvpPostprocessingConfig,
}

impl Default for BvpGuiConfig {
    fn default() -> Self {
        Self {
            core: BvpCoreSolverConfig::default(),
            backend: ReactorBvpSolverConfig::default_lambdify(),
            correction_newton: BvpCorrectionNewtonConfig::default(),
            advanced_solver: BvpAdvancedSolverConfig::default(),
            initial_guess: BvpInitialGuessConfig::default(),
            adaptive_grid: BvpAdaptiveGridConfig::default(),
            postprocessing: BvpPostprocessingConfig::default(),
        }
    }
}

impl BvpGuiConfig {
    /// Fold a raw task document into the structured GUI model.
    pub(crate) fn from_document(document: &DocumentMap) -> (Self, BvpGuiMigrationReport) {
        let mut report = BvpGuiMigrationReport::default();
        let solver_section = document.get("solver_settings");
        let postprocessing = document.get("postprocessing");
        let adaptive_strategy = document.get("adaptive_strategy");
        let grid_refinement = document.get("grid_refinement");

        let mut config = Self::default();
        if let Some(section) = solver_section {
            config.core = parse_core_solver_config(section, &mut report);
            config.backend = parse_backend_config(section, &mut report);
            config.correction_newton = parse_correction_newton_config(section, &mut report);
        }
        config.advanced_solver = parse_advanced_solver_config(
            document.get("rel_tolerance"),
            document.get("strategy_params"),
            &mut report,
        );
        config.initial_guess =
            parse_initial_guess_config(document.get("initial_guess"), &mut report);
        config.postprocessing =
            parse_postprocessing_config(postprocessing, solver_section, &mut report);
        config.adaptive_grid =
            parse_adaptive_grid_config(document, adaptive_strategy, grid_refinement, &mut report);

        (config, report)
    }

    /// Write the typed GUI model back into the raw task document.
    pub(crate) fn apply_to_document(&self, document: &mut DocumentMap) {
        {
            let solver_section = ensure_section_mut(document, "solver_settings");
            self.core.apply_to_section(solver_section);
            if matches!(
                self.core.family,
                BvpSolverFamily::Damped | BvpSolverFamily::Frozen
            ) {
                self.backend.apply_to_section(solver_section);
            }
            if self.core.family == BvpSolverFamily::CorrectionNewton {
                self.correction_newton.apply_to_section(solver_section);
            }
            for field_name in BVP_POSTPROCESSING_FIELD_NAMES {
                solver_section.remove(*field_name);
            }
        }

        match self.core.family {
            BvpSolverFamily::Damped => self.advanced_solver.apply_to_document(document),
            BvpSolverFamily::Frozen => {
                document.remove("bounds");
                document.remove("rel_tolerance");
                document.remove("adaptive_strategy");
                document.remove("grid_refinement");
            }
            BvpSolverFamily::Sci => {
                document.remove("bounds");
                document.remove("rel_tolerance");
                document.remove("strategy_params");
                document.remove("adaptive_strategy");
                document.remove("grid_refinement");
            }
            BvpSolverFamily::CorrectionNewton => {
                document.remove("strategy_params");
                document.remove("adaptive_strategy");
                document.remove("grid_refinement");
                let relative = ensure_section_mut(document, "rel_tolerance");
                self.advanced_solver
                    .rel_tolerance
                    .apply_to_section(relative);
            }
        }
        self.initial_guess.apply_to_document(document);

        let postprocessing_section = ensure_section_mut(document, "postprocessing");
        self.postprocessing.apply_to_section(postprocessing_section);
        self.adaptive_grid.apply_to_document(document);
        normalize_bvp_solver_family_document(document, self.core.family, false);
    }
}

pub(crate) fn set_bvp_solver_family(document: &mut DocumentMap, family: BvpSolverFamily) {
    normalize_bvp_solver_family_document(document, family, true);
}

fn normalize_bvp_solver_family_document(
    document: &mut DocumentMap,
    family: BvpSolverFamily,
    reset_family_defaults: bool,
) {
    set_string_field(
        ensure_section_mut(document, "solver_settings"),
        "solver_family",
        family.as_document_value(),
    );

    let damped_only = [
        "abs_tolerance",
        "banded_linear_solver",
        "refinement_steps",
        "aot_compile_preset",
        "aot_execution_policy",
        "aot_residual_target_chunks",
        "aot_jacobian_target_chunks",
        "lambdify_execution_policy",
        "lambdify_min_work",
        "bvp_logging_mode",
        "bvp_logging_max_events",
        "expr_indexed_lambdify",
        "expr_dependency_columns",
    ];
    let sci_only = [
        "execution",
        "assembly",
        "matrix_layout",
        "banded_lower",
        "banded_upper",
        "boundary_tolerance",
        "max_nodes",
        "max_newton_iterations",
        "max_jacobian_refreshes",
        "max_mesh_refinements",
        "max_backtracking_steps",
        "execution_policy",
        "execution_min_work",
        "output_policy",
        "sparse_factorization",
        "aot_output_dir",
        "aot_handoff_path",
        "aot_crate_name",
        "aot_module_name",
        "aot_residual_chunking",
        "aot_residual_chunk_size",
        "aot_sparse_jacobian_chunking",
        "aot_sparse_jacobian_chunk_size",
        "aot_banded_jacobian_chunking",
        "aot_banded_jacobian_chunk_size",
    ];
    let damped_backend = [
        "generated_backend",
        "backend_policy",
        "matrix_backend",
        "method",
        "symbolic_backend",
        "banded_linear_solver",
        "refinement_steps",
        "aot_compile_preset",
        "aot_execution_policy",
        "aot_residual_target_chunks",
        "aot_jacobian_target_chunks",
    ];
    let correction_newton_numeric = [
        "absolute_tolerance",
        "default_relative_tolerance",
        "max_jacobian_age",
        "max_damping_trials",
    ];

    match family {
        BvpSolverFamily::Damped => {
            {
                let section = ensure_section_mut(document, "solver_settings");
                for field in sci_only {
                    section.remove(field);
                }
                section.remove("tolerance");
                for field in ["assembly", "execution", "matrix_layout"]
                    .into_iter()
                    .chain(correction_newton_numeric)
                {
                    section.remove(field);
                }
            }
            if reset_family_defaults {
                document.remove("adaptive_strategy");
                document.remove("grid_refinement");
                let section = ensure_section_mut(document, "solver_settings");
                set_string_field(section, "strategy", "Damped");
                set_float_field(section, "abs_tolerance", 1e-7);
                set_usize_field(section, "max_iterations", 100);
                set_string_field(section, "banded_linear_solver", "auto");
                set_usize_field(section, "refinement_steps", 5);
                set_bounds_and_relative_tolerances(document);
                BvpAdvancedSolverConfig::default().apply_to_document(document);
                BvpAdaptiveGridConfig::default().apply_to_document(document);
            }
        }
        BvpSolverFamily::Frozen => {
            document.remove("bounds");
            document.remove("rel_tolerance");
            document.remove("adaptive_strategy");
            document.remove("grid_refinement");
            {
                let section = ensure_section_mut(document, "solver_settings");
                for field in sci_only {
                    section.remove(field);
                }
                for field in ["abs_tolerance", "banded_linear_solver", "refinement_steps"] {
                    section.remove(field);
                }
                for field in ["assembly", "execution", "matrix_layout"]
                    .into_iter()
                    .chain(correction_newton_numeric)
                {
                    section.remove(field);
                }
                if reset_family_defaults {
                    set_string_field(section, "strategy", "Frozen");
                    set_float_field(section, "tolerance", 1e-6);
                    set_usize_field(section, "max_iterations", 50);
                } else if !section.contains_key("tolerance") {
                    set_float_field(section, "tolerance", 1e-6);
                }
            }
        }
        BvpSolverFamily::Sci => {
            document.remove("bounds");
            document.remove("rel_tolerance");
            document.remove("strategy_params");
            document.remove("adaptive_strategy");
            document.remove("grid_refinement");
            {
                let section = ensure_section_mut(document, "solver_settings");
                for field in damped_only {
                    section.remove(field);
                }
                for field in damped_backend {
                    section.remove(field);
                }
                for field in correction_newton_numeric {
                    section.remove(field);
                }
                for field in ["scheme", "strategy", "linear_sys_method", "max_iterations"] {
                    section.remove(field);
                }
                if reset_family_defaults {
                    set_string_field(section, "execution", "lambdify");
                    set_string_field(section, "assembly", "atom_view_native");
                    set_string_field(section, "matrix_layout", "banded_auto");
                    set_float_field(section, "tolerance", 1e-4);
                    set_usize_field(section, "max_nodes", 256);
                }
            }
        }
        BvpSolverFamily::CorrectionNewton => {
            document.remove("adaptive_strategy");
            document.remove("grid_refinement");
            document.remove("strategy_params");
            {
                let section = ensure_section_mut(document, "solver_settings");
                for field in [
                    "scheme",
                    "strategy",
                    "linear_sys_method",
                    "abs_tolerance",
                    "tolerance",
                    "banded_linear_solver",
                    "refinement_steps",
                    "generated_backend",
                    "backend_policy",
                    "matrix_backend",
                    "method",
                    "symbolic_backend",
                    "lambdify_execution_policy",
                    "lambdify_min_work",
                    "bvp_logging_mode",
                    "bvp_logging_max_events",
                    "expr_indexed_lambdify",
                    "expr_dependency_columns",
                    "banded_lower",
                    "banded_upper",
                    "boundary_tolerance",
                    "max_nodes",
                    "max_newton_iterations",
                    "max_jacobian_refreshes",
                    "max_mesh_refinements",
                    "max_backtracking_steps",
                    "execution_policy",
                    "execution_min_work",
                    "output_policy",
                    "sparse_factorization",
                ] {
                    section.remove(field);
                }
                if reset_family_defaults {
                    for field in [
                        "aot_codegen_backend",
                        "aot_c_compiler",
                        "aot_build_policy",
                        "aot_build_profile",
                        "aot_output_dir",
                        "aot_handoff_path",
                        "aot_crate_name",
                        "aot_module_name",
                        "aot_residual_chunking",
                        "aot_residual_chunk_size",
                        "aot_sparse_jacobian_chunking",
                        "aot_sparse_jacobian_chunk_size",
                        "aot_banded_jacobian_chunking",
                        "aot_banded_jacobian_chunk_size",
                    ] {
                        section.remove(field);
                    }
                    BvpCorrectionNewtonConfig::default().apply_to_section(section);
                }
            }
            if reset_family_defaults {
                set_bounds_and_relative_tolerances(document);
            }
        }
    }
}

fn set_bounds_and_relative_tolerances(document: &mut DocumentMap) {
    let bounds = ensure_section_mut(document, "bounds");
    for (name, lower, upper) in [
        ("C", -10.0, 10.0),
        ("J", -1e20, 1e20),
        ("Teta", -100.0, 100.0),
        ("q", -1e20, 1e20),
    ] {
        bounds.insert(
            name.into(),
            Some(vec![Value::Float(lower), Value::Float(upper)]),
        );
    }
    let relative = ensure_section_mut(document, "rel_tolerance");
    for name in ["C", "J", "Teta", "q"] {
        set_float_field(relative, name, 1e-7);
    }
}

const BVP_POSTPROCESSING_FIELD_NAMES: &[&str] = &[
    "plot",
    "gnuplot",
    "save_to_csv",
    "filename",
    "save",
    "return_to_dimension",
    "no_plots_in_terminal",
    "gui_plot",
];

impl ReactorBvpSolverConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_string_field(section, "generated_backend", &generated_backend_name(self));
        set_string_field(
            section,
            "matrix_backend",
            match self.matrix_backend {
                ReactorBvpMatrixBackend::Banded => "Banded",
                ReactorBvpMatrixBackend::Sparse => "Sparse",
            },
        );
        set_string_field(
            section,
            "method",
            match self.matrix_backend {
                ReactorBvpMatrixBackend::Banded => "Banded",
                ReactorBvpMatrixBackend::Sparse => "Sparse",
            },
        );
        set_string_field(
            section,
            "symbolic_backend",
            match self.symbolic_backend {
                ReactorBvpSymbolicBackend::AtomView => "AtomView",
                ReactorBvpSymbolicBackend::ExprLegacy => "ExprLegacy",
            },
        );

        match self.execution_backend {
            ReactorBvpExecutionBackend::Lambdify => {
                set_string_field(section, "backend_policy", "lambdify_only");
                section.remove("aot_c_compiler");
                section.remove("aot_build_policy");
                section.remove("aot_build_profile");
                section.remove("aot_compile_preset");
                section.remove("aot_execution_policy");
                section.remove("aot_residual_target_chunks");
                section.remove("aot_jacobian_target_chunks");
            }
            ReactorBvpExecutionBackend::Aot(aot) => {
                set_string_field(section, "backend_policy", "aot_only");
                set_string_field(
                    section,
                    "aot_c_compiler",
                    match aot.compiler {
                        ReactorBvpAotCompiler::CTcc => "tcc",
                        ReactorBvpAotCompiler::CGcc => "gcc",
                        ReactorBvpAotCompiler::Zig => "zig",
                    },
                );
                set_string_field(
                    section,
                    "aot_build_policy",
                    match aot.build_policy {
                        ReactorBvpAotBuildPolicy::UseIfAvailable => "use_if_available",
                        ReactorBvpAotBuildPolicy::BuildIfMissing => "build_if_missing",
                        ReactorBvpAotBuildPolicy::RequirePrebuilt => "require_prebuilt",
                        ReactorBvpAotBuildPolicy::RebuildAlways => "rebuild_always",
                    },
                );
                set_string_field(
                    section,
                    "aot_build_profile",
                    match aot.build_profile {
                        ReactorBvpAotBuildProfile::Release => "release",
                        ReactorBvpAotBuildProfile::Debug => "debug",
                    },
                );
                set_string_field(
                    section,
                    "aot_compile_preset",
                    match aot.compile_preset {
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::Production =>
                            "production",
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::FastBuild =>
                            "fast_build",
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::DevFastest =>
                            "dev_fastest",
                    },
                );
                set_string_field(
                    section,
                    "aot_execution_policy",
                    match aot.execution_policy {
                        ReactorBvpAotExecutionPolicy::Auto => "auto",
                        ReactorBvpAotExecutionPolicy::Sequential => "sequential",
                        ReactorBvpAotExecutionPolicy::Parallel => "parallel",
                    },
                );
                if let Some(chunks) = aot.residual_target_chunks {
                    set_usize_field(section, "aot_residual_target_chunks", chunks);
                } else {
                    section.remove("aot_residual_target_chunks");
                }
                if let Some(chunks) = aot.jacobian_target_chunks {
                    set_usize_field(section, "aot_jacobian_target_chunks", chunks);
                } else {
                    section.remove("aot_jacobian_target_chunks");
                }
            }
        }
    }
}

impl BvpCoreSolverConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_string_field(section, "solver_family", self.family.as_document_value());
        set_string_field(section, "telemetry", self.telemetry.as_document_value());
        set_optional_string_field(section, "loglevel", self.loglevel.as_deref());
        match self.family {
            BvpSolverFamily::Damped => {
                set_string_field(section, "scheme", self.scheme.as_document_value());
                set_string_field(section, "strategy", "Damped");
                set_optional_string_field(
                    section,
                    "linear_sys_method",
                    self.linear_sys_method.as_deref(),
                );
                set_float_field(section, "abs_tolerance", self.abs_tolerance);
                set_usize_field(section, "max_iterations", self.max_iterations);
                set_string_field(
                    section,
                    "banded_linear_solver",
                    self.banded_linear_solver.as_document_value(),
                );
                set_usize_field(section, "refinement_steps", self.refinement_steps);
                section.remove("tolerance");
            }
            BvpSolverFamily::Frozen => {
                set_string_field(section, "scheme", self.scheme.as_document_value());
                set_string_field(section, "strategy", self.strategy.as_document_value());
                set_optional_string_field(
                    section,
                    "linear_sys_method",
                    self.linear_sys_method.as_deref(),
                );
                set_float_field(section, "tolerance", self.abs_tolerance);
                set_usize_field(section, "max_iterations", self.max_iterations);
                section.remove("abs_tolerance");
                section.remove("banded_linear_solver");
                section.remove("refinement_steps");
            }
            BvpSolverFamily::Sci => {
                section.remove("scheme");
                section.remove("strategy");
                section.remove("linear_sys_method");
                section.remove("abs_tolerance");
                section.remove("max_iterations");
                section.remove("banded_linear_solver");
                section.remove("refinement_steps");
            }
            BvpSolverFamily::CorrectionNewton => {
                for field in [
                    "scheme",
                    "strategy",
                    "linear_sys_method",
                    "abs_tolerance",
                    "tolerance",
                    "banded_linear_solver",
                    "refinement_steps",
                ] {
                    section.remove(field);
                }
            }
        }
    }
}

impl BvpCorrectionNewtonConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_string_field(section, "assembly", self.assembly.as_document_value());
        set_string_field(section, "execution", self.execution.as_document_value());
        set_string_field(
            section,
            "matrix_layout",
            self.matrix_layout.as_document_value(),
        );
        set_float_field(section, "absolute_tolerance", self.absolute_tolerance);
        set_float_field(
            section,
            "default_relative_tolerance",
            self.default_relative_tolerance,
        );
        set_usize_field(section, "max_iterations", self.max_iterations);
        set_usize_field(section, "max_jacobian_age", self.max_jacobian_age);
        set_usize_field(section, "max_damping_trials", self.max_damping_trials);
    }
}

impl BvpPostprocessingConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_bool_field(section, "plot", self.plot);
        set_bool_field(section, "gnuplot", self.gnuplot);
        set_bool_field(section, "save_to_csv", self.save_to_csv);
        set_string_field(section, "filename", &self.filename);
        set_bool_field(section, "save", self.save);
        set_bool_field(section, "return_to_dimension", self.return_to_dimension);
        set_bool_field(section, "no_plots_in_terminal", self.no_plots_in_terminal);
        set_bool_field(section, "gui_plot", self.gui_plot);
    }
}

impl BvpRelativeToleranceConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_float_field(section, "C", self.c);
        set_float_field(section, "J", self.j);
        set_float_field(section, "Teta", self.teta);
        set_float_field(section, "q", self.q);
    }
}

impl BvpStrategyParamsConfig {
    fn apply_to_section(&self, section: &mut HashMap<String, Option<Vec<Value>>>) {
        set_optional_usize_field(section, "max_jac", self.max_jac);
        set_optional_usize_field(section, "max_damp_iter", self.max_damp_iter);
        set_optional_float_field(section, "damp_factor", self.damp_factor);
    }
}

impl BvpAdvancedSolverConfig {
    fn apply_to_document(&self, document: &mut DocumentMap) {
        let rel_tolerance = ensure_section_mut(document, "rel_tolerance");
        self.rel_tolerance.apply_to_section(rel_tolerance);

        let strategy_params = ensure_section_mut(document, "strategy_params");
        self.strategy_params.apply_to_section(strategy_params);
    }
}

impl BvpInitialGuessConfig {
    fn apply_to_document(&self, document: &mut DocumentMap) {
        let section = ensure_section_mut(document, "initial_guess");
        match self.mode {
            BvpInitialGuessMode::Universal => {
                set_float_field(section, "universal", self.universal);
                section.remove("C");
                section.remove("J");
                section.remove("Teta");
                section.remove("q");
            }
            BvpInitialGuessMode::PerVariable => {
                section.remove("universal");
                set_float_field(section, "C", self.c);
                set_float_field(section, "J", self.j);
                set_float_field(section, "Teta", self.teta);
                set_float_field(section, "q", self.q);
            }
        }
    }
}

impl BvpAdaptiveGridConfig {
    fn apply_to_document(&self, document: &mut DocumentMap) {
        if let Some(strategy_params) = document.get_mut("strategy_params") {
            strategy_params.remove("adaptive");
        }

        if !self.enabled {
            document.remove("adaptive_strategy");
            document.remove("grid_refinement");
            return;
        }

        let adaptive_strategy = ensure_section_mut(document, "adaptive_strategy");
        adaptive_strategy.insert(
            "version".to_string(),
            Some(vec![Value::Usize(self.version)]),
        );
        set_usize_field(adaptive_strategy, "max_refinements", self.max_refinements);

        let grid_refinement = ensure_section_mut(document, "grid_refinement");
        grid_refinement.clear();
        grid_refinement.insert(
            self.grid_refinement.method.as_document_key().to_string(),
            Some(vec![Value::Vector(self.grid_refinement.params.clone())]),
        );
    }
}

fn parse_core_solver_config(
    section: &HashMap<String, Option<Vec<Value>>>,
    report: &mut BvpGuiMigrationReport,
) -> BvpCoreSolverConfig {
    let mut core = BvpCoreSolverConfig::default();
    let legacy_strategy = string_field(section, "strategy");
    if let Some(raw_family) = string_field(section, "solver_family") {
        if let Some(family) = BvpSolverFamily::parse(&raw_family) {
            core.family = family;
        } else {
            report.push_warning(format!(
                "Unknown solver family `{raw_family}`. Falling back to `damped`."
            ));
        }
    } else if legacy_strategy
        .as_deref()
        .is_some_and(|strategy| matches!(normalize_key(strategy).as_str(), "frozen" | "naive"))
    {
        core.family = BvpSolverFamily::Frozen;
    }
    if core.family == BvpSolverFamily::Frozen && legacy_strategy.is_none() {
        core.strategy = BvpStrategy::Frozen;
    }
    if let Some(scheme) = string_field(section, "scheme") {
        if let Some(parsed) = BvpScheme::parse(&scheme) {
            core.scheme = parsed;
        } else {
            report.push_warning(format!(
                "Unknown solver scheme `{scheme}`. Falling back to `forward`."
            ));
        }
    }
    if let Some(strategy) = legacy_strategy {
        if let Some(parsed) = BvpStrategy::parse(&strategy) {
            core.strategy = parsed;
        } else {
            report.push_warning(format!(
                "Unknown solver strategy `{strategy}`. Falling back to `Damped`."
            ));
        }
    }
    if let Some(telemetry) = string_field(section, "telemetry") {
        if let Some(parsed) = BvpTelemetryMode::parse(&telemetry) {
            core.telemetry = parsed;
        } else {
            report.push_warning(format!(
                "Unknown solver telemetry mode `{telemetry}`. Falling back to `off`."
            ));
        }
    }
    core.linear_sys_method = optional_string_field(section, "linear_sys_method");
    if let Some(value) = float_field(section, "abs_tolerance") {
        if value.is_finite() {
            core.abs_tolerance = value;
        } else {
            report.push_warning("Non-finite abs_tolerance encountered. Falling back to 1e-7.");
        }
    }
    if let Some(value) = float_field(section, "tolerance") {
        if value.is_finite() {
            core.abs_tolerance = value;
        } else {
            report.push_warning("Non-finite tolerance encountered. Falling back to 1e-6.");
        }
    }
    if let Some(value) = usize_field(section, "max_iterations") {
        core.max_iterations = value;
    }
    core.loglevel = optional_string_field(section, "loglevel");
    if let Some(banded_solver) = string_field(section, "banded_linear_solver") {
        if let Some(parsed) = BvpBandedLinearSolver::parse(&banded_solver) {
            core.banded_linear_solver = parsed;
        } else {
            report.push_warning(format!(
                "Unknown banded linear solver `{banded_solver}`. Falling back to `auto`."
            ));
        }
    }
    if let Some(value) = usize_field(section, "refinement_steps") {
        core.refinement_steps = value;
    }

    core
}

fn parse_correction_newton_config(
    section: &HashMap<String, Option<Vec<Value>>>,
    report: &mut BvpGuiMigrationReport,
) -> BvpCorrectionNewtonConfig {
    let mut config = BvpCorrectionNewtonConfig::default();
    if let Some(value) = string_field(section, "assembly") {
        if let Some(parsed) = BvpCorrectionNewtonAssembly::parse(&value) {
            config.assembly = parsed;
        } else {
            report.push_warning(format!(
                "Unknown CorrectionNewton assembly `{value}`. Falling back to `expr_legacy`."
            ));
        }
    }
    if let Some(value) = string_field(section, "execution") {
        if let Some(parsed) = BvpCorrectionNewtonExecution::parse(&value) {
            config.execution = parsed;
        } else {
            report.push_warning(format!(
                "Unknown CorrectionNewton execution `{value}`. Falling back to `lambdify`."
            ));
        }
    }
    if let Some(value) = string_field(section, "matrix_layout") {
        if let Some(parsed) = BvpCorrectionNewtonLayout::parse(&value) {
            config.matrix_layout = parsed;
        } else {
            report.push_warning(format!(
                "Unknown CorrectionNewton matrix layout `{value}`. Falling back to `sparse`."
            ));
        }
    }
    for (field, target) in [
        ("absolute_tolerance", &mut config.absolute_tolerance),
        (
            "default_relative_tolerance",
            &mut config.default_relative_tolerance,
        ),
    ] {
        if let Some(value) = float_field(section, field) {
            if value.is_finite() && value > 0.0 {
                *target = value;
            } else {
                report.push_warning(format!(
                    "Invalid solver_settings.{field}; falling back to CorrectionNewton default."
                ));
            }
        }
    }
    for (field, target) in [
        ("max_iterations", &mut config.max_iterations),
        ("max_jacobian_age", &mut config.max_jacobian_age),
        ("max_damping_trials", &mut config.max_damping_trials),
    ] {
        if let Some(value) = usize_field(section, field) {
            if value > 0 || field == "max_jacobian_age" {
                *target = value;
            } else {
                report.push_warning(format!(
                    "Invalid solver_settings.{field}; falling back to CorrectionNewton default."
                ));
            }
        }
    }
    config
}

fn parse_backend_config(
    section: &HashMap<String, Option<Vec<Value>>>,
    report: &mut BvpGuiMigrationReport,
) -> ReactorBvpSolverConfig {
    let backend_name = string_field(section, "generated_backend")
        .or_else(|| match string_field(section, "backend_policy") {
            Some(policy) if policy.trim().eq_ignore_ascii_case("aot_only") => {
                Some("banded_aot_tcc".to_string())
            }
            _ => None,
        })
        .unwrap_or_else(|| "banded_lambdify".to_string());

    let mut backend = match ReactorBvpSolverConfig::from_generated_backend_name(&backend_name) {
        Ok(config) => config,
        Err(error) => {
            report.push_warning(error);
            ReactorBvpSolverConfig::default_lambdify()
        }
    };

    if let Some(matrix_backend) =
        string_field(section, "matrix_backend").or_else(|| string_field(section, "method"))
    {
        match ReactorBvpMatrixBackend::parse(&matrix_backend) {
            Ok(parsed) => backend = backend.with_matrix_backend(parsed),
            Err(error) => report.push_warning(error),
        }
    }

    if let Some(symbolic_backend) = string_field(section, "symbolic_backend") {
        match ReactorBvpSymbolicBackend::parse(&symbolic_backend) {
            Ok(parsed) => backend = backend.with_symbolic_backend(parsed),
            Err(error) => report.push_warning(error),
        }
    }

    if matches!(
        backend.execution_backend,
        ReactorBvpExecutionBackend::Aot(_)
    ) {
        let mut aot_config = match backend.execution_backend {
            ReactorBvpExecutionBackend::Aot(config) => config,
            ReactorBvpExecutionBackend::Lambdify => ReactorBvpAotConfig::default(),
        };

        if let Some(compiler) = string_field(section, "aot_c_compiler") {
            match ReactorBvpAotCompiler::parse(&compiler) {
                Ok(parsed) => aot_config.compiler = parsed,
                Err(error) => report.push_warning(error),
            }
        }

        if let Some(build_policy) = string_field(section, "aot_build_policy") {
            match ReactorBvpAotBuildPolicy::parse(&build_policy) {
                Ok(parsed) => aot_config.build_policy = parsed,
                Err(error) => report.push_warning(error),
            }
        }
        if let Some(build_profile) = string_field(section, "aot_build_profile") {
            match ReactorBvpAotBuildProfile::parse(&build_profile) {
                Ok(parsed) => aot_config.build_profile = parsed,
                Err(error) => report.push_warning(error),
            }
        }
        if let Some(compile_preset) = string_field(section, "aot_compile_preset") {
            match normalize_key(&compile_preset).as_str() {
                "production" | "prod" => {
                    aot_config.compile_preset =
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::Production
                }
                "fast_build" | "fastbuild" => {
                    aot_config.compile_preset =
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::FastBuild
                }
                "dev_fastest" | "devfastest" | "fastest" => {
                    aot_config.compile_preset =
                        crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::DevFastest
                }
                other => report.push_warning(format!(
                    "Unknown AOT compile preset `{other}`. Falling back to `dev_fastest`."
                )),
            }
        }
        if let Some(execution_policy) = string_field(section, "aot_execution_policy") {
            match ReactorBvpAotExecutionPolicy::parse(&execution_policy) {
                Ok(parsed) => aot_config.execution_policy = parsed,
                Err(error) => report.push_warning(error),
            }
        }
        if let Some(value) = usize_field(section, "aot_residual_target_chunks") {
            aot_config.residual_target_chunks = Some(value);
        }
        if let Some(value) = usize_field(section, "aot_jacobian_target_chunks") {
            aot_config.jacobian_target_chunks = Some(value);
        }

        backend = backend.with_aot_config(aot_config);
    }

    backend
}

fn parse_postprocessing_config(
    postprocessing: Option<&HashMap<String, Option<Vec<Value>>>>,
    legacy_solver_section: Option<&HashMap<String, Option<Vec<Value>>>>,
    _report: &mut BvpGuiMigrationReport,
) -> BvpPostprocessingConfig {
    let mut config = BvpPostprocessingConfig::default();
    let section = postprocessing
        .filter(|section| !section.is_empty())
        .or(legacy_solver_section);

    if let Some(section) = section {
        if let Some(value) = bool_field(section, "plot") {
            config.plot = value;
        }
        if let Some(value) = bool_field(section, "gnuplot") {
            config.gnuplot = value;
        }
        if let Some(value) = bool_field(section, "save_to_csv") {
            config.save_to_csv = value;
        }
        if let Some(value) = string_field(section, "filename") {
            config.filename = value;
        }
        if let Some(value) = bool_field(section, "save") {
            config.save = value;
        }
        if let Some(value) = bool_field(section, "return_to_dimension") {
            config.return_to_dimension = value;
        }
        if let Some(value) = bool_field(section, "no_plots_in_terminal") {
            config.no_plots_in_terminal = value;
        }
        if let Some(value) = bool_field(section, "gui_plot") {
            config.gui_plot = value;
        }
    }
    config
}

fn parse_advanced_solver_config(
    rel_tolerance: Option<&HashMap<String, Option<Vec<Value>>>>,
    strategy_params: Option<&HashMap<String, Option<Vec<Value>>>>,
    report: &mut BvpGuiMigrationReport,
) -> BvpAdvancedSolverConfig {
    let mut config = BvpAdvancedSolverConfig::default();

    if let Some(section) = rel_tolerance {
        if let Some(value) = float_field(section, "C") {
            if value.is_finite() {
                config.rel_tolerance.c = value;
            } else {
                report.push_warning(
                    "Non-finite rel_tolerance.C encountered. Falling back to default.",
                );
            }
        }
        if let Some(value) = float_field(section, "J") {
            if value.is_finite() {
                config.rel_tolerance.j = value;
            } else {
                report.push_warning(
                    "Non-finite rel_tolerance.J encountered. Falling back to default.",
                );
            }
        }
        if let Some(value) = float_field(section, "Teta") {
            if value.is_finite() {
                config.rel_tolerance.teta = value;
            } else {
                report.push_warning(
                    "Non-finite rel_tolerance.Teta encountered. Falling back to default.",
                );
            }
        }
        if let Some(value) = float_field(section, "q") {
            if value.is_finite() {
                config.rel_tolerance.q = value;
            } else {
                report.push_warning(
                    "Non-finite rel_tolerance.q encountered. Falling back to default.",
                );
            }
        }
    }

    if let Some(section) = strategy_params {
        if let Some(value) = optional_usize_field(section, "max_jac") {
            config.strategy_params.max_jac = Some(value);
        }
        if let Some(value) = optional_usize_field(section, "max_damp_iter") {
            config.strategy_params.max_damp_iter = Some(value);
        }
        if let Some(value) = optional_float_field(section, "damp_factor") {
            if value.is_finite() {
                config.strategy_params.damp_factor = Some(value);
            } else {
                report.push_warning(
                    "Non-finite strategy_params.damp_factor encountered. Falling back to default.",
                );
            }
        }
    }

    config
}

fn parse_initial_guess_config(
    initial_guess: Option<&HashMap<String, Option<Vec<Value>>>>,
    report: &mut BvpGuiMigrationReport,
) -> BvpInitialGuessConfig {
    let mut config = BvpInitialGuessConfig::default();
    let Some(section) = initial_guess else {
        return config;
    };

    if let Some(value) = float_field(section, "universal") {
        if value.is_finite() {
            config.mode = BvpInitialGuessMode::Universal;
            config.universal = value;
            return config;
        }
        report.push_warning(
            "Non-finite initial_guess.universal encountered. Falling back to default.",
        );
    }

    let has_explicit_fields = section.contains_key("C")
        || section.contains_key("J")
        || section.contains_key("Teta")
        || section.contains_key("q");
    if has_explicit_fields {
        config.mode = BvpInitialGuessMode::PerVariable;
        if let Some(value) = float_field(section, "C") {
            config.c = value;
        } else {
            report.push_warning("Missing initial_guess.C. Falling back to default.");
        }
        if let Some(value) = float_field(section, "J") {
            config.j = value;
        } else {
            report.push_warning("Missing initial_guess.J. Falling back to default.");
        }
        if let Some(value) = float_field(section, "Teta") {
            config.teta = value;
        } else {
            report.push_warning("Missing initial_guess.Teta. Falling back to default.");
        }
        if let Some(value) = float_field(section, "q") {
            config.q = value;
        } else {
            report.push_warning("Missing initial_guess.q. Falling back to default.");
        }
    }

    config
}

fn parse_adaptive_grid_config(
    document: &DocumentMap,
    adaptive_strategy: Option<&HashMap<String, Option<Vec<Value>>>>,
    grid_refinement: Option<&HashMap<String, Option<Vec<Value>>>>,
    report: &mut BvpGuiMigrationReport,
) -> BvpAdaptiveGridConfig {
    let mut config = BvpAdaptiveGridConfig::default();
    let legacy_marker = document
        .get("strategy_params")
        .and_then(|section| section.get("adaptive"))
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())
        .and_then(|value| match value {
            Value::Optional(None) => Some(false),
            Value::Optional(Some(inner)) => inner.as_boolean(),
            Value::String(value) if value.trim().eq_ignore_ascii_case("none") => Some(false),
            Value::String(value) if value.trim().eq_ignore_ascii_case("true") => Some(true),
            Value::String(value) if value.trim().eq_ignore_ascii_case("false") => Some(false),
            Value::Boolean(value) => Some(*value),
            _ => None,
        });

    let has_native_payload = adaptive_strategy.is_some_and(|section| !section.is_empty())
        || grid_refinement.is_some_and(|section| !section.is_empty());
    config.enabled = legacy_marker.unwrap_or(has_native_payload);

    if !config.enabled {
        return config;
    }

    if let Some(section) = adaptive_strategy {
        if let Some(value) = usize_field(section, "version") {
            if value != 1 {
                report.push_warning(format!(
                    "Adaptive strategy version `{value}` is not supported. Falling back to version 1."
                ));
            }
        }
        if let Some(value) = usize_field(section, "max_refinements") {
            config.max_refinements = value;
        }
    }

    if let Some(section) = grid_refinement {
        if let Some((method, params)) = parse_grid_refinement_section(section, report) {
            config.grid_refinement = BvpGridRefinementConfig { method, params };
        }
    }

    config
}

fn parse_grid_refinement_section(
    section: &HashMap<String, Option<Vec<Value>>>,
    report: &mut BvpGuiMigrationReport,
) -> Option<(BvpGridRefinementMethod, Vec<f64>)> {
    for method in [
        BvpGridRefinementMethod::Pearson,
        BvpGridRefinementMethod::GrcarSmooke,
        BvpGridRefinementMethod::Twopnt,
        BvpGridRefinementMethod::Easy,
        BvpGridRefinementMethod::DoublePoints,
    ] {
        if let Some((_raw_key, slot)) = section.iter().find(|(key, _)| {
            BvpGridRefinementMethod::parse(key).is_some_and(|parsed| parsed == method)
        }) {
            let params = slot
                .as_ref()
                .and_then(|values| {
                    if let Some(vector) = values.first().and_then(|value| value.as_vector()) {
                        Some(vector.clone())
                    } else {
                        let mut params = Vec::with_capacity(values.len());
                        for value in values {
                            params.push(value.as_float()?);
                        }
                        Some(params)
                    }
                })
                .unwrap_or_else(|| method.default_params());
            return Some((method, params));
        }
    }

    report.push_warning(
        "Unknown grid refinement method found. Falling back to `pearson`.".to_string(),
    );
    None
}

fn string_field(section: &HashMap<String, Option<Vec<Value>>>, field_name: &str) -> Option<String> {
    let value = section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())?;

    match value {
        Value::String(value) => Some(value.clone()),
        Value::Optional(Some(inner)) => inner.as_string().cloned(),
        Value::Optional(None) => None,
        _ => None,
    }
}

fn optional_string_field(
    section: &HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
) -> Option<String> {
    let value = section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())?;

    match value {
        Value::Optional(None) => None,
        Value::Optional(Some(inner)) => inner.as_string().cloned(),
        Value::String(value) if value.eq_ignore_ascii_case("none") => None,
        Value::String(value) => Some(value.clone()),
        _ => None,
    }
}

fn bool_field(section: &HashMap<String, Option<Vec<Value>>>, field_name: &str) -> Option<bool> {
    let value = section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())?;

    match value {
        Value::Boolean(value) => Some(*value),
        Value::String(value) if value.eq_ignore_ascii_case("true") => Some(true),
        Value::String(value) if value.eq_ignore_ascii_case("false") => Some(false),
        _ => None,
    }
}

fn optional_usize_field(
    section: &HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
) -> Option<usize> {
    let value = section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())?;

    match value {
        Value::Optional(None) => None,
        Value::Optional(Some(inner)) => try_value_as_usize(inner).ok(),
        Value::Integer(_) | Value::Usize(_) => try_value_as_usize(value).ok(),
        _ => None,
    }
}

fn optional_float_field(
    section: &HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
) -> Option<f64> {
    let value = section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())?;

    match value {
        Value::Optional(None) => None,
        Value::Optional(Some(inner)) => inner.as_float(),
        _ => value.as_float(),
    }
}

fn usize_field(section: &HashMap<String, Option<Vec<Value>>>, field_name: &str) -> Option<usize> {
    section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())
        .and_then(|value| try_value_as_usize(value).ok())
}

fn float_field(section: &HashMap<String, Option<Vec<Value>>>, field_name: &str) -> Option<f64> {
    section
        .get(field_name)
        .and_then(|slot| slot.as_ref())
        .and_then(|values| values.first())
        .and_then(Value::as_float)
}

fn set_string_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: &str,
) {
    section.insert(
        field_name.to_string(),
        Some(vec![Value::String(value.to_string())]),
    );
}

fn set_optional_string_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: Option<&str>,
) {
    let value = value
        .map(|value| Value::Optional(Some(Box::new(Value::String(value.to_string())))))
        .unwrap_or(Value::Optional(None));
    section.insert(field_name.to_string(), Some(vec![value]));
}

fn set_bool_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: bool,
) {
    section.insert(field_name.to_string(), Some(vec![Value::Boolean(value)]));
}

fn set_optional_usize_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: Option<usize>,
) {
    match value {
        Some(value) => {
            section.insert(
                field_name.to_string(),
                Some(vec![Value::Optional(Some(Box::new(Value::Usize(value))))]),
            );
        }
        None => {
            section.remove(field_name);
        }
    }
}

fn set_optional_float_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: Option<f64>,
) {
    match value {
        Some(value) => {
            section.insert(
                field_name.to_string(),
                Some(vec![Value::Optional(Some(Box::new(Value::Float(value))))]),
            );
        }
        None => {
            section.remove(field_name);
        }
    }
}

fn set_float_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: f64,
) {
    section.insert(field_name.to_string(), Some(vec![Value::Float(value)]));
}

fn set_usize_field(
    section: &mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    value: usize,
) {
    section.insert(field_name.to_string(), Some(vec![Value::Usize(value)]));
}

fn ensure_section_mut<'a>(
    document: &'a mut DocumentMap,
    section_name: &str,
) -> &'a mut HashMap<String, Option<Vec<Value>>> {
    document
        .entry(section_name.to_string())
        .or_insert_with(HashMap::new)
}

fn normalize_key(value: &str) -> String {
    value.trim().to_ascii_lowercase().replace('-', "_")
}

fn generated_backend_name(config: &ReactorBvpSolverConfig) -> String {
    let matrix_prefix = match config.matrix_backend {
        ReactorBvpMatrixBackend::Banded => "banded",
        ReactorBvpMatrixBackend::Sparse => "sparse",
    };

    match config.execution_backend {
        ReactorBvpExecutionBackend::Lambdify => format!("{}_lambdify", matrix_prefix),
        ReactorBvpExecutionBackend::Aot(aot) => match aot.compiler {
            ReactorBvpAotCompiler::CTcc => format!("{}_aot_tcc", matrix_prefix),
            ReactorBvpAotCompiler::CGcc => format!("{}_aot_gcc", matrix_prefix),
            ReactorBvpAotCompiler::Zig => format!("{}_aot_zig", matrix_prefix),
        },
    }
}

const BVP_AOT_ONLY_FIELDS: &[&str] = &[
    "aot_codegen_backend",
    "aot_c_compiler",
    "aot_build_policy",
    "aot_build_profile",
    "aot_compile_preset",
    "aot_execution_policy",
    "aot_residual_target_chunks",
    "aot_jacobian_target_chunks",
];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GuiExecutionBackend {
    Lambdify,
    Aot,
}

impl GuiExecutionBackend {
    pub(crate) fn from_generated_backend(raw: &str) -> Option<Self> {
        let normalized = raw.trim().to_ascii_lowercase();
        if normalized.contains("lambdify") {
            Some(Self::Lambdify)
        } else if generated_backend_requests_aot(&normalized) {
            Some(Self::Aot)
        } else {
            None
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GuiAotCodegenBackend {
    C,
    Zig,
    Rust,
}

impl GuiAotCodegenBackend {
    pub(crate) fn parse(raw: &str) -> Option<Self> {
        match normalize_key(raw).as_str() {
            "c" => Some(Self::C),
            "zig" => Some(Self::Zig),
            "rust" | "rs" => Some(Self::Rust),
            _ => None,
        }
    }

    pub(crate) fn infer_from_preset(preset: &str) -> Self {
        let normalized = preset.trim().to_ascii_lowercase();
        if normalized.contains("zig") {
            Self::Zig
        } else if normalized.contains("rust") {
            Self::Rust
        } else {
            Self::C
        }
    }

    pub(crate) fn as_document_value(self) -> &'static str {
        match self {
            Self::C => "C",
            Self::Zig => "Zig",
            Self::Rust => "Rust",
        }
    }
}

fn ensure_field_slot<'a>(
    section: &'a mut HashMap<String, Option<Vec<Value>>>,
    field_name: &str,
    default_value: Value,
) -> &'a mut Option<Vec<Value>> {
    let entry = section
        .entry(field_name.to_string())
        .or_insert_with(|| Some(vec![default_value.clone()]));

    if entry.is_none() {
        *entry = Some(vec![default_value.clone()]);
    }

    if entry.as_ref().is_some_and(|values| values.is_empty()) {
        *entry = Some(vec![default_value]);
    }

    entry
}

pub(crate) fn generated_backend_requests_aot(generated_backend: &str) -> bool {
    let normalized = generated_backend.trim().to_ascii_lowercase();
    normalized.contains("_aot")
        || normalized.starts_with("aot_")
        || normalized.ends_with("_build_if_missing")
        || normalized.ends_with("_require_prebuilt")
        || normalized.ends_with("_rebuild_always")
        || normalized.ends_with("_repeated")
        || normalized.contains("_atomview_gcc")
        || normalized.contains("_atomview_tcc")
        || normalized.contains("_atomview_zig")
}

fn compiler_inferred_from_preset(preset: &str) -> &'static str {
    let normalized = preset.trim().to_ascii_lowercase();
    if normalized.ends_with("_gcc") {
        "gcc"
    } else if normalized.ends_with("_zig") {
        "zig"
    } else {
        "tcc"
    }
}

/// Normalizes the visible solver-backend controls into a single canonical raw section.
///
/// The GUI and the reactor-task parser share this helper so the renderer does not
/// own a second copy of the backend contract. When a document only carries the
/// compatibility `backend_policy`, the helper still reconstructs the visible
/// backend mode instead of forcing callers to duplicate that fallback.
pub(crate) fn normalize_bvp_solver_backend_section(
    section: &mut HashMap<String, Option<Vec<Value>>>,
) {
    let generated_backend = string_field(section, "generated_backend");
    let backend_mode = if let Some(raw_backend) = generated_backend.as_deref() {
        match GuiExecutionBackend::from_generated_backend(raw_backend) {
            Some(mode) => mode,
            None => return,
        }
    } else {
        match string_field(section, "backend_policy")
            .map(|value| normalize_key(&value))
            .as_deref()
        {
            Some("aot_only") => GuiExecutionBackend::Aot,
            Some("lambdify_only") => GuiExecutionBackend::Lambdify,
            _ => return,
        }
    };

    let matrix_backend = string_field(section, "matrix_backend")
        .or_else(|| string_field(section, "method"))
        .unwrap_or_else(|| "Banded".to_string());
    let matrix_prefix = if matrix_backend.trim().eq_ignore_ascii_case("Sparse") {
        "sparse"
    } else {
        "banded"
    };

    match backend_mode {
        GuiExecutionBackend::Lambdify => {
            set_string_field(section, "backend_policy", "lambdify_only");
            for field_name in BVP_AOT_ONLY_FIELDS {
                section.remove(*field_name);
            }

            let next_backend = format!("{}_lambdify", matrix_prefix);
            if generated_backend.as_deref() != Some(next_backend.as_str()) {
                set_string_field(section, "generated_backend", &next_backend);
                info!("Field 'generated_backend' changed to: {}", next_backend);
            }
        }
        GuiExecutionBackend::Aot => {
            set_string_field(section, "backend_policy", "aot_only");

            let codegen = string_field(section, "aot_codegen_backend")
                .as_deref()
                .and_then(GuiAotCodegenBackend::parse)
                .unwrap_or_else(|| {
                    GuiAotCodegenBackend::infer_from_preset(
                        generated_backend.as_deref().unwrap_or_default(),
                    )
                });
            set_string_field(section, "aot_codegen_backend", codegen.as_document_value());

            match codegen {
                GuiAotCodegenBackend::C => {
                    if !section.contains_key("aot_c_compiler") {
                        set_string_field(
                            section,
                            "aot_c_compiler",
                            compiler_inferred_from_preset(
                                generated_backend.as_deref().unwrap_or_default(),
                            ),
                        );
                    }
                }
                _ => {
                    section.remove("aot_c_compiler");
                }
            }

            for (field_name, default_value) in [
                (
                    "aot_build_policy",
                    Value::String("build_if_missing".to_string()),
                ),
                ("aot_build_profile", Value::String("release".to_string())),
                (
                    "aot_compile_preset",
                    Value::String("dev_fastest".to_string()),
                ),
                ("aot_execution_policy", Value::String("auto".to_string())),
            ] {
                let _ = ensure_field_slot(section, field_name, default_value);
            }

            let next_backend = match codegen {
                GuiAotCodegenBackend::C => {
                    let compiler = string_field(section, "aot_c_compiler").unwrap_or_else(|| {
                        compiler_inferred_from_preset(
                            generated_backend.as_deref().unwrap_or_default(),
                        )
                        .to_string()
                    });
                    format!("{}_aot_{}", matrix_prefix, compiler.to_ascii_lowercase())
                }
                GuiAotCodegenBackend::Zig => format!("{}_aot_zig", matrix_prefix),
                GuiAotCodegenBackend::Rust => format!("{}_aot", matrix_prefix),
            };
            if generated_backend.as_deref() != Some(next_backend.as_str()) {
                set_string_field(section, "generated_backend", &next_backend);
                info!("Field 'generated_backend' changed to: {}", next_backend);
            }
        }
    }
}

/// Executables that the GUI permits for AOT compilation.
///
/// RustedSciThe accepts explicit compiler names, but the GUI should keep a
/// conservative allow-list so shared documents cannot smuggle an arbitrary
/// executable into an AOT confirmation flow.
const BVP_APPROVED_AOT_COMPILERS: &[&str] = &["tcc", "gcc"];

/// Stable description of an AOT toolchain request extracted from solver settings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AotToolchainRequest {
    pub generated_backend: String,
    pub codegen_backend: String,
    pub compiler: Option<String>,
    pub build_policy: String,
}

impl AotToolchainRequest {
    pub(crate) fn summary(&self) -> String {
        format!(
            "backend={}, codegen={}, compiler={}, build_policy={}",
            self.generated_backend,
            self.codegen_backend,
            self.compiler.as_deref().unwrap_or("backend default"),
            self.build_policy
        )
    }
}

/// Validate the GUI-visible AOT toolchain fields before solver handoff.
pub(crate) fn validate_aot_toolchain_fields(document: &DocumentMap) -> Result<(), String> {
    let Some(section) = document.get("solver_settings") else {
        return Ok(());
    };

    let codegen = string_field(section, "aot_codegen_backend")
        .map(|raw| {
            GuiAotCodegenBackend::parse(&raw).ok_or_else(|| {
                format!(
                    "AOT codegen backend `{}` is invalid. Choose C, Zig, or Rust",
                    raw
                )
            })
        })
        .transpose()?;
    if let Some(compiler) = string_field(section, "aot_c_compiler") {
        let normalized = compiler.trim().to_ascii_lowercase();
        if !BVP_APPROVED_AOT_COMPILERS.contains(&normalized.as_str()) {
            return Err(format!(
                "AOT compiler `{}` is not allowed by the GUI. Choose one of: {}",
                compiler,
                BVP_APPROVED_AOT_COMPILERS.join(", ")
            ));
        }
        if let Some(non_c_codegen) = codegen.filter(|codegen| *codegen != GuiAotCodegenBackend::C) {
            return Err(format!(
                "AOT C compiler `{}` cannot be used with the {} codegen backend",
                compiler,
                non_c_codegen.as_document_value()
            ));
        }
    }

    Ok(())
}

/// Build the AOT confirmation payload only when the effective document requests it.
pub(crate) fn aot_toolchain_request(document: &DocumentMap) -> Option<AotToolchainRequest> {
    let section = document.get("solver_settings")?;
    let correction_newton_aot = string_field(section, "solver_family")
        .and_then(|family| BvpSolverFamily::parse(&family))
        == Some(BvpSolverFamily::CorrectionNewton)
        && string_field(section, "execution")
            .is_some_and(|execution| execution.eq_ignore_ascii_case("aot"));
    let generated_backend = if correction_newton_aot {
        "correction_newton_aot".to_string()
    } else {
        string_field(section, "generated_backend")?
    };
    let policy_requests_aot = string_field(section, "backend_policy")
        .is_some_and(|policy| policy.trim().eq_ignore_ascii_case("aot_only"));
    if !correction_newton_aot
        && !generated_backend_requests_aot(&generated_backend)
        && !policy_requests_aot
    {
        return None;
    }

    Some(AotToolchainRequest {
        generated_backend,
        codegen_backend: string_field(section, "aot_codegen_backend")
            .unwrap_or_else(|| "C".to_string()),
        compiler: string_field(section, "aot_c_compiler"),
        build_policy: string_field(section, "aot_build_policy")
            .unwrap_or_else(|| "build_if_missing".to_string()),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SimpleReactorsBVP::task_parser_reactor_BVP::SIMPLE_BVP_TEMPLATE;
    use RustedSciThe::command_interpreter::task_parser::DocumentParser;

    fn parse_template() -> DocumentMap {
        let mut parser = DocumentParser::new(SIMPLE_BVP_TEMPLATE.to_string());
        parser.parse_document().expect("template must parse");
        parser
            .get_result()
            .cloned()
            .expect("template document must exist")
    }

    fn section_value<'a>(document: &'a DocumentMap, section: &str, field: &str) -> &'a Value {
        document
            .get(section)
            .and_then(|section| section.get(field))
            .and_then(|slot| slot.as_ref())
            .and_then(|values| values.first())
            .expect("expected field to exist")
    }

    #[test]
    fn default_gui_config_roundtrips_canonical_solver_settings() {
        let document = parse_template();
        let (config, report) = BvpGuiConfig::from_document(&document);

        assert!(
            report.warnings.is_empty(),
            "warnings: {:?}",
            report.warnings
        );
        assert_eq!(config.core.scheme, BvpScheme::Forward);
        assert_eq!(
            config.backend.matrix_backend,
            ReactorBvpMatrixBackend::Banded
        );
        assert_eq!(
            config.backend.symbolic_backend,
            ReactorBvpSymbolicBackend::AtomView
        );
        assert!(matches!(
            config.backend.execution_backend,
            ReactorBvpExecutionBackend::Lambdify
        ));
        assert!(config.adaptive_grid.enabled);
        assert_eq!(config.adaptive_grid.version, 1);
        assert_eq!(
            config.adaptive_grid.grid_refinement.method,
            BvpGridRefinementMethod::GrcarSmooke
        );
        assert_eq!(config.initial_guess.mode, BvpInitialGuessMode::Universal);
        assert_eq!(config.initial_guess.universal, 1e-2);
        assert_eq!(config.advanced_solver.rel_tolerance.c, 1e-7);
        assert_eq!(config.advanced_solver.strategy_params.max_jac, Some(3));

        let mut rebuilt = DocumentMap::new();
        config.apply_to_document(&mut rebuilt);

        assert_eq!(
            section_value(&rebuilt, "solver_settings", "scheme"),
            &Value::String("forward".to_string())
        );
        assert_eq!(
            section_value(&rebuilt, "solver_settings", "matrix_backend"),
            &Value::String("Banded".to_string())
        );
        assert_eq!(
            section_value(&rebuilt, "solver_settings", "generated_backend"),
            &Value::String("banded_lambdify".to_string())
        );
        assert_eq!(
            section_value(&rebuilt, "initial_guess", "universal"),
            &Value::Float(1e-2)
        );
        assert_eq!(
            section_value(&rebuilt, "rel_tolerance", "C"),
            &Value::Float(1e-7)
        );
    }

    #[test]
    fn aot_backend_roundtrips_through_typed_config() {
        let mut document = parse_template();
        let solver = document
            .get_mut("solver_settings")
            .expect("solver_settings");
        set_string_field(solver, "generated_backend", "sparse_aot_gcc");
        set_string_field(solver, "matrix_backend", "Sparse");
        set_string_field(solver, "symbolic_backend", "ExprLegacy");
        set_string_field(solver, "aot_codegen_backend", "C");
        set_string_field(solver, "aot_c_compiler", "gcc");
        set_string_field(solver, "aot_build_policy", "rebuild_always");
        set_string_field(solver, "aot_build_profile", "debug");
        set_string_field(solver, "aot_compile_preset", "fast_build");
        set_string_field(solver, "aot_execution_policy", "parallel");
        set_usize_field(solver, "aot_residual_target_chunks", 12);
        set_usize_field(solver, "aot_jacobian_target_chunks", 9);

        let (config, report) = BvpGuiConfig::from_document(&document);
        assert!(
            report.warnings.is_empty(),
            "warnings: {:?}",
            report.warnings
        );
        assert_eq!(
            config.backend.matrix_backend,
            ReactorBvpMatrixBackend::Sparse
        );
        assert_eq!(
            config.backend.symbolic_backend,
            ReactorBvpSymbolicBackend::ExprLegacy
        );
        match config.backend.execution_backend {
            ReactorBvpExecutionBackend::Aot(aot) => {
                assert_eq!(aot.compiler, ReactorBvpAotCompiler::CGcc);
                assert_eq!(aot.build_policy, ReactorBvpAotBuildPolicy::RebuildAlways);
                assert_eq!(aot.build_profile, ReactorBvpAotBuildProfile::Debug);
                assert_eq!(
                    aot.compile_preset,
                    crate::SimpleReactorsBVP::solver_backend::ReactorBvpAotCompilePreset::FastBuild
                );
                assert_eq!(aot.execution_policy, ReactorBvpAotExecutionPolicy::Parallel);
                assert_eq!(aot.residual_target_chunks, Some(12));
                assert_eq!(aot.jacobian_target_chunks, Some(9));
            }
            other => panic!("expected AOT backend, got {other:?}"),
        }

        let mut rebuilt = DocumentMap::new();
        config.apply_to_document(&mut rebuilt);
        assert_eq!(
            section_value(&rebuilt, "solver_settings", "generated_backend"),
            &Value::String("sparse_aot_gcc".to_string())
        );
        assert_eq!(
            section_value(&rebuilt, "solver_settings", "backend_policy"),
            &Value::String("aot_only".to_string())
        );
    }

    #[test]
    fn aot_toolchain_request_is_extracted_from_shared_backend_state() {
        let mut document = parse_template();
        let solver = document
            .get_mut("solver_settings")
            .expect("solver_settings");
        set_string_field(solver, "generated_backend", "banded_aot_gcc");
        set_string_field(solver, "aot_codegen_backend", "C");
        set_string_field(solver, "aot_c_compiler", "gcc");
        set_string_field(solver, "aot_build_policy", "build_if_missing");

        let request = aot_toolchain_request(&document).expect("expected AOT request");
        assert_eq!(request.generated_backend, "banded_aot_gcc");
        assert_eq!(request.codegen_backend, "C");
        assert_eq!(request.compiler.as_deref(), Some("gcc"));
        assert_eq!(request.build_policy, "build_if_missing");
        assert!(request.summary().contains("backend=banded_aot_gcc"));
    }

    #[test]
    fn initial_guess_roundtrips_through_typed_config() {
        let mut document = parse_template();
        document.insert(
            "initial_guess".to_string(),
            HashMap::from([
                ("C".to_string(), Some(vec![Value::Float(0.2)])),
                ("J".to_string(), Some(vec![Value::Float(0.3)])),
                ("Teta".to_string(), Some(vec![Value::Float(0.4)])),
                ("q".to_string(), Some(vec![Value::Float(0.5)])),
            ]),
        );

        let (config, report) = BvpGuiConfig::from_document(&document);
        assert!(
            report.warnings.is_empty(),
            "warnings: {:?}",
            report.warnings
        );
        assert!(matches!(
            config.initial_guess.mode,
            BvpInitialGuessMode::PerVariable
        ));
        assert_eq!(config.initial_guess.c, 0.2);
        assert_eq!(config.initial_guess.j, 0.3);
        assert_eq!(config.initial_guess.teta, 0.4);
        assert_eq!(config.initial_guess.q, 0.5);

        let mut rebuilt = DocumentMap::new();
        config.apply_to_document(&mut rebuilt);
        assert_eq!(
            section_value(&rebuilt, "initial_guess", "C"),
            &Value::Float(0.2)
        );
        assert_eq!(
            section_value(&rebuilt, "initial_guess", "q"),
            &Value::Float(0.5)
        );
        assert!(
            !rebuilt
                .get("initial_guess")
                .expect("initial_guess section")
                .contains_key("universal")
        );
    }

    #[test]
    fn advanced_solver_roundtrips_through_typed_config() {
        let mut document = parse_template();
        document.insert(
            "rel_tolerance".to_string(),
            HashMap::from([
                ("C".to_string(), Some(vec![Value::Float(1e-5)])),
                ("J".to_string(), Some(vec![Value::Float(2e-5)])),
                ("Teta".to_string(), Some(vec![Value::Float(3e-5)])),
                ("q".to_string(), Some(vec![Value::Float(4e-5)])),
            ]),
        );
        document.insert(
            "strategy_params".to_string(),
            HashMap::from([
                (
                    "max_jac".to_string(),
                    Some(vec![Value::Optional(Some(Box::new(Value::Usize(7))))]),
                ),
                (
                    "max_damp_iter".to_string(),
                    Some(vec![Value::Optional(Some(Box::new(Value::Usize(11))))]),
                ),
                (
                    "damp_factor".to_string(),
                    Some(vec![Value::Optional(Some(Box::new(Value::Float(0.25))))]),
                ),
            ]),
        );

        let (config, report) = BvpGuiConfig::from_document(&document);
        assert!(
            report.warnings.is_empty(),
            "warnings: {:?}",
            report.warnings
        );
        assert_eq!(config.advanced_solver.rel_tolerance.c, 1e-5);
        assert_eq!(config.advanced_solver.rel_tolerance.q, 4e-5);
        assert_eq!(config.advanced_solver.strategy_params.max_jac, Some(7));
        assert_eq!(
            config.advanced_solver.strategy_params.max_damp_iter,
            Some(11)
        );
        assert_eq!(
            config.advanced_solver.strategy_params.damp_factor,
            Some(0.25)
        );

        let mut rebuilt = DocumentMap::new();
        config.apply_to_document(&mut rebuilt);
        assert_eq!(
            section_value(&rebuilt, "rel_tolerance", "J"),
            &Value::Float(2e-5)
        );
        assert_eq!(
            section_value(&rebuilt, "strategy_params", "max_damp_iter"),
            &Value::Optional(Some(Box::new(Value::Usize(11))))
        );
    }

    #[test]
    fn validate_aot_toolchain_fields_rejects_unapproved_compiler() {
        let mut document = parse_template();
        let solver = document
            .get_mut("solver_settings")
            .expect("solver_settings");
        set_string_field(solver, "generated_backend", "banded_aot_tcc");
        set_string_field(solver, "aot_codegen_backend", "C");
        set_string_field(solver, "aot_c_compiler", "clang");

        let error = validate_aot_toolchain_fields(&document)
            .expect_err("unapproved compiler must be rejected");
        assert!(error.contains("not allowed"));
    }

    #[test]
    fn legacy_adaptive_marker_becomes_typed_adaptive_state() {
        let mut document = parse_template();
        let strategy_params = document
            .get_mut("strategy_params")
            .expect("strategy_params section");
        strategy_params.insert("adaptive".to_string(), Some(vec![Value::Optional(None)]));

        let (config, report) = BvpGuiConfig::from_document(&document);
        assert!(
            report.warnings.is_empty(),
            "warnings: {:?}",
            report.warnings
        );
        assert!(!config.adaptive_grid.enabled);

        let mut rebuilt = document.clone();
        config.apply_to_document(&mut rebuilt);
        assert!(!rebuilt.contains_key("adaptive_strategy"));
        assert!(!rebuilt.contains_key("grid_refinement"));
    }

    #[test]
    fn typed_snapshot_apply_is_idempotent_on_canonical_documents() {
        let document = parse_template();
        let (config, report) = BvpGuiConfig::from_document(&document);
        assert!(report.warnings.is_empty());

        let mut once = document.clone();
        config.apply_to_document(&mut once);

        let mut twice = once.clone();
        config.apply_to_document(&mut twice);

        assert_eq!(once, twice);
    }

    #[test]
    fn normalize_backend_section_keeps_aot_codegen_choice_and_updates_backend_name() {
        let mut document = parse_template();
        {
            let solver = document
                .get_mut("solver_settings")
                .expect("solver_settings");
            set_string_field(solver, "generated_backend", "banded_aot");
            set_string_field(solver, "matrix_backend", "Banded");
            set_string_field(solver, "aot_codegen_backend", "Rust");
            set_string_field(solver, "backend_policy", "lambdify_only");

            normalize_bvp_solver_backend_section(solver);

            assert!(!solver.contains_key("aot_c_compiler"));

            set_string_field(solver, "matrix_backend", "Sparse");
            normalize_bvp_solver_backend_section(solver);
        }

        assert_eq!(
            section_value(&document, "solver_settings", "generated_backend"),
            &Value::String("sparse_aot".to_string())
        );
        assert_eq!(
            section_value(&document, "solver_settings", "backend_policy"),
            &Value::String("aot_only".to_string())
        );
        assert_eq!(
            section_value(&document, "solver_settings", "aot_codegen_backend"),
            &Value::String("Rust".to_string())
        );
    }

    #[test]
    fn normalize_backend_section_removes_aot_fields_for_lambdify() {
        let mut document = parse_template();
        {
            let solver = document
                .get_mut("solver_settings")
                .expect("solver_settings");
            set_string_field(solver, "generated_backend", "banded_lambdify");
            set_string_field(solver, "matrix_backend", "Banded");
            set_string_field(solver, "aot_codegen_backend", "C");
            set_string_field(solver, "aot_c_compiler", "gcc");
            set_string_field(solver, "aot_build_policy", "rebuild_always");
            set_string_field(solver, "aot_build_profile", "debug");

            normalize_bvp_solver_backend_section(solver);
        }

        assert_eq!(
            section_value(&document, "solver_settings", "generated_backend"),
            &Value::String("banded_lambdify".to_string())
        );
        assert_eq!(
            section_value(&document, "solver_settings", "backend_policy"),
            &Value::String("lambdify_only".to_string())
        );
        let solver = document.get("solver_settings").expect("solver_settings");
        assert!(!solver.contains_key("aot_codegen_backend"));
        assert!(!solver.contains_key("aot_c_compiler"));
        assert!(!solver.contains_key("aot_build_policy"));
        assert!(!solver.contains_key("aot_build_profile"));
    }

    #[test]
    fn normalize_backend_section_recovers_backend_policy_only_aot_docs() {
        let mut document = parse_template();
        {
            let solver = document
                .get_mut("solver_settings")
                .expect("solver_settings");
            solver.remove("generated_backend");
            set_string_field(solver, "method", "Sparse");
            set_string_field(solver, "matrix_backend", "Sparse");
            set_string_field(solver, "backend_policy", "aot_only");
            set_string_field(solver, "aot_c_compiler", "gcc");

            normalize_bvp_solver_backend_section(solver);
        }

        assert_eq!(
            section_value(&document, "solver_settings", "generated_backend"),
            &Value::String("sparse_aot_gcc".to_string())
        );
        assert_eq!(
            section_value(&document, "solver_settings", "backend_policy"),
            &Value::String("aot_only".to_string())
        );
        assert_eq!(
            section_value(&document, "solver_settings", "aot_c_compiler"),
            &Value::String("gcc".to_string())
        );
    }
}