pounce-cinterface 0.17.0

C ABI for POUNCE (port of Ipopt's Interfaces/IpStdCInterface.{h,cpp}). Provides CreateIpoptProblem / IpoptSolve / FreeIpoptProblem so existing PyIpopt / cyipopt / JuMP / AMPL clients link without source changes. Feature-complete for the upstream Ipopt C ABI surface.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
//! POUNCE C ABI — port of `Interfaces/IpStdCInterface.{h,cpp}`.
//!
//! Provides the `CreateIpoptProblem / IpoptSolve / FreeIpoptProblem` C
//! entry points that existing PyIpopt / cyipopt / JuMP wrappers link
//! against. Function names and signatures match upstream Ipopt 3.14.x
//! exactly so consumers can swap `libipopt.{dylib,so}` for
//! `libpounce_cinterface` without rebuilding.
//!
//! Surface area (in `IpStdCInterface.h` order):
//!
//! * Lifecycle: [`CreateIpoptProblem`], [`FreeIpoptProblem`].
//! * Options: [`AddIpoptStrOption`], [`AddIpoptNumOption`],
//!   [`AddIpoptIntOption`], [`OpenIpoptOutputFile`],
//!   [`SetIpoptProblemScaling`].
//! * Callbacks: [`SetIntermediateCallback`].
//! * Solve: [`IpoptSolve`].
//! * Introspection (only valid inside an intermediate callback):
//!   [`GetIpoptCurrentIterate`], [`GetIpoptCurrentViolations`].
//! * Library info: [`GetIpoptVersion`].
//!
//! Pounce extensions for post-solve stats (not present in upstream
//! Ipopt's C API): [`GetIpoptIterCount`], [`GetIpoptSolveTime`],
//! [`GetIpoptPrimalInf`], [`GetIpoptDualInf`], [`GetIpoptComplInf`].
//!
//! All entry points are `extern "C"` and `#[no_mangle]`. Pointers are
//! raw and the caller is responsible for lifetime; the `IpoptProblem`
//! handle is opaque (`*mut c_void` from C's perspective). The Fortran
//! 77 ABI shim lives in [`fortran`].

#![allow(non_camel_case_types, non_snake_case)]
#![allow(unsafe_op_in_unsafe_fn, dead_code)]
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]

pub mod bounds;
pub mod errors;
pub mod fortran;
pub mod qp;
pub mod solver;

pub use bounds::*;
pub use errors::*;
pub use qp::*;

use bounds::{ComplementsLedger, ComplementsRow, ComplementsUse, DeclaredPairs};
use pounce_algorithm::application::{
    IpoptApplication, default_backend_factory, feral_config_from_options, ma57_config_from_options,
};
use pounce_algorithm::intermediate as ip_intermediate;
use pounce_common::reg_options::OptionType;
use pounce_common::types::{NLP_LOWER_BOUND_INF, NLP_UPPER_BOUND_INF};
use pounce_nlp::mpcc::{ComplementarityPair, PairErrorKind, PairShape, classify_pair};
use pounce_nlp::return_codes::ApplicationReturnStatus;
use pounce_nlp::solve_statistics::SolveStatistics;
use pounce_nlp::tnlp::{
    BoundsInfo, IndexStyle, IpoptCq, IpoptData, NlpInfo, ScalingRequest, Solution, SparsityRequest,
    StartingPoint, TNLP,
};
use pounce_restoration::resto_alg_builder::RestoAlgorithmBuilder;
use pounce_restoration::resto_inner_solver::{
    InnerBackendFactoryFactory, make_default_restoration_factory_provider,
};
use pounce_restoration::second_opinion_driver::run_second_opinion_ladder;
use std::cell::RefCell;
use std::ffi::{CStr, c_char, c_int, c_uint, c_void};
use std::rc::Rc;

/// Mirrors C `Number` typedef in `IpStdCInterface.h`.
pub type Number = f64;
/// Mirrors C `Index`.
pub type Index = c_int;
/// Mirrors C `Bool`, which `pounce.h` — like Ipopt 3.14's
/// `IpStdCInterface.h` — declares as the C99 `bool`. That is **one byte**,
/// so this is `u8` and not `c_int`.
///
/// It was `c_int` until gh#624, i.e. four bytes on the Rust side against
/// one on every C caller's, in both directions:
///
/// * a callback returning `false` sets only `AL`, and the x86-64 psABI
///   leaves the rest of `EAX` unspecified — read as an `i32`, a failed
///   evaluation could come back nonzero, which reads as *success*. The
///   solver would then accept a point it was told it could not evaluate
///   instead of cutting the step. gcc and clang emit `movzbl`, which is
///   why this stayed latent rather than exploding;
/// * an *array* of them would have been a hard stride bug, 1-byte
///   elements read at 4-byte spacing. That is why
///   [`IpoptSetNonlinearVariables`] takes a count plus an index list
///   rather than the `Bool` mask gh#624 originally proposed.
///
/// `u8` rather than Rust's `bool` on purpose: the two have identical
/// layout, but `bool` carries a validity invariant (it *must* hold 0 or
/// 1), and a C caller reaching this boundary with anything else — an
/// older header where `Bool` was `int`, a hand-rolled binding, a value
/// that came through a `memcpy` — would be instant undefined behaviour.
/// `u8` accepts whatever arrives and tests it the way C does, which is
/// the same reason the entry points validate rather than trust.
pub type Bool = u8;

const TRUE: Bool = 1;
const FALSE: Bool = 0;

// The whole point of the alias. `pounce.h` says `typedef bool Bool`, so a
// build where this stops being one byte is one where every C caller
// disagrees with the implementation about every boolean.
const _: () = assert!(
    core::mem::size_of::<Bool>() == 1,
    "Bool must be one byte to match `typedef bool Bool` in pounce.h"
);

/// Run an FFI entry-point body, converting any Rust panic into `fallback`
/// rather than letting it unwind across the `extern "C"` boundary — which is
/// undefined behavior and, in practice, a process abort that takes the
/// embedding application down with it. Upstream Ipopt's C interface likewise
/// wraps the solve in `try { … } catch(…)` and reports `Internal_Error`
/// instead of propagating a C++ exception across the ABI.
///
/// Note: this guards panics that originate in *pounce's own* Rust code (the
/// solver core, the callback bridge, numerical kernels). A panic inside a
/// user-supplied `extern "C"` callback aborts at that callback's own ABI
/// boundary, before unwinding can reach here — that is the caller's
/// responsibility, exactly as in the C/C++ original.
pub(crate) fn ffi_guard<R>(fallback: R, body: impl FnOnce() -> R) -> R {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)) {
        Ok(r) => r,
        Err(_) => fallback,
    }
}

/// An *extensible* caller-allocated output struct (gh#1147): its first
/// member is `ipindex struct_size`, which the caller sets to `sizeof(T)`
/// before the call. `PounceComplementarityStats`, `PounceComplementaritySolve`,
/// `PounceQpResiduals` and `PounceQpCertificate` follow it;
/// `PounceLinearSolverStats` does not (it shipped before the convention).
///
/// # The growth rule
///
/// A later release may only **append** fields at the end; nothing is
/// removed, reordered or widened. Every getter then writes
/// `min(caller's struct_size, its own size_of::<T>())` bytes — which is what
/// `write_extensible` does for this release, whose size is the minimum
/// whenever the call is accepted at all.
///
/// # Safety
///
/// Implementors must be `#[repr(C)]` with `struct_size: Index` as the first
/// field, so it sits at offset 0 (asserted by
/// `tests/c_examples_build_and_run.rs`).
pub(crate) unsafe trait ExtensibleOut: Copy {}

/// This release's `sizeof(T)`, as the `struct_size` value a caller passes.
pub(crate) const fn struct_size_of<T: ExtensibleOut>() -> Index {
    std::mem::size_of::<T>() as Index
}

/// Write `value` into the caller's `out` under the `struct_size` contract.
///
/// Returns `false`, writing nothing at all, when the caller's
/// `struct_size` is smaller than this release's `size_of::<T>()` (a
/// forgotten or garbage initializer: `0`, negative, or a size from a
/// release that predates a field of `T` — there is none yet). Otherwise
/// copies **exactly this release's bytes** of `value` after `struct_size`
/// and returns `true`; `struct_size` itself is read, never written, and no
/// byte past `size_of::<T>()` is touched, however large `struct_size` is
/// (a caller built against a newer header keeps its newer fields as they
/// were).
///
/// The copy is a bounded byte copy, not `*out = value`, on purpose: a
/// whole-struct assignment is a contract about *this* release's size that
/// would silently stay one when a field is appended. When appending a field
/// to `T` in a later release, keep this function, and change the refusal
/// below to the size of the oldest layout still accepted (the size *before*
/// the first appended field), writing `min(struct_size, size_of::<T>())`
/// bytes; never lower the floor to accept `struct_size` values a getter
/// cannot tell from an uninitialized one.
///
/// # Safety
///
/// `out` must be non-NULL, aligned for `T`, readable for its first
/// `size_of::<Index>()` bytes and, when the call is accepted, writable for
/// `size_of::<T>()` bytes (the caller promised `struct_size` of them).
pub(crate) unsafe fn write_extensible<T: ExtensibleOut>(out: *mut T, value: &T) -> bool {
    const HEAD: usize = std::mem::size_of::<Index>();
    let size = std::mem::size_of::<T>();
    // SAFETY: `struct_size` is at offset 0 (the trait's contract) and the
    // caller guarantees the first `HEAD` bytes are readable.
    let claimed = unsafe { std::ptr::read(out.cast::<Index>()) };
    if usize::try_from(claimed).map_or(true, |c| c < size) {
        return false;
    }
    // SAFETY: `claimed >= size`, so the caller promised `size` writable
    // bytes; `value` is a distinct Rust value, so the ranges cannot overlap.
    // Only bytes `HEAD..size` are written: `struct_size` stays the caller's.
    unsafe {
        std::ptr::copy_nonoverlapping(
            (value as *const T).cast::<u8>().add(HEAD),
            out.cast::<u8>().add(HEAD),
            size - HEAD,
        );
    }
    true
}

/// C-ABI encoding of [`pounce_qp::BoundStatus`] (§7.2 of the
/// active-set-SQP design note). Stable values:
/// `0 = Inactive`, `1 = AtLower`, `2 = AtUpper`, `3 = Fixed`.
pub type IpoptBoundStatus = c_int;
/// C-ABI encoding of [`pounce_qp::ConsStatus`] (§7.2). Stable values:
/// `0 = Inactive`, `1 = AtLower`, `2 = AtUpper`, `3 = Equality`.
pub type IpoptConsStatus = c_int;

const POUNCE_WS_INACTIVE: c_int = 0;
const POUNCE_WS_AT_LOWER: c_int = 1;
const POUNCE_WS_AT_UPPER: c_int = 2;
const POUNCE_WS_FIXED_OR_EQ: c_int = 3;

/// Internal owned state behind the opaque `IpoptProblem` handle.
/// `#[repr(C)]` is unnecessary because C only sees the pointer.
pub struct IpoptProblemInfo {
    pub(crate) app: IpoptApplication,
    pub(crate) n: Index,
    pub(crate) m: Index,
    pub(crate) nele_jac: Index,
    pub(crate) nele_hess: Index,
    pub(crate) index_style: Index,
    pub(crate) x_l: Vec<Number>,
    pub(crate) x_u: Vec<Number>,
    pub(crate) g_l: Vec<Number>,
    pub(crate) g_u: Vec<Number>,
    pub(crate) eval_f: Option<Eval_F_CB>,
    pub(crate) eval_g: Option<Eval_G_CB>,
    pub(crate) eval_grad_f: Option<Eval_Grad_F_CB>,
    pub(crate) eval_jac_g: Option<Eval_Jac_G_CB>,
    pub(crate) eval_h: Option<Eval_H_CB>,
    pub(crate) intermediate_cb: Option<Intermediate_CB>,
    /// User-provided scaling installed by [`SetIpoptProblemScaling`].
    /// `obj_scaling` defaults to `1.0`. `x_scaling`/`g_scaling` are
    /// `None` when the user passed NULL.
    pub(crate) user_scaling: Option<UserScaling>,
    /// Final iterate and stats from the most recent [`IpoptSolve`].
    /// Used by `GetIpopt{IterCount,SolveTime,...}` accessors. Reset
    /// (cleared) by the next `IpoptSolve` call.
    pub(crate) last_solve: Option<LastSolve>,
    /// Working set staged by [`IpoptSetWarmStartWorkingSet`], pending
    /// until the next [`IpoptSolve`].
    ///
    /// Only the working set is stored here — deliberately *not* a full
    /// `SqpIterates`. The primal/dual iterate is not knowable at set
    /// time; it arrives with the `x` (and, under
    /// `warm_start_init_point=yes`, `mult_g`/`mult_x_L`/`mult_x_U`)
    /// buffers passed to `IpoptSolve`. Building the `SqpIterates`
    /// eagerly here forced the primal to a placeholder — zeros — which
    /// then *became* the starting iterate, because
    /// `SqpAlgorithm::optimize_with_warm_start` uses a supplied warm
    /// iterate instead of querying the NLP for a starting point. The
    /// merge therefore has to happen inside `IpoptSolve` (gh#484).
    pub(crate) pending_working_set: Option<pounce_qp::WorkingSet>,
    /// Nonlinear-variable subset staged by
    /// [`IpoptSetNonlinearVariables`] (gh#624). Stored in the problem's
    /// own index style, exactly as the caller passed it; the bridge
    /// TNLP serves it back through
    /// `get_number_of_nonlinear_variables` /
    /// `get_list_of_nonlinear_variables`, which is where the algorithm
    /// reads it. `None` — the default — means "every variable is
    /// nonlinear".
    pub(crate) nonlinear_vars: Option<Vec<Index>>,
    /// Complementarity pairs declared by [`AddPounceComplementarityPair`] /
    /// [`SetPounceComplementarityPairs`] (gh#1147), **0-based** whatever
    /// the problem's index style, in declaration order. Every stored set
    /// passed [`pounce_nlp::mpcc::validate_pairs`] against this handle's
    /// bounds when it was declared. Empty — the default — means no pairs.
    pub(crate) complementarity: DeclaredPairs,
    /// Every `(row, var)`, 0-based, that [`AddPounceComplementsConstraint`]
    /// accepted on this handle, whether or not it declared a pair. The
    /// helper refuses a row or variable already in here (or in
    /// `complementarity`), so one `F` or one `x` cannot be in two MOI
    /// `Complements` constraints. Never cleared: the bound edits it records
    /// are not undone either.
    pub(crate) complements_used: ComplementsLedger,
}

/// User-provided NLP scaling stored on the problem until
/// [`IpoptSolve`] copies it into the [`CCallbackTnlp`] bridge.
#[derive(Clone)]
pub(crate) struct UserScaling {
    obj_scaling: Number,
    x_scaling: Option<Vec<Number>>,
    g_scaling: Option<Vec<Number>>,
}

/// Stats and final-iterate snapshot retained between
/// [`IpoptSolve`] and the post-solve accessors. Everything needed to
/// reconstruct a `pounce.solve-report/v1` JSON file lives here so
/// [`IpoptWriteSolveReport`] doesn't have to ask the caller to thread
/// `x`/`lambda`/`obj` back in.
#[derive(Clone)]
pub(crate) struct LastSolve {
    pub(crate) stats: SolveStatistics,
    pub(crate) status: ApplicationReturnStatus,
    pub(crate) linear_solver: Option<pounce_linsol::summary::LinearSolverSummary>,
    pub(crate) final_x: Vec<Number>,
    pub(crate) final_lambda: Vec<Number>,
    pub(crate) final_obj: Number,
    /// The complementarity driver's record when the solve declared pairs
    /// (gh#1147); `None` on every other solve, including every session solve.
    pub(crate) mpcc: Option<pounce_restoration::mpcc_driver::MpccOutcome>,
    /// The second-opinion ladder's outcome when the solve took the path
    /// without pairs (gh#850, gh#1147); `None` on a driver solve and on
    /// every session solve, neither of which runs the ladder. Kept whether
    /// or not a rung ran: [`IpoptWriteSolveReport`] writes the block under
    /// the same `ran()` test as the CLI and Python.
    pub(crate) second_opinion:
        Option<pounce_restoration::second_opinion_driver::SecondOpinionOutcome>,
}

impl Default for LastSolve {
    fn default() -> Self {
        Self {
            stats: SolveStatistics::default(),
            status: ApplicationReturnStatus::InternalError,
            linear_solver: None,
            final_x: Vec::new(),
            final_lambda: Vec::new(),
            final_obj: 0.0,
            mpcc: None,
            second_opinion: None,
        }
    }
}

pub type IpoptProblem = *mut IpoptProblemInfo;

// User-callback function pointer types — match
// `IpStdCInterface.h:Eval_F_CB` etc. byte for byte.

pub type Eval_F_CB = unsafe extern "C" fn(
    n: Index,
    x: *const Number,
    new_x: Bool,
    obj_value: *mut Number,
    user_data: *mut c_void,
) -> Bool;

pub type Eval_Grad_F_CB = unsafe extern "C" fn(
    n: Index,
    x: *const Number,
    new_x: Bool,
    grad_f: *mut Number,
    user_data: *mut c_void,
) -> Bool;

pub type Eval_G_CB = unsafe extern "C" fn(
    n: Index,
    x: *const Number,
    new_x: Bool,
    m: Index,
    g: *mut Number,
    user_data: *mut c_void,
) -> Bool;

pub type Eval_Jac_G_CB = unsafe extern "C" fn(
    n: Index,
    x: *const Number,
    new_x: Bool,
    m: Index,
    nele_jac: Index,
    iRow: *mut Index,
    jCol: *mut Index,
    values: *mut Number,
    user_data: *mut c_void,
) -> Bool;

pub type Eval_H_CB = unsafe extern "C" fn(
    n: Index,
    x: *const Number,
    new_x: Bool,
    obj_factor: Number,
    m: Index,
    lambda: *const Number,
    new_lambda: Bool,
    nele_hess: Index,
    iRow: *mut Index,
    jCol: *mut Index,
    values: *mut Number,
    user_data: *mut c_void,
) -> Bool;

pub type Intermediate_CB = unsafe extern "C" fn(
    alg_mod: Index,
    iter_count: Index,
    obj_value: Number,
    inf_pr: Number,
    inf_du: Number,
    mu: Number,
    d_norm: Number,
    regularization_size: Number,
    alpha_du: Number,
    alpha_pr: Number,
    ls_trials: Index,
    user_data: *mut c_void,
) -> Bool;

/// Port of `IpStdCInterface.cpp:CreateIpoptProblem`. Returns NULL on
/// invalid arguments (negative n/m, missing required callbacks, NULL
/// bound pointers when the corresponding dimension is positive).
///
/// # Safety
///
/// `x_L`, `x_U` must be valid pointers to `n` `Number`s when `n > 0`.
/// `g_L`, `g_U` must be valid pointers to `m` `Number`s when `m > 0`.
/// The callback function pointers must be valid for the lifetime of
/// the returned [`IpoptProblem`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn CreateIpoptProblem(
    n: Index,
    x_L: *const Number,
    x_U: *const Number,
    m: Index,
    g_L: *const Number,
    g_U: *const Number,
    nele_jac: Index,
    nele_hess: Index,
    index_style: Index,
    eval_f: Option<Eval_F_CB>,
    eval_g: Option<Eval_G_CB>,
    eval_grad_f: Option<Eval_Grad_F_CB>,
    eval_jac_g: Option<Eval_Jac_G_CB>,
    eval_h: Option<Eval_H_CB>,
) -> IpoptProblem {
    unsafe {
        // Install the tracing subscriber on first use so C consumers
        // (cyipopt, AMPL, …) get logging and the iteration collector that
        // backs `IpoptEnableIterHistory` (pounce#71). Idempotent.
        pounce_observability::init_subscriber();

        if n < 0 || m < 0 || nele_jac < 0 || nele_hess < 0 {
            return std::ptr::null_mut();
        }
        if !(0..=1).contains(&index_style) {
            return std::ptr::null_mut();
        }
        if eval_f.is_none() || eval_grad_f.is_none() {
            return std::ptr::null_mut();
        }
        if m > 0 && (eval_g.is_none() || eval_jac_g.is_none()) {
            return std::ptr::null_mut();
        }
        if n > 0 && (x_L.is_null() || x_U.is_null()) {
            return std::ptr::null_mut();
        }
        if m > 0 && (g_L.is_null() || g_U.is_null()) {
            return std::ptr::null_mut();
        }

        let x_l = if n > 0 {
            std::slice::from_raw_parts(x_L, n as usize).to_vec()
        } else {
            Vec::new()
        };
        let x_u = if n > 0 {
            std::slice::from_raw_parts(x_U, n as usize).to_vec()
        } else {
            Vec::new()
        };
        let g_l_vec = if m > 0 {
            std::slice::from_raw_parts(g_L, m as usize).to_vec()
        } else {
            Vec::new()
        };
        let g_u_vec = if m > 0 {
            std::slice::from_raw_parts(g_U, m as usize).to_vec()
        } else {
            Vec::new()
        };

        let info = Box::new(IpoptProblemInfo {
            app: IpoptApplication::new(),
            n,
            m,
            nele_jac,
            nele_hess,
            index_style,
            x_l,
            x_u,
            g_l: g_l_vec,
            g_u: g_u_vec,
            eval_f,
            eval_g,
            eval_grad_f,
            eval_jac_g,
            eval_h,
            intermediate_cb: None,
            user_scaling: None,
            nonlinear_vars: None,
            complementarity: DeclaredPairs::default(),
            complements_used: ComplementsLedger::default(),
            last_solve: None,
            pending_working_set: None,
        });
        Box::into_raw(info)
    }
}

/// Port of `IpStdCInterface.cpp:FreeIpoptProblem`.
///
/// # Safety
///
/// `ipopt_problem` must be a pointer previously returned by
/// [`CreateIpoptProblem`] and not yet freed, or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn FreeIpoptProblem(ipopt_problem: IpoptProblem) {
    unsafe {
        if ipopt_problem.is_null() {
            return;
        }
        drop(Box::from_raw(ipopt_problem));
    }
}

unsafe fn keyword_str<'a>(keyword: *const c_char) -> Option<&'a str> {
    unsafe {
        if keyword.is_null() {
            return None;
        }
        CStr::from_ptr(keyword).to_str().ok()
    }
}

/// Port of `IpStdCInterface.cpp:AddIpoptStrOption`.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. `keyword` and `val`
/// must be valid NUL-terminated strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn AddIpoptStrOption(
    ipopt_problem: IpoptProblem,
    keyword: *const c_char,
    val: *const c_char,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let Some(k) = keyword_str(keyword) else {
            return FALSE;
        };
        if val.is_null() {
            return FALSE;
        }
        let Ok(v) = CStr::from_ptr(val).to_str() else {
            return FALSE;
        };
        match info.app.options_mut().set_string_value(k, v, true, false) {
            Ok(_) => TRUE,
            Err(_) => FALSE,
        }
    }
}

/// Port of `AddIpoptNumOption`.
///
/// # Safety
///
/// `keyword` must be a valid NUL-terminated string and
/// `ipopt_problem` must be a valid `IpoptProblem`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn AddIpoptNumOption(
    ipopt_problem: IpoptProblem,
    keyword: *const c_char,
    val: Number,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let Some(k) = keyword_str(keyword) else {
            return FALSE;
        };
        match info
            .app
            .options_mut()
            .set_numeric_value(k, val, true, false)
        {
            Ok(_) => TRUE,
            Err(_) => FALSE,
        }
    }
}

/// Port of `AddIpoptIntOption`.
///
/// # Safety
///
/// `keyword` must be a valid NUL-terminated string and
/// `ipopt_problem` must be a valid `IpoptProblem`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn AddIpoptIntOption(
    ipopt_problem: IpoptProblem,
    keyword: *const c_char,
    val: Index,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let Some(k) = keyword_str(keyword) else {
            return FALSE;
        };
        match info.app.options_mut().set_integer_value(
            k,
            val as pounce_common::types::Index,
            true,
            false,
        ) {
            Ok(_) => TRUE,
            Err(_) => FALSE,
        }
    }
}

/// Port of `IpStdCInterface.cpp:OpenIpoptOutputFile`. Opens `file_name`
/// at `print_level` and attaches a journalist `FileJournal` so all
/// solver output is mirrored to disk. Equivalent to setting
/// `output_file` + `file_print_level` options and triggering
/// `IpoptApplication::Initialize`.
///
/// Returns `TRUE` (1) on success, `FALSE` (0) if the file could not
/// be opened or the option store rejected the value.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. `file_name` must
/// be a valid NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn OpenIpoptOutputFile(
    ipopt_problem: IpoptProblem,
    file_name: *const c_char,
    print_level: c_int,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() || file_name.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let Ok(fname) = CStr::from_ptr(file_name).to_str() else {
            return FALSE;
        };
        if info.app.open_output_file(fname, print_level) {
            TRUE
        } else {
            FALSE
        }
    }
}

/// Port of `IpStdCInterface.cpp:SetIpoptProblemScaling`. Stores
/// user-provided NLP scaling on the problem; the scaling is forwarded
/// to the solver via [`TNLP::get_scaling_parameters`] when the option
/// `nlp_scaling_method=user-scaling` is set. Passing NULL for
/// `x_scaling` / `g_scaling` disables scaling on that axis.
///
/// Always returns `TRUE` (the upstream contract). A non-trivial
/// `x_scaling` is applied as a change of variables, so the solution and
/// bound multipliers `IpoptSolve` writes back are in the caller's own
/// units (gh#486). A factor that is not finite and positive is refused
/// at solve time, where [`IpoptSolve`] returns `Invalid_Option` and the
/// journalist explains why: store-time validation is not an option,
/// because the C signature has no way to report it.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. When non-NULL,
/// `x_scaling` must point to `n` doubles and `g_scaling` to `m`
/// doubles; both arrays are copied internally.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn SetIpoptProblemScaling(
    ipopt_problem: IpoptProblem,
    obj_scaling: Number,
    x_scaling: *const Number,
    g_scaling: *const Number,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let n = info.n as usize;
        let m = info.m as usize;
        let x_vec = if !x_scaling.is_null() && n > 0 {
            Some(std::slice::from_raw_parts(x_scaling, n).to_vec())
        } else {
            None
        };
        let g_vec = if !g_scaling.is_null() && m > 0 {
            Some(std::slice::from_raw_parts(g_scaling, m).to_vec())
        } else {
            None
        };
        info.user_scaling = Some(UserScaling {
            obj_scaling,
            x_scaling: x_vec,
            g_scaling: g_vec,
        });
        TRUE
    }
}

/// Port of `IpStdCInterface.cpp:IpoptSolve`. Returns the
/// `ApplicationReturnStatus` integer.
///
/// Builds a [`CCallbackTnlp`] from the user-supplied callback table
/// and bounds, runs it through [`IpoptApplication::optimize_tnlp`],
/// and writes back the final iterate.
///
/// With complementarity pairs declared (gh#1147) the bridge goes to
/// [`pounce_restoration::mpcc_driver::solve_mpcc`] instead of one
/// `optimize_tnlp` and the second-opinion ladder, as in the CLI and Python;
/// the driver forwards its reported point to the bridge once, so the
/// write-back is the same. A staged SQP working set plus pairs is refused
/// with `Invalid_Problem_Definition` before any callback.
///
/// # Safety
///
/// All pointer arguments are read/written per the
/// `IpStdCInterface.h` contract: `x` is in/out (size `n`); `g` is
/// out-only (size `m`); `mult_g`, `mult_x_L`, `mult_x_U` (sizes
/// `m, n, n`) are out, and are also *read* as the starting multipliers
/// when `warm_start_init_point=yes` (upstream's `start_lam`, `start_z_L`,
/// `start_z_U`). Any of them may be NULL; a NULL multiplier buffer under
/// a warm start means "not supplied" and that block starts unseeded.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptSolve(
    ipopt_problem: IpoptProblem,
    x: *mut Number,
    g: *mut Number,
    obj_val: *mut Number,
    mult_g: *mut Number,
    mult_x_L: *mut Number,
    mult_x_U: *mut Number,
    user_data: *mut c_void,
) -> Index {
    unsafe {
        if ipopt_problem.is_null() {
            return ApplicationReturnStatus::InternalError as Index;
        }
        // Invalidate the retained stats up front, before the solve is attempted.
        // The `last_solve` snapshot is only repopulated at the *end* of a
        // completed solve, so if the guarded body below bails early or a panic is
        // caught (returning `Internal_Error`), the post-solve accessors
        // (`GetIpoptIterCount`, `IpoptWriteSolveReport`, …) must not silently
        // report the *previous* solve's stats. Clearing here makes the
        // failure-consistent state "no data" rather than stale data (F5).
        (*ipopt_problem).last_solve = None;
        // Guard the whole solve: `optimize_tnlp` runs the entire pounce core and
        // callback bridge, any of which could panic on an unexpected internal
        // state. Without this, such a panic would unwind across `extern "C"` and
        // abort the embedding process; instead we report `Internal_Error`,
        // matching upstream Ipopt's exception handling. (See `ffi_guard`.)
        ffi_guard(ApplicationReturnStatus::InternalError as Index, || {
            let info = &mut *ipopt_problem;
            // Every solve states, for its own duration, whether the live
            // iterate on this thread is a lowered model's (gh#1147 review):
            // a pair-free solve nested inside a lowered solve's callback
            // clears the flag, so its own inspectors answer, and the outer
            // value comes back when it returns.
            let _lowered = LoweredSolveGuard::set(!info.complementarity.is_empty());
            if info.n < 0 || info.m < 0 {
                return ApplicationReturnStatus::InvalidProblemDefinition as Index;
            }
            if info.n > 0 && x.is_null() {
                return ApplicationReturnStatus::InvalidProblemDefinition as Index;
            }
            // A staged SQP working set is over the caller's rows and
            // variables; the complementarity driver solves a lowered model
            // with more rows (and possibly lifted variables), so there is no
            // set it could seed. Refused before any callback runs, and
            // neither the working set nor the pairs are consumed (gh#1147).
            if !info.complementarity.is_empty() && info.pending_working_set.is_some() {
                if pounce_algorithm::second_opinion::narration_is_wanted(info.app.options()) {
                    eprintln!(
                        "pounce: a warm-start working set cannot seed a solve with \
                         complementarity pairs ({} declared); clear one of them \
                         (IpoptClearWarmStartWorkingSet or ClearPounceComplementarityPairs).",
                        info.complementarity.len()
                    );
                }
                return ApplicationReturnStatus::InvalidProblemDefinition as Index;
            }

            let n_us = info.n as usize;
            let m_us = info.m as usize;
            let initial_x = if n_us > 0 {
                std::slice::from_raw_parts(x, n_us).to_vec()
            } else {
                Vec::new()
            };

            // Merge any working set staged by
            // `IpoptSetWarmStartWorkingSet` with the iterate the caller
            // actually supplied. This is the point at which the primal
            // starting point is known, so it is the only correct place
            // to build the `SqpIterates` (gh#484).
            //
            // Duals follow upstream Ipopt's `IpoptSolve` contract:
            // `mult_g` / `mult_x_L` / `mult_x_U` are inputs only when
            // `warm_start_init_point=yes`, and out-only otherwise. A
            // caller who has not opted in may pass uninitialized
            // buffers, so reading them unconditionally would seed the
            // SQP with garbage multipliers.
            if let Some(working) = info.pending_working_set.take() {
                let seed_duals = matches!(
                    info.app
                        .options()
                        .get_bool_value("warm_start_init_point", ""),
                    Ok((true, true))
                );
                let read_in = |p: *const Number, len: usize| -> Vec<Number> {
                    if seed_duals && !p.is_null() && len > 0 {
                        std::slice::from_raw_parts(p, len).to_vec()
                    } else {
                        vec![0.0; len]
                    }
                };
                let lambda_g = read_in(mult_g as *const Number, m_us);
                let z_l = read_in(mult_x_L as *const Number, n_us);
                let z_u = read_in(mult_x_U as *const Number, n_us);
                // SQP packs the bound multipliers signed, as
                // `lambda_x = z_l − z_u` (see `sqp::warm_start`). All three
                // stay in the caller's space (`g` order, unscaled, full `n`);
                // `set_sqp_warm_start` maps them into the algorithm's.
                let lambda_x = z_l.iter().zip(&z_u).map(|(l, u)| l - u).collect();
                info.app
                    .set_sqp_warm_start(pounce_algorithm::sqp::SqpIterates {
                        x: initial_x.clone(),
                        lambda_g,
                        lambda_x,
                        working: Some(working),
                    });
            }

            let (lower_inf, upper_inf, zero_fixed_grad_lag) =
                bridge_violation_options(info.app.options());
            let bridge = Rc::new(RefCell::new(CCallbackTnlp {
                n: info.n,
                m: info.m,
                nele_jac: info.nele_jac,
                nele_hess: info.nele_hess,
                index_style: info.index_style,
                x_l: info.x_l.clone(),
                x_u: info.x_u.clone(),
                g_l: info.g_l.clone(),
                g_u: info.g_u.clone(),
                initial_x,
                start_lambda: mult_g as *const Number,
                start_z_l: mult_x_L as *const Number,
                start_z_u: mult_x_U as *const Number,
                eval_f: info.eval_f,
                eval_grad_f: info.eval_grad_f,
                eval_g: info.eval_g,
                eval_jac_g: info.eval_jac_g,
                eval_h: info.eval_h,
                user_data,
                intermediate_cb: info.intermediate_cb,
                user_scaling: info.user_scaling.clone(),
                nonlinear_vars: info.nonlinear_vars.clone(),
                lower_inf,
                upper_inf,
                zero_fixed_grad_lag,
                final_status: None,
                final_x: vec![0.0; n_us],
                final_z_l: vec![0.0; n_us],
                final_z_u: vec![0.0; n_us],
                final_g: vec![0.0; m_us],
                final_lambda: vec![0.0; m_us],
                final_obj: 0.0,
            }));

            // Wire the restoration phase fresh for this solve. Without it, any
            // line-search failure surfaces as `RestorationFailure` instead of
            // falling back into the ℓ1-feasibility sub-IPM — exactly what the
            // CLI driver does. Re-wire per `IpoptSolve` to stay correct across
            // repeated solves on the same `IpoptProblem`. The feral config is
            // snapshot from the now-fully-populated options so `feral_*`
            // overrides flow into the restoration sub-IPM too. Use the multi-pass
            // provider so the ℓ₁ wrapper / auto-fallback don't panic on the
            // second inner solve (pounce#10 Phase 3 / pounce#24).
            let feral_cfg = feral_config_from_options(info.app.options());
            // The `ma57_*` options under the `"resto."` prefix — dead until
            // gh#825, because nothing threaded any MA57 config into a factory.
            let ma57_cfg = ma57_config_from_options(info.app.options(), "resto.");
            let bff_mint = move || -> InnerBackendFactoryFactory {
                let feral_cfg = feral_cfg.clone();
                let ma57_cfg = ma57_cfg.clone();
                Box::new(move || default_backend_factory(feral_cfg.clone(), ma57_cfg.clone()))
            };
            let resto_provider = make_default_restoration_factory_provider(
                RestoAlgorithmBuilder::new(),
                info.app.algorithm_builder_from_options(),
                bff_mint,
            );
            info.app.set_restoration_factory_provider(resto_provider);

            let bridge_for_solve: Rc<RefCell<dyn TNLP>> = bridge.clone();
            // The run-ending `EXIT:` / `POUNCE <version>:` verdict belongs to the
            // whole run, not to each attempt. Deferred from here through the
            // second-opinion ladder below, which releases it and prints it once
            // with the status that actually ships. Without this, every retry
            // driver's attempt printed its own verdict and a run that recovered
            // reported a mid-run one that read as the final answer.
            info.app.defer_end_verdict();
            // Declared complementarity (gh#1147): the driver chooses the
            // formulation, runs the lowered solves and certifies the answer,
            // as in the CLI and Python. It replaces the single solve and the
            // second-opinion ladder, which both assume one solve of one model,
            // and forwards the reported point to the bridge's
            // `finalize_solution` exactly once, so the copy-back below is the
            // same for both paths.
            let (status, statistics, mpcc, second_opinion) = if !info.complementarity.is_empty() {
                let narrate =
                    pounce_algorithm::second_opinion::narration_is_wanted(info.app.options());
                let result = pounce_restoration::mpcc_driver::solve_mpcc(
                    &mut info.app,
                    bridge_for_solve,
                    info.complementarity.to_vec(),
                    &mut |line| {
                        if narrate {
                            eprintln!("{line}");
                        }
                    },
                );
                let out = match result {
                    Ok(out) => out,
                    // Unreachable from C: the only `Err` is `MpccTnlp::with_lift`
                    // refusing the pairs, and the stored set passed the same
                    // validator against the same bounds at declaration. Kept
                    // as a refusal rather than an assumption.
                    Err(e) => {
                        if narrate {
                            eprintln!(
                                "pounce: cannot solve this model's complementarity constraints: {e}"
                            );
                        }
                        let status = ApplicationReturnStatus::InvalidProblemDefinition;
                        if info.app.release_end_verdict() {
                            info.app.print_end_verdict(status);
                        }
                        return status as Index;
                    }
                };
                if narrate {
                    eprintln!(
                        "{}",
                        pounce_algorithm::mpcc::describe_outcome(
                            out.reported,
                            out.solves.len(),
                            out.total_iterations,
                            out.max_abs_product,
                            out.certificate.as_ref(),
                        )
                    );
                }
                if info.app.release_end_verdict() {
                    info.app.print_end_verdict(out.status);
                }
                (out.status, out.statistics.clone(), Some(out), None)
            } else {
                // The path without pairs, unchanged: one solve, then the ladder.
                let status = info.app.optimize_tnlp(bridge_for_solve);
                let stats = info.app.statistics();
                // Second-opinion ladder, on by default as it is in the CLI and the
                // Python frontend: an `Infeasible_Problem_Detected` or
                // `Invalid_Number_Detected` is re-solved along up to three
                // deliberately different trajectories and a re-solve is promoted
                // only if it converges. A converged solve pays nothing — the
                // ladder reads the status and returns. The three `*_retry`
                // options turn individual rungs off.
                //
                // Narration goes to stderr, where the solver's own banners already
                // go -- but gated on `print_level >= 1`. This crate is the Ipopt
                // drop-in, so `print_level=0 sb=yes` is a caller asking for
                // silence, and eight unexpected `pounce:` lines on a failing
                // solve is exactly what that asks not to happen. The ladder still runs;
                // only the console is quiet.
                let narrate =
                    pounce_algorithm::second_opinion::narration_is_wanted(info.app.options());
                let ladder = run_second_opinion_ladder(
                    &mut info.app,
                    bridge.clone() as Rc<RefCell<dyn TNLP>>,
                    status,
                    stats,
                    &mut |line| {
                        if narrate {
                            eprintln!("{line}");
                        }
                    },
                );
                (ladder.status, ladder.statistics.clone(), None, Some(ladder))
            };
            let bridge_ref = bridge.borrow();
            info.last_solve = Some(LastSolve {
                stats: statistics,
                status,
                linear_solver: info.app.linear_solver_summary(),
                final_x: bridge_ref.final_x.clone(),
                final_lambda: bridge_ref.final_lambda.clone(),
                final_obj: bridge_ref.final_obj,
                mpcc,
                second_opinion,
            });
            if !x.is_null() && n_us > 0 {
                std::ptr::copy_nonoverlapping(bridge_ref.final_x.as_ptr(), x, n_us);
            }
            if !g.is_null() && m_us > 0 {
                std::ptr::copy_nonoverlapping(bridge_ref.final_g.as_ptr(), g, m_us);
            }
            if !obj_val.is_null() {
                *obj_val = bridge_ref.final_obj;
            }
            if !mult_g.is_null() && m_us > 0 {
                std::ptr::copy_nonoverlapping(bridge_ref.final_lambda.as_ptr(), mult_g, m_us);
            }
            if !mult_x_L.is_null() && n_us > 0 {
                std::ptr::copy_nonoverlapping(bridge_ref.final_z_l.as_ptr(), mult_x_L, n_us);
            }
            if !mult_x_U.is_null() && n_us > 0 {
                std::ptr::copy_nonoverlapping(bridge_ref.final_z_u.as_ptr(), mult_x_U, n_us);
            }
            status as Index
        })
    }
}

/// Port of `SetIntermediateCallback`.
///
/// # Safety
///
/// `ipopt_problem` must be valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn SetIntermediateCallback(
    ipopt_problem: IpoptProblem,
    intermediate_cb: Option<Intermediate_CB>,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        info.intermediate_cb = intermediate_cb;
        TRUE
    }
}

/// Port of `IpStdCInterface.cpp:GetIpoptCurrentIterate` (Ipopt 3.14+).
/// Designed to be called from inside an intermediate callback to
/// inspect `x`, the bound multipliers `z_L/z_U`, the constraint values
/// `g`, and the constraint multipliers `lambda` at the current
/// iterate.
///
/// All output buffers are optional — pass NULL to skip. `n` and `m`
/// must match the dimensions the problem was created with; mismatched
/// sizes cause the function to return `FALSE` without writing.
///
/// `scaled` keeps upstream's meaning (`TNLP::get_curr_iterate`, Ipopt
/// 3.14 `IpTNLP.cpp`), on both the interior-point and the active-set SQP
/// arm:
///
/// * `FALSE` — the user TNLP's unscaled space, the units `IpoptSolve`
///   writes back: objective, constraint and per-variable
///   (`SetIpoptProblemScaling` `x_scaling`) scaling all undone.
/// * `TRUE` — the algorithm's scaled space in the TNLP's shape: `x̃ = d ⊙ x`
///   (a fixed variable at its own value, as upstream's `ResortX` writes
///   it), `z̃ = obj·z/d` (at a fixed variable `obj·z`, `z_L`/`z_U` swapped
///   when `obj < 0`, upstream's manual rescale of `ResortBoundMultipliers`),
///   `g̃ = s ⊙ g` (row factor; equality right-hand sides scaled too) and
///   `λ̃ = obj·λ/s` ([`pounce_nlp::live_iterate::scaled_iterate`]). With
///   presolve on, the scaled values of the problem the algorithm solved,
///   lifted to the user's shape like the unscaled ones: a column or row the
///   algorithm holds carries its factor, one presolve removed carries
///   factor `1` (a multiplier there still carries `obj`).
///
/// Both arms answer from the iterate the algorithm materialises before
/// each fire ([`pounce_algorithm::intermediate::UserIterate`]), built by
/// the conversions `finalize_solution` applies — so at the last fire this
/// reads what `IpoptSolve` writes back. That includes the bound
/// multipliers of fixed variables, recovered from `∇f + Jᵀλ` as upstream's
/// `TNLPAdapter::ResortBoundMultipliers` does (not under
/// `fixed_variable_treatment=make_parameter_nodual`), and, with presolve on,
/// the rows and columns it removed.
///
/// Returns `FALSE` when called outside an active intermediate
/// callback (no live iterate to inspect).
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. Each output buffer,
/// when non-NULL, must hold at least the declared length.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptCurrentIterate(
    ipopt_problem: IpoptProblem,
    scaled: Bool,
    n: Index,
    x: *mut Number,
    z_l: *mut Number,
    z_u: *mut Number,
    m: Index,
    g: *mut Number,
    lambda: *mut Number,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        // During a complementarity solve the algorithm's iterate is the
        // lowered model's, not the caller's (gh#1147): no data, whatever
        // the request shape. Checked before the handle is read.
        if in_lowered_solve() {
            return FALSE;
        }
        let info = &*ipopt_problem;
        if n != info.n || m != info.m {
            return FALSE;
        }
        // Active-set SQP arm (gh#1015): no `IpoptData`/`IpoptCq`, so the
        // callback window carries a materialised user-space iterate instead.
        if let Some(r) = ip_intermediate::with_current_user_iterate(|it| {
            let scaled_it;
            let it = if scaled != FALSE {
                scaled_it = pounce_nlp::live_iterate::scaled_iterate(it);
                &scaled_it
            } else {
                it
            };
            let n_us = n as usize;
            let m_us = m as usize;
            let copy = |src: &[Number], dst: *mut Number, len: usize| -> bool {
                if dst.is_null() || len == 0 {
                    return true;
                }
                if src.len() != len {
                    return false;
                }
                std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
                true
            };
            copy(&it.x, x, n_us)
                && copy(&it.z_l, z_l, n_us)
                && copy(&it.z_u, z_u, n_us)
                && copy(&it.g, g, m_us)
                && copy(&it.lambda, lambda, m_us)
        }) {
            return if r { TRUE } else { FALSE };
        }
        let result = ip_intermediate::with_current(|ctx| {
            // Snapshot the iterate handles and release the `data` borrow
            // before touching `cq`: several `IpoptCq` accessors
            // (`curr_c`, `curr_d`, …) evaluate through the NLP and take
            // `nlp.borrow_mut()` internally, so no `nlp`/`data` borrow may
            // be alive across them. Holding one here panicked
            // ("RefCell already borrowed") on every `g != NULL` call, and
            // a panic across this `extern "C"` boundary aborts the
            // process rather than returning `FALSE`.
            let curr = {
                let data = ctx.data.borrow();
                match data.curr.as_ref() {
                    Some(curr) => curr.clone(),
                    None => return false,
                }
            };
            let n_us = n as usize;
            let m_us = m as usize;
            // Per-variable `user-scaling` substitutes `x̃ = d ⊙ x` in a
            // `ScalingTnlp` below the NLP, so the iterate lifted here is
            // `x̃` / `z̃`. `finalize_solution` undoes that on the way out;
            // so must this, or the callback reads coordinates the user's
            // model never had. The multipliers go through the
            // `finalize_solution_*` lifts, not `pack_*_for_user`, for the
            // same reason: only those divide out `obj_scale_factor`, so a
            // solve with objective scaling (user or gradient-based) read
            // `z` and `λ` that many times too large here — the same
            // convention the SQP arm's iterate and `IpoptSolve` use.
            let d = ctx.nlp.borrow().variable_scaling();
            let d = d.as_deref();
            if !x.is_null() && n_us > 0 {
                let mut full_x = ctx.nlp.borrow().lift_x_to_full(&*curr.x);
                if full_x.len() != n_us {
                    return false;
                }
                pounce_nlp::scaling_tnlp::unscale_iterate(d, &mut full_x, &mut [], &mut []);
                std::ptr::copy_nonoverlapping(full_x.as_ptr(), x, n_us);
            }
            if !z_l.is_null() && n_us > 0 {
                let mut full = ctx.nlp.borrow().finalize_solution_z_l(&*curr.z_l);
                if full.len() != n_us {
                    return false;
                }
                pounce_nlp::scaling_tnlp::unscale_iterate(d, &mut [], &mut full, &mut []);
                std::ptr::copy_nonoverlapping(full.as_ptr(), z_l, n_us);
            }
            if !z_u.is_null() && n_us > 0 {
                let mut full = ctx.nlp.borrow().finalize_solution_z_u(&*curr.z_u);
                if full.len() != n_us {
                    return false;
                }
                pounce_nlp::scaling_tnlp::unscale_iterate(d, &mut [], &mut [], &mut full);
                std::ptr::copy_nonoverlapping(full.as_ptr(), z_u, n_us);
            }
            if !g.is_null() && m_us > 0 {
                // `curr_c` / `curr_d` re-enter the NLP mutably: evaluate
                // them first, *then* borrow `nlp` to pack the result.
                let (c, d) = {
                    let cq = ctx.cq.borrow();
                    (cq.curr_c(), cq.curr_d())
                };
                let full = ctx.nlp.borrow().pack_g_for_user(&*c, &*d);
                if full.len() != m_us {
                    return false;
                }
                std::ptr::copy_nonoverlapping(full.as_ptr(), g, m_us);
            }
            if !lambda.is_null() && m_us > 0 {
                let full = ctx
                    .nlp
                    .borrow()
                    .finalize_solution_lambda(&*curr.y_c, &*curr.y_d);
                if full.len() != m_us {
                    return false;
                }
                std::ptr::copy_nonoverlapping(full.as_ptr(), lambda, m_us);
            }
            true
        });
        if result.unwrap_or(false) { TRUE } else { FALSE }
    }
}

/// Port of `IpStdCInterface.cpp:GetIpoptCurrentViolations` (Ipopt 3.14+).
/// Same contract as [`GetIpoptCurrentIterate`]; returns `FALSE` when
/// called outside an active intermediate callback.
///
/// `scaled` keeps upstream's meaning (`TNLP::get_curr_violations`):
///
/// * `FALSE` — the user's problem, unscaled: objective, constraint and
///   per-variable scaling undone, full `n` with fixed variables, rows in
///   `g` order. Computed from the live iterate [`GetIpoptCurrentIterate`]
///   reads (so with presolve on, the user's own rows and columns) against
///   the declared bounds: `x_L_violation = max(0, x_L − x)`,
///   `compl_x_L = (x − x_L^alg)·z_L` with `x_L^alg` the bound the
///   algorithm's slack is measured to (declared, widened by
///   `bound_relax_factor`: upstream's `curr_compl_x_L / obj`, except under
///   per-variable user scaling, where pounce relaxes in the scaled frame and
///   Ipopt in the unscaled one), `grad_lag_x = ∇f + Jᵀλ − z_L + z_U`
///   (`0` at fixed variables, as upstream's `ResortX` leaves them; `∇f` and
///   `J` come from this problem's `eval_grad_f` / `eval_jac_g`, called only
///   when `grad_lag_x` is requested), per-row violation `|g − g_L|` /
///   `max(0, g_L − g, g − g_U)` and `compl_g` with upstream's signs. Both arms.
/// * `TRUE` — upstream's `get_curr_violations(scaled = true)`: the same
///   quantities in the algorithm's scaled space, each a fixed factor of its
///   unscaled counterpart ([`pounce_nlp::live_iterate::scale_violations`]):
///   bound violations `× d`, complementarities `× obj`, `grad_lag_x
///   × obj/d`, row violations `× s` — the factors `GetIpoptCurrentIterate`
///   (`scaled = TRUE`) applies. Both arms (the SQP arm's scaled space is
///   `d` and the `obj_scaling_factor` option: it runs no other scaling),
///   and under presolve, where a removed column or row carries factor 1.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. Each output buffer,
/// when non-NULL, must hold at least the declared length.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptCurrentViolations(
    ipopt_problem: IpoptProblem,
    scaled: Bool,
    n: Index,
    x_l_violation: *mut Number,
    x_u_violation: *mut Number,
    compl_x_l: *mut Number,
    compl_x_u: *mut Number,
    grad_lag_x: *mut Number,
    m: Index,
    nlp_constraint_violation: *mut Number,
    compl_g: *mut Number,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        // During a complementarity solve the algorithm's iterate is the
        // lowered model's, not the caller's (gh#1147): no data, whatever
        // the request shape. Checked before the handle is read.
        if in_lowered_solve() {
            return FALSE;
        }
        let info = &*ipopt_problem;
        if n != info.n || m != info.m {
            return FALSE;
        }
        let n_us = n as usize;
        let m_us = m as usize;
        let Some(it) = ip_intermediate::with_current_user_iterate(|it| it.clone()) else {
            return FALSE;
        };
        let bridge = CURRENT_BRIDGE.with(|c| c.get());
        if bridge.is_null() {
            return FALSE;
        }
        let bridge = &*bridge;
        if it.x.len() != n_us
            || it.z_l.len() != n_us
            || it.z_u.len() != n_us
            || it.g.len() != m_us
            || it.lambda.len() != m_us
        {
            return FALSE;
        }
        let grad_lag = if grad_lag_x.is_null() || n_us == 0 {
            None
        } else if it.grad_lag_x.len() == n_us {
            // The algorithm's own, from the evaluations it made: no
            // `eval_grad_f` / `eval_jac_g` call for it.
            Some(it.grad_lag_x.clone())
        } else {
            match bridge.user_grad_lag(&it) {
                Some(g) => Some(g),
                None => return FALSE,
            }
        };
        let bounds = pounce_nlp::live_iterate::DeclaredBounds {
            x_l: &bridge.x_l,
            x_u: &bridge.x_u,
            g_l: &bridge.g_l,
            g_u: &bridge.g_u,
            lower_inf: bridge.lower_inf,
            upper_inf: bridge.upper_inf,
        };
        let violations = Some(pounce_nlp::live_iterate::current_violations(
            &it,
            &bounds,
            grad_lag,
            bridge.zero_fixed_grad_lag,
            scaled != FALSE,
        ));
        let Some(v) = violations else {
            return FALSE;
        };
        let copy = |src: &[Number], dst: *mut Number, len: usize| -> bool {
            if dst.is_null() || len == 0 {
                return true;
            }
            if src.len() != len {
                return false;
            }
            std::ptr::copy_nonoverlapping(src.as_ptr(), dst, len);
            true
        };
        let ok = copy(&v.x_l_violation, x_l_violation, n_us)
            && copy(&v.x_u_violation, x_u_violation, n_us)
            && copy(&v.compl_x_l, compl_x_l, n_us)
            && copy(&v.compl_x_u, compl_x_u, n_us)
            && copy(&v.grad_lag_x, grad_lag_x, n_us)
            && copy(&v.constraint_violation, nlp_constraint_violation, m_us)
            && copy(&v.compl_g, compl_g, m_us);
        if ok { TRUE } else { FALSE }
    }
}

/// Port of `IpStdCInterface.cpp:GetIpoptVersion` (Ipopt 3.14.18+).
/// Writes the pounce crate's `major.minor.patch` into the buffers.
/// Any pointer may be NULL to skip that component.
///
/// # Safety
///
/// Each non-NULL pointer must point at a writable `int`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptVersion(
    major: *mut c_int,
    minor: *mut c_int,
    release: *mut c_int,
) {
    unsafe {
        // Read from Cargo at compile time so the symbol always matches the
        // shipped binary. `unwrap_or(0)` keeps the function infallible if a
        // component is missing from the manifest (shouldn't happen in
        // practice — workspace manifest requires SemVer triples).
        let (mj, mn, pt) = parse_pkg_version(env!("CARGO_PKG_VERSION"));
        if !major.is_null() {
            *major = mj;
        }
        if !minor.is_null() {
            *minor = mn;
        }
        if !release.is_null() {
            *release = pt;
        }
    }
}

fn parse_pkg_version(v: &str) -> (c_int, c_int, c_int) {
    let mut it = v.split('.').map(|s| s.parse::<c_int>().unwrap_or(0));
    (
        it.next().unwrap_or(0),
        it.next().unwrap_or(0),
        it.next().unwrap_or(0),
    )
}

// ----------------------------------------------------------------------
// Pounce extensions: post-solve statistics accessors.
//
// Convenience accessors not present in upstream Ipopt's C API. Valid
// only after [`IpoptSolve`] has returned; calling them on a
// never-solved problem yields zero. They expose the same
// `SolveStatistics` data the Rust API surfaces via
// [`IpoptApplication::statistics`].
// ----------------------------------------------------------------------

/// Number of IPM iterations in the most recent solve, or `0` if the
/// problem has not been solved yet.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptIterCount(ipopt_problem: IpoptProblem) -> Index {
    unsafe { last_stat(ipopt_problem, |s| s.iteration_count).unwrap_or(0) }
}

/// Wall-clock solve time in seconds for the most recent solve, or
/// `0.0` if the problem has not been solved yet.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptSolveTime(ipopt_problem: IpoptProblem) -> Number {
    unsafe { last_stat(ipopt_problem, |s| s.total_wallclock_time_secs).unwrap_or(0.0) }
}

/// Final primal infeasibility (max constraint violation) for the most
/// recent solve.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptPrimalInf(ipopt_problem: IpoptProblem) -> Number {
    unsafe { last_stat(ipopt_problem, |s| s.final_constr_viol).unwrap_or(0.0) }
}

/// Final dual infeasibility (max gradient-of-Lagrangian norm) for the
/// most recent solve.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptDualInf(ipopt_problem: IpoptProblem) -> Number {
    unsafe { last_stat(ipopt_problem, |s| s.final_dual_inf).unwrap_or(0.0) }
}

/// Final complementarity error for the most recent solve.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetIpoptComplInf(ipopt_problem: IpoptProblem) -> Number {
    unsafe { last_stat(ipopt_problem, |s| s.final_compl).unwrap_or(0.0) }
}

unsafe fn last_stat<T, F>(ipopt_problem: IpoptProblem, f: F) -> Option<T>
where
    F: FnOnce(&SolveStatistics) -> T,
{
    unsafe {
        if ipopt_problem.is_null() {
            return None;
        }
        (*ipopt_problem).last_solve.as_ref().map(|ls| f(&ls.stats))
    }
}

/// Restoration-phase activity in the most recent solve. Each output
/// may be NULL to skip it; all yield zero before the first solve.
///
/// Solve-level, and still worth having now that the intermediate
/// callback also fires from restoration with `alg_mod = 1` (gh#645):
/// these counters answer "how much restoration did this solve do?"
/// without the caller having to install a callback and tally fires,
/// and they are the only source for the inner iteration count and
/// wall time.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. Each
/// non-NULL output pointer must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceRestorationStats(
    ipopt_problem: IpoptProblem,
    calls: *mut Index,
    inner_iters: *mut Index,
    outer_iters: *mut Index,
    wall_secs: *mut Number,
) {
    unsafe {
        let stats = last_stat(ipopt_problem, |s| {
            (
                s.restoration_calls,
                s.restoration_inner_iters,
                s.restoration_outer_iters,
                s.restoration_wall_secs,
            )
        });
        let (c, i, o, w) = stats.unwrap_or((0, 0, 0, 0.0));
        if !calls.is_null() {
            *calls = c;
        }
        if !inner_iters.is_null() {
            *inner_iters = i;
        }
        if !outer_iters.is_null() {
            *outer_iters = o;
        }
        if !wall_secs.is_null() {
            *wall_secs = w;
        }
    }
}

/// Finite-difference Hessian census from the most recent solve. Any
/// pointer may be NULL to skip that component.
///
/// All outputs are left at their "did not run" values on any solve that
/// was not `hessian_approximation=finite-difference`: `pattern_used`
/// is `-1` and the counts are `0`. `pattern_used` is `0` for the
/// declared pattern and `1` for the Jacobian-derived one, and it names
/// what the run **ended up with** — `declared` falls back to `jacobian`
/// when the TNLP declares no Hessian structure, and that fallback is
/// what the number is worth reading for.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. Each
/// non-NULL output pointer must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceFdHessianStats(
    ipopt_problem: IpoptProblem,
    pattern_used: *mut Index,
    nnz: *mut Index,
    n: *mut Index,
    groups: *mut Index,
    rho_max: *mut Index,
    coloring_fell_back: *mut Index,
    objective_clique_widened: *mut Index,
) {
    unsafe {
        let stats = last_stat(ipopt_problem, |s| {
            (
                s.fd_hessian_pattern_used,
                s.fd_hessian_nnz,
                s.fd_hessian_n,
                s.fd_hessian_groups,
                s.fd_hessian_rho_max,
                if s.fd_hessian_coloring_fell_back {
                    1
                } else {
                    0
                },
                if s.fd_hessian_objective_clique_widened {
                    1
                } else {
                    0
                },
            )
        });
        let (p, nz, cols, g, r, f, w) = stats.unwrap_or((-1, 0, 0, 0, 0, 0, 0));
        if !pattern_used.is_null() {
            *pattern_used = p;
        }
        if !nnz.is_null() {
            *nnz = nz;
        }
        if !n.is_null() {
            *n = cols;
        }
        if !groups.is_null() {
            *groups = g;
        }
        if !rho_max.is_null() {
            *rho_max = r;
        }
        if !coloring_fell_back.is_null() {
            *coloring_fell_back = f;
        }
        if !objective_clique_widened.is_null() {
            *objective_clique_widened = w;
        }
    }
}

/// C mirror of [`pounce_linsol::summary::LinearSolverSummary`], laid
/// out for `pounce.h`'s `PounceLinearSolverStats`. Optional fields
/// carry sentinels rather than a discriminant, because a plain struct
/// of scalars is what a C or C++ caller can consume without an
/// accessor per field: `NaN` for absent reals, `-1` for absent counts.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PounceLinearSolverStats {
    pub solver_name: [c_char; 32],
    pub n_factors: Index,
    pub n_pattern_reuse: Index,
    pub n_pattern_changes: Index,
    pub max_fill_ratio: Number,
    pub min_abs_pivot: Number,
    pub max_abs_pivot: Number,
    pub last_inertia_positive: Index,
    pub last_inertia_negative: Index,
    pub last_inertia_zero: Index,
    pub last_nnz_a: Index,
    pub last_nnz_l: Index,
}

/// Post-mortem of the KKT linear solver for the most recent solve.
///
/// Reports what pounce already collects — factorization counts,
/// pattern reuse, fill, pivot range, final inertia. Timings are not
/// among them: pounce does not instrument the analyse / factor /
/// solve phases separately, so there is nothing honest to report and
/// the struct omits them rather than inventing zeros.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `stats`,
/// when non-NULL, must point at a writable `PounceLinearSolverStats`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceLinearSolverStats(
    ipopt_problem: IpoptProblem,
    stats: *mut PounceLinearSolverStats,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() || stats.is_null() {
            return FALSE;
        }
        let Some(summary) = (*ipopt_problem)
            .last_solve
            .as_ref()
            .and_then(|ls| ls.linear_solver.as_ref())
        else {
            return FALSE;
        };
        // Saturate rather than wrap: these are diagnostics, and a
        // count that does not fit an `Index` is better reported as the
        // largest representable one than as a negative.
        let count = |v: u64| Index::try_from(v).unwrap_or(Index::MAX);
        let size = |x: usize| Index::try_from(x).unwrap_or(Index::MAX);
        let opt_size = |v: Option<usize>| v.map_or(-1, size);
        let inertia = summary.last_inertia;
        let mut out = PounceLinearSolverStats {
            solver_name: [0; 32],
            n_factors: count(summary.n_factors),
            n_pattern_reuse: count(summary.n_pattern_reuse),
            n_pattern_changes: count(summary.n_pattern_changes),
            max_fill_ratio: summary.max_fill_ratio.unwrap_or(Number::NAN),
            min_abs_pivot: summary.min_abs_pivot.unwrap_or(Number::NAN),
            max_abs_pivot: summary.max_abs_pivot.unwrap_or(Number::NAN),
            last_inertia_positive: inertia.map_or(-1, |(p, _, _)| size(p)),
            last_inertia_negative: inertia.map_or(-1, |(_, n, _)| size(n)),
            last_inertia_zero: inertia.map_or(-1, |(_, _, z)| size(z)),
            last_nnz_a: opt_size(summary.last_nnz_a),
            last_nnz_l: opt_size(summary.last_nnz_l),
        };
        // Truncate on a byte boundary and always leave room for the
        // NUL; backend names are ASCII identifiers well under 31 bytes,
        // so this is a guard rather than an expected path.
        let name = summary.solver_name.as_bytes();
        let keep = name.len().min(out.solver_name.len() - 1);
        for (slot, b) in out.solver_name.iter_mut().zip(&name[..keep]) {
            *slot = *b as c_char;
        }
        *stats = out;
        TRUE
    }
}

thread_local! {
    /// Option registry for handle-free [`GetPounceOptionType`] queries.
    ///
    /// Built from a throwaway application rather than by re-running the
    /// registration functions here, so it cannot drift from the set a
    /// real problem carries: it *is* that set, by construction.
    static DEFAULT_REGISTRY: Rc<pounce_common::reg_options::RegisteredOptions> =
        Rc::clone(IpoptApplication::new().registered_options());
}

/// Which `AddIpopt*Option` setter a keyword expects.
///
/// Returns a `PounceOptionType` discriminant: 0 when the keyword is not
/// registered in this build, 1 number, 2 integer, 3 string. Lets a
/// caller forwarding options from an untyped source pick the setter
/// from pounce's registry instead of from the value's own type — the
/// difference between `tol: 1` reaching the solver as `1.0` and being
/// refused as an integer.
///
/// `ipopt_problem` may be NULL: option types are a property of the
/// build, not of a problem, and a caller deciding how to forward
/// options may not have created one yet (code generators, in
/// particular, have no handle at all).
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `keyword`,
/// when non-NULL, must be a NUL-terminated C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceOptionType(
    ipopt_problem: IpoptProblem,
    keyword: *const c_char,
) -> c_int {
    unsafe {
        if keyword.is_null() {
            return 0;
        }
        let Ok(name) = CStr::from_ptr(keyword).to_str() else {
            return 0;
        };
        let registered = if ipopt_problem.is_null() {
            DEFAULT_REGISTRY.with(|r| r.get_option(name))
        } else {
            (*ipopt_problem).app.registered_options().get_option(name)
        };
        let Some(opt) = registered else {
            return 0;
        };
        match opt.option_type {
            OptionType::OT_Number => 1,
            OptionType::OT_Integer => 2,
            OptionType::OT_String => 3,
            OptionType::OT_Unknown => 0,
        }
    }
}

// ─────────────────────────────────────────────────────────────
// Pounce extension: SQP working-set warm-start C ABI (§7.2 of
// `docs/research/active-set-sqp-warm-start.md`).
//
// Three new entry points; all backward-compatible additions.
// No existing signature changes — existing cyipopt / JuMP /
// AMPL clients are unaffected.
// ─────────────────────────────────────────────────────────────

fn bound_status_to_int(s: pounce_qp::BoundStatus) -> c_int {
    use pounce_qp::BoundStatus::*;
    match s {
        Inactive => POUNCE_WS_INACTIVE,
        AtLower => POUNCE_WS_AT_LOWER,
        AtUpper => POUNCE_WS_AT_UPPER,
        Fixed => POUNCE_WS_FIXED_OR_EQ,
    }
}

/// Whether a staged variable status is a true claim about bounds `[lo, hi]`:
/// `Fixed` needs `lo == hi`, `AtLower`/`AtUpper` a finite side. Shared by
/// [`IpoptSetWarmStartWorkingSet`] and [`bounds::SetPounceBounds`], which
/// re-checks a staged set against the bounds it would install.
pub(crate) fn bound_status_consistent(s: pounce_qp::BoundStatus, lo: Number, hi: Number) -> bool {
    match s {
        pounce_qp::BoundStatus::Fixed => lo == hi,
        pounce_qp::BoundStatus::AtLower => lo > NLP_LOWER_BOUND_INF,
        pounce_qp::BoundStatus::AtUpper => hi < NLP_UPPER_BOUND_INF,
        pounce_qp::BoundStatus::Inactive => true,
    }
}

/// The row counterpart of [`bound_status_consistent`]: `Equality` needs two
/// equal finite sides.
pub(crate) fn cons_status_consistent(s: pounce_qp::ConsStatus, lo: Number, hi: Number) -> bool {
    let lo_finite = lo > NLP_LOWER_BOUND_INF;
    let hi_finite = hi < NLP_UPPER_BOUND_INF;
    match s {
        pounce_qp::ConsStatus::Equality => lo_finite && hi_finite && lo == hi,
        pounce_qp::ConsStatus::AtLower => lo_finite,
        pounce_qp::ConsStatus::AtUpper => hi_finite,
        pounce_qp::ConsStatus::Inactive => true,
    }
}

fn int_to_bound_status(v: c_int) -> Option<pounce_qp::BoundStatus> {
    use pounce_qp::BoundStatus::*;
    match v {
        POUNCE_WS_INACTIVE => Some(Inactive),
        POUNCE_WS_AT_LOWER => Some(AtLower),
        POUNCE_WS_AT_UPPER => Some(AtUpper),
        POUNCE_WS_FIXED_OR_EQ => Some(Fixed),
        _ => None,
    }
}

fn cons_status_to_int(s: pounce_qp::ConsStatus) -> c_int {
    use pounce_qp::ConsStatus::*;
    match s {
        Inactive => POUNCE_WS_INACTIVE,
        AtLower => POUNCE_WS_AT_LOWER,
        AtUpper => POUNCE_WS_AT_UPPER,
        Equality => POUNCE_WS_FIXED_OR_EQ,
    }
}

fn int_to_cons_status(v: c_int) -> Option<pounce_qp::ConsStatus> {
    use pounce_qp::ConsStatus::*;
    match v {
        POUNCE_WS_INACTIVE => Some(Inactive),
        POUNCE_WS_AT_LOWER => Some(AtLower),
        POUNCE_WS_AT_UPPER => Some(AtUpper),
        POUNCE_WS_FIXED_OR_EQ => Some(Equality),
        _ => None,
    }
}

/// Retrieve the working set produced by the most recent SQP solve
/// (`algorithm = active-set-sqp`). Buffer sizes are `n` for
/// `bound_status_out` and `m` for `cons_status_out`. Pass `NULL`
/// for either to skip that side. Entry `i` is variable `i` / constraint
/// row `i` in the problem's own order (a variable fixed by
/// `x_L == x_U` reads `POUNCE_WS_FIXED_OR_EQ`), the same indexing
/// [`IpoptSetWarmStartWorkingSet`] takes.
///
/// Returns `TRUE` (1) on success, `FALSE` (0) if there is no
/// working set to retrieve (e.g. no SQP solve has run, the IPM
/// path was used, or the very first KKT check declared
/// optimality before solving any QP), if the most recent
/// [`IpoptSolve`] did not complete (refused, or failed before it
/// finished), or if complementarity pairs are declared on the
/// problem; nothing is written then.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem`. Output
/// buffers (when non-NULL) must be sized at least `n` and `m`
/// respectively.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptGetWorkingSet(
    ipopt_problem: IpoptProblem,
    bound_status_out: *mut IpoptBoundStatus,
    cons_status_out: *mut IpoptConsStatus,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &*ipopt_problem;
        // No completed solve (none yet, or the last one was refused or
        // failed before it finished — `IpoptSolve` clears `last_solve` up
        // front), or pairs are declared, or the last solve ran the
        // complementarity driver on the lowered model (gh#1147): no working
        // set over the caller's rows belongs to the handle's current state,
        // and one left over from an earlier SQP solve must not read as if it
        // did.
        let Some(last) = info.last_solve.as_ref() else {
            return FALSE;
        };
        if last.mpcc.is_some() || !info.complementarity.is_empty() {
            return FALSE;
        }
        let ws = match info.app.last_sqp_working_set() {
            Some(w) => w,
            None => return FALSE,
        };
        // `last_sqp_working_set` is already in the caller's index spaces —
        // full `n` (fixed variables read `Fixed`) and `g` row order — so it
        // is copied positionally. This used to rebuild the SQP's
        // equalities-first order from the bounds and permute here, which
        // stopped matching once the application lifted bound statuses to
        // full `n` (gh#986): with any fixed variable the length check
        // below failed and this returned FALSE after a successful solve.
        let n = info.x_l.len();
        let m = info.g_l.len();
        if ws.constraints.len() != m || ws.bounds.len() != n {
            // The stored set does not match this problem's shape. Report
            // nothing rather than something mis-indexed.
            return FALSE;
        }
        if !bound_status_out.is_null() {
            for (i, &s) in ws.bounds.iter().enumerate() {
                *bound_status_out.add(i) = bound_status_to_int(s);
            }
        }
        if !cons_status_out.is_null() {
            for (i, &s) in ws.constraints.iter().enumerate() {
                *cons_status_out.add(i) = cons_status_to_int(s);
            }
        }
        TRUE
    }
}

/// Supply a warm-start working set consumed by the next
/// [`IpoptSolve`] on this problem. Pass `NULL` for either side to
/// cold-start it. The caller-owned buffers are copied; reuse
/// across calls is safe. Indexed like [`IpoptGetWorkingSet`]: entry `i`
/// is variable `i` / constraint row `i` in the problem's own order.
///
/// Returns `TRUE` on success, `FALSE` on (a) NULL problem, (b)
/// an out-of-range status code in one of the buffers, or
/// (c) both inputs NULL (which would equal a no-op
/// — call [`IpoptClearWarmStartWorkingSet`] instead).
///
/// # Safety
///
/// `ipopt_problem` must be valid. `bound_status_in` (when
/// non-NULL) must be sized `n`; `cons_status_in` (when non-NULL)
/// must be sized `m`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptSetWarmStartWorkingSet(
    ipopt_problem: IpoptProblem,
    bound_status_in: *const IpoptBoundStatus,
    cons_status_in: *const IpoptConsStatus,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        if bound_status_in.is_null() && cons_status_in.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        let n = info.n.max(0) as usize;
        let m = info.m.max(0) as usize;
        // The caller indexes by *their* rows and variables, and so does
        // `IpoptApplication::set_sqp_warm_start`: the solve maps the staged
        // set into the SQP's equalities-first, fixed-variables-removed
        // vectors through the problem's own classification, the inverse of
        // what `IpoptGetWorkingSet` reads out. Staged as given.
        // Validation is not just a range check. A status code says
        // where the point sits relative to a bound — but `Fixed` /
        // `Equality`, and `AtLower` / `AtUpper` against an infinite
        // side, additionally assert something about the *problem*:
        // that a variable has `x_l == x_u`, that a row has
        // `b_l == b_u`, that the bound being sat on exists at all.
        // Those are not guesses about the active set, they are claims
        // about the model, and the model is right here to check them
        // against.
        //
        // Accepting them unchecked converted a caller's mistake into a
        // silently wrong answer: `POUNCE_WS_FIXED_OR_EQ` on a variable
        // whose bounds differ pinned it, the solve over-constrained
        // itself, and a *convex* program came back with the wrong
        // optimum — the function having returned TRUE. Rejecting is
        // strictly better: the caller already handles FALSE, and this
        // function already returns it for an out-of-range code, so
        // TRUE reasonably reads as "your working set was accepted".
        let mut bounds = vec![pounce_qp::BoundStatus::Inactive; n];
        if !bound_status_in.is_null() {
            // Validate every entry the caller supplied, including those for
            // fixed variables that the internal problem drops: a wrong
            // claim is worth rejecting whether or not it would be used.
            for i in 0..n {
                let v = *bound_status_in.add(i);
                let Some(s) = int_to_bound_status(v) else {
                    return FALSE;
                };
                if !bound_status_consistent(s, info.x_l[i], info.x_u[i]) {
                    return FALSE;
                }
            }
            for (i, b) in bounds.iter_mut().enumerate() {
                // Already range-checked above.
                if let Some(s) = int_to_bound_status(*bound_status_in.add(i)) {
                    *b = s;
                }
            }
        }
        let mut constraints = vec![pounce_qp::ConsStatus::Inactive; m];
        if !cons_status_in.is_null() {
            for i in 0..m {
                let v = *cons_status_in.add(i);
                let Some(s) = int_to_cons_status(v) else {
                    return FALSE;
                };
                if !cons_status_consistent(s, info.g_l[i], info.g_u[i]) {
                    return FALSE;
                }
            }
            for (i, c) in constraints.iter_mut().enumerate() {
                if let Some(s) = int_to_cons_status(*cons_status_in.add(i)) {
                    *c = s;
                }
            }
        }
        // Stage the working set only. We do *not* know the
        // primal/dual iterate here, and we must not invent one:
        // `SqpAlgorithm::optimize_with_warm_start` treats a supplied
        // `SqpIterates` as *the* starting iterate and never consults
        // `get_starting_x` on that branch, so a placeholder `x` would
        // silently override the `x` buffer the caller hands to
        // `IpoptSolve`. Zeros here restarted every warm solve from
        // the origin — outside the bounds on any problem with
        // `x_l > 0` — and returned `Infeasible_Problem_Detected` at
        // iteration 0 (gh#484). `IpoptSolve` merges this working set
        // with the real starting point instead.
        info.pending_working_set = Some(pounce_qp::WorkingSet {
            bounds,
            constraints,
        });
        TRUE
    }
}

/// Declare which variables enter the problem **nonlinearly** (gh#624).
///
/// This is the C-API face of Ipopt's `TNLP::get_number_of_nonlinear_variables`
/// / `get_list_of_nonlinear_variables` pair, which upstream exposes only
/// to C++ callers. It exists so a frontend that already knows the
/// structure of its model — CasADi's `pass_nonlinear_variables`, an
/// algebraic modeling language, a hand-written driver — can hand that
/// knowledge to pounce.
///
/// Effect is confined to the **limited-memory** Hessian: curvature is
/// approximated over the declared subset only, and the Hessian is
/// exactly zero for every other variable. Exact-Hessian solves ignore
/// the declaration entirely, and so does any solve that never calls
/// this function — the default remains "all variables are nonlinear".
/// The subset takes precedence over the `num_linear_variables` option,
/// matching Ipopt's own ordering.
///
/// `pos_nonlin_vars` holds `num_nonlin_vars` variable indices **in the
/// problem's index style** (the `index_style` passed to
/// [`CreateIpoptProblem`]). The subset may be arbitrary and
/// noncontiguous; order does not matter. Passing `num_nonlin_vars == n`
/// is equivalent to not calling this at all.
///
/// Returns `FALSE` (leaving any previous declaration untouched) on a
/// NULL problem, a negative or oversized count, a NULL array with a
/// positive count, or an index outside the problem's variable range.
///
/// Note the deliberate signature choice: the issue that requested this
/// suggested a `const Bool*` mask, but `Bool` in the Ipopt C API is a
/// C99 `bool`, and a *array* of those would be a per-element
/// data-layout contract that is easy to get wrong from a caller with a
/// different boolean width. The count-plus-index-list shape is the one
/// the TNLP callbacks already use.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
/// `pos_nonlin_vars`, when non-NULL, must point at `num_nonlin_vars`
/// readable `ipindex` values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptSetNonlinearVariables(
    ipopt_problem: IpoptProblem,
    num_nonlin_vars: Index,
    pos_nonlin_vars: *const Index,
) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &mut *ipopt_problem;
        if num_nonlin_vars < 0 || num_nonlin_vars > info.n {
            return FALSE;
        }
        if num_nonlin_vars > 0 && pos_nonlin_vars.is_null() {
            return FALSE;
        }
        let offset = if info.index_style == 1 { 1 } else { 0 };
        let raw = if num_nonlin_vars == 0 {
            &[][..]
        } else {
            std::slice::from_raw_parts(pos_nonlin_vars, num_nonlin_vars as usize)
        };
        // Validate before storing: a half-applied declaration would be
        // worse than a refused one.
        for &p in raw {
            let zero_based = p - offset;
            if zero_based < 0 || zero_based >= info.n {
                return FALSE;
            }
        }
        info.nonlinear_vars = Some(raw.to_vec());
        TRUE
    }
}

/// Drop a subset declared by [`IpoptSetNonlinearVariables`], restoring
/// the default (every variable treated as nonlinear).
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptClearNonlinearVariables(ipopt_problem: IpoptProblem) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        (*ipopt_problem).nonlinear_vars = None;
        TRUE
    }
}

// ---------------------------------------------------------------------------
// Declared complementarity pairs (gh#1147)
// ---------------------------------------------------------------------------

/// The bits [`SetPounceComplementarityPairs`]' `flags` may carry in this
/// version: none.
const KNOWN_PAIR_FLAGS: c_uint = 0;

fn pair_error_code(kind: &PairErrorKind) -> c_int {
    match kind {
        PairErrorKind::OutOfRange => POUNCE_ERR_OUT_OF_RANGE,
        PairErrorKind::VarAlreadyPaired => POUNCE_ERR_VAR_ALREADY_PAIRED,
        PairErrorKind::RowAlreadyPaired => POUNCE_ERR_ROW_ALREADY_PAIRED,
        PairErrorKind::UnsupportedShape => POUNCE_ERR_SHAPE,
    }
}

/// An index in the problem's index style, as a 0-based `usize` when it is
/// in `[0, len)`, else `usize::MAX`, which every caller refuses as out of
/// range. `checked_sub` keeps `i32::MIN` in Fortran
/// style from overflowing.
pub(crate) fn zero_based(p: Index, offset: Index, len: Index) -> usize {
    match p.checked_sub(offset) {
        Some(z) if z >= 0 && z < len => z as usize,
        _ => usize::MAX,
    }
}

/// Replace the declared pairs with `new` (pairs in the problem's index
/// style), validated as a whole and on their own, and stored only if every
/// pair passes. On refusal the declared set is untouched and the error
/// names the refused pair's position in `new`.
///
/// Two passes, in the C API's check order (`errors.rs`): first every
/// pair's argument checks — range, variable not already in the batch, row
/// not already in the batch — then every pair's shape, by
/// [`classify_pair`]. Together they are the checks [`validate_pairs`](pounce_nlp::mpcc::validate_pairs) (the
/// solve's lowering) runs, but check by check over the batch where it goes
/// pair by pair, so a shape fault at pair 0 does not hide an argument
/// fault at pair 1, as in `SetPounceBounds`. `validate_pairs` is left as
/// it is because the lowering shares it.
///
/// O(n + m + P): one flag per variable and row. Fine once per batch; the
/// one-pair path is [`append_pair`].
fn replace_pairs(
    info: &mut IpoptProblemInfo,
    new: &[(Index, Index)],
) -> Result<(), (usize, PairErrorKind)> {
    let offset = if info.index_style == 1 { 1 } else { 0 };
    let candidate: Vec<ComplementarityPair> = new
        .iter()
        .map(|&(row, var)| ComplementarityPair {
            row: zero_based(row, offset, info.m),
            var: zero_based(var, offset, info.n),
        })
        .collect();
    let mut seen_var = vec![false; info.n as usize];
    let mut seen_row = vec![false; info.m as usize];
    for (k, p) in candidate.iter().enumerate() {
        if p.var == usize::MAX || p.row == usize::MAX {
            return Err((k, PairErrorKind::OutOfRange));
        }
        if std::mem::replace(&mut seen_var[p.var], true) {
            return Err((k, PairErrorKind::VarAlreadyPaired));
        }
        if std::mem::replace(&mut seen_row[p.row], true) {
            return Err((k, PairErrorKind::RowAlreadyPaired));
        }
    }
    for (k, p) in candidate.iter().enumerate() {
        if classify_pair(
            info.x_l[p.var],
            info.x_u[p.var],
            info.g_l[p.row],
            info.g_u[p.row],
        )
        .is_none()
        {
            return Err((k, PairErrorKind::UnsupportedShape));
        }
    }
    info.complementarity.replace(candidate);
    Ok(())
}

/// Append one pair `(row, var)`, in the problem's index style, to the
/// declared set, after the checks [`validate_pairs`](pounce_nlp::mpcc::validate_pairs) runs on a pair, in its
/// order: range, variable not in a pair, row not in a pair, a shape
/// [`classify_pair`] accepts. O(1) expected (gh#1147 Stage 2): the stored
/// pairs are not re-validated, because every stored pair passed when it was
/// stored and every change to the bounds re-classifies the pairs it touches
/// ([`bounds`]), and the new pair's variable and row are in no stored pair.
fn append_pair(info: &mut IpoptProblemInfo, row: Index, var: Index) -> Result<(), PairErrorKind> {
    let offset = if info.index_style == 1 { 1 } else { 0 };
    let r = zero_based(row, offset, info.m);
    let v = zero_based(var, offset, info.n);
    if r == usize::MAX || v == usize::MAX {
        return Err(PairErrorKind::OutOfRange);
    }
    if info.complementarity.of_var(v).is_some() {
        return Err(PairErrorKind::VarAlreadyPaired);
    }
    if info.complementarity.of_row(r).is_some() {
        return Err(PairErrorKind::RowAlreadyPaired);
    }
    if classify_pair(info.x_l[v], info.x_u[v], info.g_l[r], info.g_u[r]).is_none() {
        return Err(PairErrorKind::UnsupportedShape);
    }
    info.complementarity
        .push(ComplementarityPair { row: r, var: v });
    Ok(())
}

/// Declare one complementarity pair: constraint row `row` with variable
/// `var`, both **in the problem's index style** (gh#1147). The pair is in
/// POUNCE's native shapes — one-sided, one-sided plus a plain bound, or
/// mixed — exactly as Python's `Problem(complementarity=)` and the `.nl`
/// reader accept, and is checked at once by the same classifier the
/// solve's lowering runs (`pounce_nlp::mpcc::validate_pairs`), against the
/// handle's bounds — those given to [`CreateIpoptProblem`], as
/// [`AddPounceComplementsConstraint`] may have edited them — and the pairs
/// already declared.
///
/// Returns [`POUNCE_OK`] or a negative `POUNCE_ERR_*` code; a refused
/// pair leaves the declared set unchanged. Pairs persist on the handle
/// until [`SetPounceComplementarityPairs`] replaces them or
/// [`ClearPounceComplementarityPairs`] drops them.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn AddPounceComplementarityPair(
    ipopt_problem: IpoptProblem,
    row: Index,
    var: Index,
) -> c_int {
    ffi_guard(POUNCE_ERR_INTERNAL, || unsafe {
        if ipopt_problem.is_null() {
            return POUNCE_ERR_NULL;
        }
        match append_pair(&mut *ipopt_problem, row, var) {
            Ok(()) => POUNCE_OK,
            Err(kind) => pair_error_code(&kind),
        }
    })
}

/// Replace the declared pairs with `n_pairs` pairs `(rows[k], vars[k])`,
/// indices in the problem's index style. All or nothing: the new set is
/// validated as a whole (on its own, not against the pairs it replaces)
/// and stored only if every pair passes; otherwise the previous set stays.
/// `n_pairs == 0` clears the set (the arrays may then be NULL).
///
/// `flags` must be 0. No bit is defined yet: it exists so that a later
/// relaxation (re-validating against the pairs being replaced, last-wins
/// duplicates, ...) can be asked for explicitly rather than change what an
/// existing call does. A bit this library does not define is refused with
/// [`POUNCE_ERR_FLAGS`], so an older library never silently ignores one.
/// Checked after the handle and before the count, as in
/// [`SetPounceBounds`].
///
/// `n_pairs < 0`, or above `min(n, m)` (more pairs than that must repeat a
/// variable or a row), is [`POUNCE_ERR_COUNT`], refused before `rows` and
/// `vars` are read.
///
/// Range and already-paired checks run over the whole batch before any
/// shape check (the shared check order, `errors.rs`).
///
/// `bad_index`, when non-NULL, receives the position in the batch of the
/// first refused pair (for a duplicate, the second occurrence), or `-1`
/// on success and on the errors that concern no single pair
/// ([`POUNCE_ERR_NULL`], [`POUNCE_ERR_FLAGS`], [`POUNCE_ERR_COUNT`]).
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `rows` and
/// `vars`, when non-NULL, must each point at `n_pairs` readable `ipindex`
/// values; `bad_index` must be NULL or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn SetPounceComplementarityPairs(
    ipopt_problem: IpoptProblem,
    n_pairs: Index,
    rows: *const Index,
    vars: *const Index,
    flags: c_uint,
    bad_index: *mut Index,
) -> c_int {
    ffi_guard(POUNCE_ERR_INTERNAL, || unsafe {
        let report = |k: Index| {
            if !bad_index.is_null() {
                *bad_index = k;
            }
        };
        report(-1);
        if ipopt_problem.is_null() {
            return POUNCE_ERR_NULL;
        }
        if flags & !KNOWN_PAIR_FLAGS != 0 {
            return POUNCE_ERR_FLAGS;
        }
        // More pairs than `min(n, m)` must repeat a variable or a row, so it
        // is a count fault, refused before the arrays are read: a garbage
        // count (an uninitialised `n_pairs`) would otherwise size the read
        // and the allocation below, and a failed allocation aborts the
        // process past `ffi_guard`. Same rule as `SetPounceBounds`.
        let max_pairs = (*ipopt_problem).n.min((*ipopt_problem).m);
        if n_pairs < 0 || n_pairs > max_pairs {
            return POUNCE_ERR_COUNT;
        }
        if n_pairs > 0 && (rows.is_null() || vars.is_null()) {
            return POUNCE_ERR_NULL;
        }
        let new: Vec<(Index, Index)> = if n_pairs == 0 {
            Vec::new()
        } else {
            let r = std::slice::from_raw_parts(rows, n_pairs as usize);
            let v = std::slice::from_raw_parts(vars, n_pairs as usize);
            r.iter().copied().zip(v.iter().copied()).collect()
        };
        match replace_pairs(&mut *ipopt_problem, &new) {
            Ok(()) => POUNCE_OK,
            Err((k, kind)) => {
                report(k as Index);
                pair_error_code(&kind)
            }
        }
    })
}

/// Drop every declared complementarity pair. Returns `FALSE` only on a
/// NULL handle.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ClearPounceComplementarityPairs(ipopt_problem: IpoptProblem) -> Bool {
    ffi_guard(FALSE, || unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        (*ipopt_problem).complementarity.clear();
        TRUE
    })
}

/// Number of declared complementarity pairs, or `-1` on a NULL handle.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceComplementarityPairCount(ipopt_problem: IpoptProblem) -> Index {
    ffi_guard(-1, || unsafe {
        if ipopt_problem.is_null() {
            return -1;
        }
        (&*ipopt_problem).complementarity.len() as Index
    })
}

/// Copy the declared pairs, in declaration order and **in the problem's
/// index style**, into `rows` and `vars` (each sized by
/// [`GetPounceComplementarityPairCount`]). Returns `FALSE`, writing
/// nothing, on a NULL handle or a NULL array while pairs are declared;
/// with no pairs it returns `TRUE` and the arrays may be NULL.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `rows` and
/// `vars`, when non-NULL, must each have room for the declared count.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceComplementarityPairs(
    ipopt_problem: IpoptProblem,
    rows: *mut Index,
    vars: *mut Index,
) -> Bool {
    ffi_guard(FALSE, || unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        let info = &*ipopt_problem;
        let k = info.complementarity.len();
        if k == 0 {
            return TRUE;
        }
        if rows.is_null() || vars.is_null() {
            return FALSE;
        }
        let offset = if info.index_style == 1 { 1 } else { 0 };
        let rows = std::slice::from_raw_parts_mut(rows, k);
        let vars = std::slice::from_raw_parts_mut(vars, k);
        for (i, p) in info.complementarity.iter().enumerate() {
            rows[i] = p.row as Index + offset;
            vars[i] = p.var as Index + offset;
        }
        TRUE
    })
}

// ---------------------------------------------------------------------------
// MOI `[F, x] ∈ Complements` semantics (gh#1147)
// ---------------------------------------------------------------------------

/// `x` boxed, `l < u` both finite: a native **mixed** pair was declared;
/// the row's bounds are unchanged (free).
pub const POUNCE_COMPLEMENTS_PAIR_MIXED: c_int = 0;
/// `x >= l` only: the row's lower bound was set to `0` (`F >= 0`) and a
/// native one-sided pair declared.
pub const POUNCE_COMPLEMENTS_PAIR_LOWER: c_int = 1;
/// `x <= u` only: the row's upper bound was set to `0` (`F <= 0`) and a
/// native one-sided pair declared.
pub const POUNCE_COMPLEMENTS_PAIR_UPPER: c_int = 2;
/// `x` free: both row bounds were set to `0` (`F = 0`); no pair.
pub const POUNCE_COMPLEMENTS_ROW_FIXED_NO_PAIR: c_int = 3;
/// `x` fixed (`l == u`): nothing changed, `F` stays free; no pair.
pub const POUNCE_COMPLEMENTS_VAR_FIXED_NO_PAIR: c_int = 4;

pub(crate) fn complements_row(xl: Number, xu: Number) -> Option<ComplementsRow> {
    if xl.is_nan() || xu.is_nan() {
        return None;
    }
    match (xl > NLP_LOWER_BOUND_INF, xu < NLP_UPPER_BOUND_INF) {
        (true, true) if xl < xu => Some(ComplementsRow::Mixed),
        (true, true) if xl == xu => Some(ComplementsRow::VarFixed),
        (true, true) => None,
        (true, false) => Some(ComplementsRow::Lower),
        (false, true) => Some(ComplementsRow::Upper),
        (false, false) => Some(ComplementsRow::RowFixed),
    }
}

impl ComplementsRow {
    /// The row bounds the table gives a free row, and whether it declares a
    /// pair.
    pub(crate) fn row_bounds(self, gl: Number, gu: Number) -> (Number, Number, bool) {
        match self {
            ComplementsRow::Mixed => (gl, gu, true),
            ComplementsRow::Lower => (0.0, gu, true),
            ComplementsRow::Upper => (gl, 0.0, true),
            ComplementsRow::RowFixed => (0.0, 0.0, false),
            ComplementsRow::VarFixed => (gl, gu, false),
        }
    }

    fn code(self) -> c_int {
        match self {
            ComplementsRow::Mixed => POUNCE_COMPLEMENTS_PAIR_MIXED,
            ComplementsRow::Lower => POUNCE_COMPLEMENTS_PAIR_LOWER,
            ComplementsRow::Upper => POUNCE_COMPLEMENTS_PAIR_UPPER,
            ComplementsRow::RowFixed => POUNCE_COMPLEMENTS_ROW_FIXED_NO_PAIR,
            ComplementsRow::VarFixed => POUNCE_COMPLEMENTS_VAR_FIXED_NO_PAIR,
        }
    }

    /// The native shape the edited bounds must classify as (pair rows).
    fn shape_matches(self, shape: Option<PairShape>) -> bool {
        matches!(
            (self, shape),
            (ComplementsRow::Mixed, Some(PairShape::Mixed { .. }))
                | (ComplementsRow::Lower, Some(PairShape::OneSided { .. }))
                | (ComplementsRow::Upper, Some(PairShape::OneSided { .. }))
        )
    }
}

fn add_complements(info: &mut IpoptProblemInfo, row: Index, var: Index) -> c_int {
    let offset = if info.index_style == 1 { 1 } else { 0 };
    let (r, v) = (
        zero_based(row, offset, info.m),
        zero_based(var, offset, info.n),
    );
    if r == usize::MAX || v == usize::MAX {
        return POUNCE_ERR_OUT_OF_RANGE;
    }
    // Argument checks before semantic ones (the C API's check order,
    // `errors.rs`): a row an earlier call already used reads as already
    // paired, not as "not free" because that call bounded it.
    if info.complementarity.of_var(v).is_some() || info.complements_used.of_var(v).is_some() {
        return POUNCE_ERR_VAR_ALREADY_PAIRED;
    }
    if info.complementarity.of_row(r).is_some() || info.complements_used.of_row(r).is_some() {
        return POUNCE_ERR_ROW_ALREADY_PAIRED;
    }
    let (gl, gu) = (info.g_l[r], info.g_u[r]);
    if !(gl <= NLP_LOWER_BOUND_INF && gu >= NLP_UPPER_BOUND_INF) {
        return POUNCE_ERR_ROW_NOT_FREE;
    }
    let Some(table_row) = complements_row(info.x_l[v], info.x_u[v]) else {
        return POUNCE_ERR_VAR_BOUNDS;
    };
    let (new_gl, new_gu, declares) = table_row.row_bounds(gl, gu);
    debug_assert!(
        !declares
            || table_row.shape_matches(classify_pair(info.x_l[v], info.x_u[v], new_gl, new_gu)),
        "MOI table row {table_row:?} edits to a bound pair that is not its native shape"
    );
    // Tentative edit, then declare the pair (if any) through the path every
    // one-pair declaration takes. The row and the variable are in no pair,
    // so only the shape check can refuse, and the table row's edit makes
    // that shape native by construction; if it does refuse, the row is
    // restored rather than left half-edited.
    info.g_l[r] = new_gl;
    info.g_u[r] = new_gu;
    if declares && append_pair(info, row, var).is_err() {
        info.g_l[r] = gl;
        info.g_u[r] = gu;
        return POUNCE_ERR_INTERNAL;
    }
    info.complements_used.push(ComplementsUse {
        row: r,
        var: v,
        table: table_row,
        user_gl: gl,
        user_gu: gu,
    });
    table_row.code()
}

/// Declare MOI's `[F, x] ∈ Complements` for constraint row `row` (`F`) and
/// variable `var` (`x`), both **in the problem's index style** (gh#1147).
///
/// MOI writes `F` as a free function and reads the sign it must have off
/// `x`'s bounds; POUNCE's native pairs read both sides' signs off their
/// bounds. This helper transcribes one into the other **by editing the
/// handle's copy of the row bounds**, then declares the native pair, as
/// the table says (bounds at or beyond `±1e19` are infinite):
///
/// | `x` bounds         | row edit            | pair            | returns |
/// |--------------------|---------------------|-----------------|---------|
/// | `l < u`, finite    | none                | native mixed    | [`POUNCE_COMPLEMENTS_PAIR_MIXED`] |
/// | `l` only           | `g_L = 0` (`F ≥ 0`) | one-sided       | [`POUNCE_COMPLEMENTS_PAIR_LOWER`] |
/// | `u` only           | `g_U = 0` (`F ≤ 0`) | one-sided       | [`POUNCE_COMPLEMENTS_PAIR_UPPER`] |
/// | free               | `g_L = g_U = 0`     | none (`F = 0`)  | [`POUNCE_COMPLEMENTS_ROW_FIXED_NO_PAIR`] |
/// | `l == u`           | none (`F` free)     | none            | [`POUNCE_COMPLEMENTS_VAR_FIXED_NO_PAIR`] |
///
/// The row must be free (else [`POUNCE_ERR_ROW_NOT_FREE`]:
/// use [`AddPounceComplementarityPair`] for a row that already has a
/// side). Checks, in order: NULL handle, range, variable then row not
/// already used (by a declared pair or by an earlier accepted call of this
/// helper), row free, the variable's bounds neither NaN nor crossed. A
/// refused call changes nothing. Bound edits are permanent on the handle:
/// [`ClearPounceComplementarityPairs`] and
/// [`SetPounceComplementarityPairs`] drop pairs, not edits.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn AddPounceComplementsConstraint(
    ipopt_problem: IpoptProblem,
    row: Index,
    var: Index,
) -> c_int {
    ffi_guard(POUNCE_ERR_INTERNAL, || unsafe {
        if ipopt_problem.is_null() {
            return POUNCE_ERR_NULL;
        }
        add_complements(&mut *ipopt_problem, row, var)
    })
}

// ---------------------------------------------------------------------------
// Complementarity outcome getters (gh#1147)
//
// What the complementarity driver did on the most recent `IpoptSolve`: the
// same fields, through the same encodings, as the solve report's
// `complementarity` block (`MpccOutcome::report_info`) and Python's
// `info["complementarity"]`. Every getter answers "nothing" (`FALSE` / `-1`)
// when the most recent solve did not run the driver: no solve yet, a solve
// without pairs, a refused or failed solve, or a session solve.
// ---------------------------------------------------------------------------

/// `certificate_class`: strongly stationary.
pub const POUNCE_CC_CLASS_S: c_int = 0;
/// `certificate_class`: weakly stationary only.
pub const POUNCE_CC_CLASS_W: c_int = 1;
/// `certificate_class`: not a stationary point of the model.
pub const POUNCE_CC_CLASS_NONE: c_int = 2;
/// `certificate_class`: not determined (the multiplier set is too large to
/// search).
pub const POUNCE_CC_CLASS_NOT_SEARCHED: c_int = 3;
/// `certificate_class`: no certificate (the model could not be evaluated at
/// the reported point).
pub const POUNCE_CC_CLASS_ABSENT: c_int = -1;

/// `reported`: a formulation answered.
pub const POUNCE_CC_REPORTED_ANSWER: c_int = 0;
/// `reported`: a weakly stationary point, reported when none answered.
pub const POUNCE_CC_REPORTED_WEAK_FALLBACK: c_int = 1;
/// `reported`: a converged point with every product in tolerance, no
/// stationarity certified.
pub const POUNCE_CC_REPORTED_FEASIBLE_UNCERTIFIED: c_int = 2;
/// `reported`: no feasible point; the exact-product solve's verdict.
pub const POUNCE_CC_REPORTED_VERDICT: c_int = 3;

/// `b_verdict`: B-stationary.
pub const POUNCE_CC_B_VERDICT_B: c_int = 0;
/// `b_verdict`: a branch descends.
pub const POUNCE_CC_B_VERDICT_NOT_B: c_int = 1;
/// `b_verdict`: not decided (the reason is `POUNCE_CC_TEXT_B_REASON`).
pub const POUNCE_CC_B_VERDICT_NOT_CHECKED: c_int = 2;
/// `b_verdict`: the check did not run.
pub const POUNCE_CC_B_VERDICT_ABSENT: c_int = -1;

/// [`GetPounceComplementarityText`]: the driver's one-line account.
pub const POUNCE_CC_TEXT_SUMMARY: c_int = 0;
/// [`GetPounceComplementarityText`]: why the polish's point was not taken.
pub const POUNCE_CC_TEXT_POLISH_REASON: c_int = 1;
/// [`GetPounceComplementarityText`]: why the B-stationarity check was not
/// decided.
pub const POUNCE_CC_TEXT_B_REASON: c_int = 2;

/// C mirror of the driver's [`MpccOutcome`](pounce_restoration::mpcc_driver::MpccOutcome)
/// for `pounce.h`'s `PounceComplementarityStats`. Field order is the ABI
/// (Pounce.jl mirrors structs field for field); `tests/c_examples_build_and_run.rs`
/// holds every offset to the C compiler's. Sentinels instead of
/// discriminants: `NaN` for a real that was not measured (or is not
/// finite, as the report's `null`), `-1` for a count or flag whose record
/// is absent.
///
/// Extensible (see `ExtensibleOut` in this crate): `struct_size` first, set by the
/// caller to `sizeof(PounceComplementarityStats)`; fields are only ever
/// appended.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PounceComplementarityStats {
    pub struct_size: Index,
    pub strategy: [c_char; 16],
    pub reported: Index,
    pub accepted_by: [c_char; 32],
    pub fallback: [c_char; 32],
    pub n_solves: Index,
    pub total_iterations: Index,
    pub max_abs_product: Number,
    pub certificate_class: Index,
    pub n_pairs: Index,
    pub n_biactive: Index,
    pub n_neither: Index,
    pub multipliers_unique: Index,
    pub residual: Number,
    pub resid_tol: Number,
    pub tight: Index,
    pub feasible: Index,
    pub primal_violation: Number,
    pub b_verdict: Index,
    pub b_n_biactive: Index,
    pub b_branches_solved: Index,
    pub b_enumerated: Index,
    pub escapes: Index,
    pub lifted: Index,
    pub natural_residual: Number,
    pub polish_ran: Index,
    pub polish_taken: Index,
    pub polish_residual_before: Number,
    pub polish_residual_after: Number,
    pub polish_threshold: Number,
}

/// C mirror of one [`MpccSolveRecord`](pounce_restoration::mpcc_driver::MpccSolveRecord),
/// for `pounce.h`'s `PounceComplementaritySolve`. Extensible, like
/// [`PounceComplementarityStats`].
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PounceComplementaritySolve {
    pub struct_size: Index,
    pub stage: [c_char; 32],
    pub relaxed: Index,
    pub tau: Number,
    pub status: Index,
    pub iterations: Index,
    pub max_abs_product: Number,
    pub seconds: Number,
}

// SAFETY: both are `#[repr(C)]` with `struct_size: Index` first.
unsafe impl ExtensibleOut for PounceComplementarityStats {}
unsafe impl ExtensibleOut for PounceComplementaritySolve {}

/// Copy `s` into a fixed C char array, truncated on a byte boundary so that
/// a NUL always fits; the rest of the array is zeroed.
fn copy_label<const N: usize>(dst: &mut [c_char; N], s: &str) {
    dst.fill(0);
    let keep = s.len().min(N.saturating_sub(1));
    for (slot, b) in dst.iter_mut().zip(&s.as_bytes()[..keep]) {
        *slot = *b as c_char;
    }
}

/// A count as an `Index`, saturating rather than wrapping.
fn cc_count(v: usize) -> Index {
    Index::try_from(v).unwrap_or(Index::MAX)
}

/// The report's `finite` rule, in C's terms: a non-finite or unmeasured
/// real reads `NaN` where the JSON reads `null`.
fn cc_real(v: Number) -> Number {
    if v.is_finite() { v } else { Number::NAN }
}

fn cc_flag(b: bool) -> Index {
    Index::from(b)
}

/// The struct [`GetPounceComplementarityStats`] fills, from the driver's
/// record. The encodings are `MpccOutcome::report_info`'s field for field
/// (strings become the `POUNCE_CC_*` codes, `null` becomes `NaN` or `-1`).
pub(crate) fn complementarity_stats(
    out: &pounce_restoration::mpcc_driver::MpccOutcome,
) -> PounceComplementarityStats {
    use pounce_algorithm::mpcc::{BVerdict, Reported, StationarityClass};
    let mut s = PounceComplementarityStats {
        struct_size: struct_size_of::<PounceComplementarityStats>(),
        strategy: [0; 16],
        reported: match out.reported {
            Reported::Answer(_) => POUNCE_CC_REPORTED_ANSWER,
            Reported::WeakFallback(_) => POUNCE_CC_REPORTED_WEAK_FALLBACK,
            Reported::FeasibleUncertified(_) => POUNCE_CC_REPORTED_FEASIBLE_UNCERTIFIED,
            Reported::Verdict => POUNCE_CC_REPORTED_VERDICT,
        },
        accepted_by: [0; 32],
        fallback: [0; 32],
        n_solves: cc_count(out.solves.len()),
        total_iterations: cc_count(out.total_iterations),
        max_abs_product: cc_real(out.max_abs_product),
        certificate_class: POUNCE_CC_CLASS_ABSENT,
        n_pairs: -1,
        n_biactive: -1,
        n_neither: -1,
        multipliers_unique: -1,
        residual: Number::NAN,
        resid_tol: Number::NAN,
        tight: -1,
        feasible: -1,
        primal_violation: Number::NAN,
        b_verdict: POUNCE_CC_B_VERDICT_ABSENT,
        b_n_biactive: -1,
        b_branches_solved: -1,
        b_enumerated: -1,
        escapes: cc_count(out.escapes),
        lifted: cc_count(out.lifted),
        natural_residual: out.natural_residual.map_or(Number::NAN, cc_real),
        polish_ran: 0,
        polish_taken: 0,
        polish_residual_before: Number::NAN,
        polish_residual_after: Number::NAN,
        polish_threshold: cc_real(out.polish_threshold),
    };
    copy_label(&mut s.strategy, out.strategy.name());
    if let Some(stage) = out.accepted_by {
        copy_label(&mut s.accepted_by, stage.label());
    }
    if let Some(stage) = out.fallback {
        copy_label(&mut s.fallback, stage.label());
    }
    if let Some(c) = &out.certificate {
        s.certificate_class = match c.class {
            StationarityClass::S => POUNCE_CC_CLASS_S,
            StationarityClass::W => POUNCE_CC_CLASS_W,
            StationarityClass::None => POUNCE_CC_CLASS_NONE,
            StationarityClass::NotSearched => POUNCE_CC_CLASS_NOT_SEARCHED,
        };
        s.n_pairs = cc_count(c.n_pairs);
        s.n_biactive = cc_count(c.n_biactive);
        s.n_neither = cc_count(c.n_neither);
        s.multipliers_unique = cc_flag(c.multipliers_unique);
        s.residual = cc_real(c.residual);
        s.resid_tol = cc_real(c.resid_tol);
        s.tight = cc_flag(c.tight);
        s.feasible = cc_flag(c.feasible);
        s.primal_violation = cc_real(c.primal_violation);
    }
    if let Some(b) = &out.b_check {
        s.b_verdict = match b.verdict {
            BVerdict::B => POUNCE_CC_B_VERDICT_B,
            BVerdict::NotB { .. } => POUNCE_CC_B_VERDICT_NOT_B,
            BVerdict::NotChecked(_) => POUNCE_CC_B_VERDICT_NOT_CHECKED,
        };
        s.b_n_biactive = cc_count(b.n_biactive);
        s.b_branches_solved = cc_count(b.branches_solved);
        s.b_enumerated = cc_flag(b.enumerated);
    }
    if let Some(p) = &out.polish {
        s.polish_ran = 1;
        s.polish_taken = cc_flag(p.taken);
        s.polish_residual_before = cc_real(p.residual_before);
        s.polish_residual_after = cc_real(p.residual_after);
    }
    s
}

/// The record [`GetPounceComplementaritySolve`] fills for one lowered solve.
pub(crate) fn complementarity_solve(
    r: &pounce_restoration::mpcc_driver::MpccSolveRecord,
) -> PounceComplementaritySolve {
    let mut s = PounceComplementaritySolve {
        struct_size: struct_size_of::<PounceComplementaritySolve>(),
        stage: [0; 32],
        relaxed: cc_flag(r.tau.is_some()),
        tau: r.tau.unwrap_or(Number::NAN),
        status: r.status as Index,
        iterations: cc_count(r.iterations),
        max_abs_product: cc_real(r.max_abs_product),
        seconds: cc_real(r.seconds),
    };
    copy_label(&mut s.stage, r.stage.label());
    s
}

/// The text [`GetPounceComplementarityText`] returns for `which`, or `None`
/// when that text is absent on this run (or `which` names none).
pub(crate) fn complementarity_text(
    out: &pounce_restoration::mpcc_driver::MpccOutcome,
    which: c_int,
) -> Option<String> {
    use pounce_algorithm::mpcc::BVerdict;
    match which {
        POUNCE_CC_TEXT_SUMMARY => Some(pounce_algorithm::mpcc::describe_outcome(
            out.reported,
            out.solves.len(),
            out.total_iterations,
            out.max_abs_product,
            out.certificate.as_ref(),
        )),
        POUNCE_CC_TEXT_POLISH_REASON => out.polish.as_ref().and_then(|p| p.reason.clone()),
        POUNCE_CC_TEXT_B_REASON => match out.b_check.as_ref().map(|b| &b.verdict) {
            Some(BVerdict::NotChecked(why)) => Some((*why).to_string()),
            _ => None,
        },
        _ => None,
    }
}

/// The driver's record of the most recent solve, if that solve ran it.
unsafe fn last_mpcc<'a>(
    ipopt_problem: IpoptProblem,
) -> Option<&'a pounce_restoration::mpcc_driver::MpccOutcome> {
    unsafe {
        if ipopt_problem.is_null() {
            return None;
        }
        (*ipopt_problem)
            .last_solve
            .as_ref()
            .and_then(|ls| ls.mpcc.as_ref())
    }
}

/// What the complementarity driver did on the most recent [`IpoptSolve`]
/// (gh#1147): the strategy, what was reported and by which formulation,
/// the iteration totals, the stationarity certificate, the B-stationarity
/// check and the polish — the solve report's `complementarity` block as a
/// struct of scalars. The caller sets `stats->struct_size =
/// sizeof(PounceComplementarityStats)` first. Returns `FALSE`, leaving
/// `stats` untouched, on a NULL argument, a `struct_size` smaller than this
/// release's size, before any solve, and when the most recent solve did not run
/// the driver (no pairs were declared, or it was refused or failed before
/// the driver returned). The record describes the most recent solve: clearing
/// the pairs afterwards does not erase it, the next solve does.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `stats`, when
/// non-NULL, must point at a writable `PounceComplementarityStats` (at
/// least `struct_size` bytes when that is this release's size or more).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceComplementarityStats(
    ipopt_problem: IpoptProblem,
    stats: *mut PounceComplementarityStats,
) -> Bool {
    ffi_guard(FALSE, || unsafe {
        if stats.is_null() {
            return FALSE;
        }
        let Some(out) = last_mpcc(ipopt_problem) else {
            return FALSE;
        };
        // Bounded write of this release's size; FALSE, nothing written,
        // when `stats->struct_size` is short (see `write_extensible`).
        Bool::from(write_extensible(stats, &complementarity_stats(out)))
    })
}

/// Lowered solve `k` (0-based, in the order the driver ran them, `k <
/// n_solves`) of the most recent driver solve; the caller sets
/// `solve->struct_size = sizeof(PounceComplementaritySolve)` first. Returns
/// `FALSE`, leaving `solve` untouched, on a NULL argument, a short
/// `struct_size`, a `k` out of range, and whenever
/// [`GetPounceComplementarityStats`] would.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `solve`, when
/// non-NULL, must point at a writable `PounceComplementaritySolve` (at
/// least `struct_size` bytes when that is this release's size or more).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceComplementaritySolve(
    ipopt_problem: IpoptProblem,
    k: Index,
    solve: *mut PounceComplementaritySolve,
) -> Bool {
    ffi_guard(FALSE, || unsafe {
        if solve.is_null() {
            return FALSE;
        }
        let Some(out) = last_mpcc(ipopt_problem) else {
            return FALSE;
        };
        let Some(r) = usize::try_from(k).ok().and_then(|k| out.solves.get(k)) else {
            return FALSE;
        };
        Bool::from(write_extensible(solve, &complementarity_solve(r)))
    })
}

/// One of the driver's free-form texts for the most recent driver solve,
/// with C's `snprintf` contract: writes at most `buflen - 1` bytes of it
/// plus a NUL into `buf` and returns its full length in bytes, without the
/// NUL — so `buf = NULL, buflen = 0` sizes the buffer, and a return `>=
/// buflen` means it was truncated. Returns `-1`, writing nothing, when
/// there is no such text: a NULL handle, a `which` that names none,
/// whenever [`GetPounceComplementarityStats`] would return `FALSE`, or a
/// text this run does not have (`POUNCE_CC_TEXT_POLISH_REASON` unless the
/// polish ran and was not taken; `POUNCE_CC_TEXT_B_REASON` unless the
/// B-stationarity check ran and was not decided). A NULL `buf` or a
/// `buflen <= 0` writes nothing and still returns the length.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL. `buf`, when
/// non-NULL and `buflen > 0`, must have room for `buflen` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn GetPounceComplementarityText(
    ipopt_problem: IpoptProblem,
    which: c_int,
    buf: *mut c_char,
    buflen: Index,
) -> Index {
    ffi_guard(-1, || unsafe {
        let Some(out) = last_mpcc(ipopt_problem) else {
            return -1;
        };
        let Some(text) = complementarity_text(out, which) else {
            return -1;
        };
        let bytes = text.as_bytes();
        if !buf.is_null() && buflen > 0 {
            let keep = bytes.len().min(buflen as usize - 1);
            let dst = std::slice::from_raw_parts_mut(buf, keep + 1);
            for (slot, b) in dst.iter_mut().zip(&bytes[..keep]) {
                *slot = *b as c_char;
            }
            dst[keep] = 0;
        }
        cc_count(bytes.len())
    })
}

/// Drop any pending warm-start working set without solving. The
/// next [`IpoptSolve`] will cold-start.
///
/// # Safety
///
/// `ipopt_problem` must be a valid `IpoptProblem` or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptClearWarmStartWorkingSet(ipopt_problem: IpoptProblem) -> Bool {
    unsafe {
        if ipopt_problem.is_null() {
            return FALSE;
        }
        (*ipopt_problem).pending_working_set = None;
        (*ipopt_problem).app.clear_sqp_warm_start();
        TRUE
    }
}

/// Convenience one-shot: equivalent to
/// `IpoptSetWarmStartWorkingSet` + `IpoptSolve` +
/// `IpoptGetWorkingSet` in sequence. The input/output working-set
/// buffers are independent (so a caller can read back the new
/// working set into the same array used as input). Pass `NULL`
/// for any in/out buffer to skip that side.
///
/// Returns the `ApplicationReturnStatus` integer, identical to
/// [`IpoptSolve`].
///
/// # Safety
///
/// All pointer arguments follow the same contract as
/// `IpoptSolve` plus the working-set buffer sizes documented on
/// `IpoptSetWarmStartWorkingSet` / `IpoptGetWorkingSet`.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptSolveWarmStart(
    ipopt_problem: IpoptProblem,
    x: *mut Number,
    g: *mut Number,
    obj_val: *mut Number,
    mult_g: *mut Number,
    mult_x_L: *mut Number,
    mult_x_U: *mut Number,
    bound_status_in: *const IpoptBoundStatus,
    cons_status_in: *const IpoptConsStatus,
    bound_status_out: *mut IpoptBoundStatus,
    cons_status_out: *mut IpoptConsStatus,
    user_data: *mut c_void,
) -> Index {
    if ipopt_problem.is_null() {
        return ApplicationReturnStatus::InternalError as Index;
    }
    // Guard the working-set set/get helpers too. The inner `IpoptSolve` is
    // independently guarded, but a panic in the warm-start working-set
    // marshalling would otherwise still abort across `extern "C"`.
    ffi_guard(ApplicationReturnStatus::InternalError as Index, || unsafe {
        // Best-effort set. Errors here (e.g. bad status code) are
        // silently treated as cold-start; the caller can probe via
        // `IpoptSetWarmStartWorkingSet` directly if they need to
        // validate the input.
        if !bound_status_in.is_null() || !cons_status_in.is_null() {
            let _ = IpoptSetWarmStartWorkingSet(ipopt_problem, bound_status_in, cons_status_in);
        }
        let status = IpoptSolve(
            ipopt_problem,
            x,
            g,
            obj_val,
            mult_g,
            mult_x_L,
            mult_x_U,
            user_data,
        );
        // Copy a set out only when this solve completed: a refused solve
        // (pairs with a working set, gh#1147) leaves `last_solve` empty, and
        // the handle's last SQP set is then an earlier solve's.
        if (*ipopt_problem).last_solve.is_some() {
            let _ = IpoptGetWorkingSet(ipopt_problem, bound_status_out, cons_status_out);
        }
        status
    })
}

thread_local! {
    /// The bridge whose `intermediate_callback` is running, for
    /// [`GetIpoptCurrentViolations`]; null outside that window.
    static CURRENT_BRIDGE: std::cell::Cell<*const CCallbackTnlp> =
        const { std::cell::Cell::new(std::ptr::null()) };
}

/// `(nlp_lower_bound_inf, nlp_upper_bound_inf, zero_fixed_grad_lag)` for
/// the bridge fields of the same names.
pub(crate) fn bridge_violation_options(
    o: &pounce_common::options_list::OptionsList,
) -> (Number, Number, bool) {
    let num = |k: &str, d: Number| {
        o.get_numeric_value(k, "")
            .ok()
            .and_then(|(v, f)| f.then_some(v))
            .unwrap_or(d)
    };
    let relax = matches!(
        o.get_string_value("fixed_variable_treatment", "")
            .ok()
            .and_then(|(v, f)| f.then_some(v))
            .as_deref(),
        Some("relax_bounds")
    );
    (
        num("nlp_lower_bound_inf", NLP_LOWER_BOUND_INF),
        num("nlp_upper_bound_inf", NLP_UPPER_BOUND_INF),
        !relax,
    )
}

thread_local! {
    /// `true` while the innermost [`IpoptSolve`] on this thread runs the
    /// complementarity driver (gh#1147). The live inspectors report no data
    /// then: the algorithm's iterate is the lowered model's — product rows
    /// appended, possibly lifted variables — not the caller's, and a prefix
    /// of it is not the caller's iterate either (a lifted row's bounds are
    /// rewritten).
    ///
    /// Per *solve*, not per thread: every `IpoptSolve` sets it for its own
    /// duration, so a pair-free solve of another problem started from inside
    /// a lowered solve's callback reads `false` (its iterate is its own) and
    /// the lowered solve reads `true` again once it returns.
    static IN_LOWERED_SOLVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Sets [`IN_LOWERED_SOLVE`] for its lifetime, restoring the previous value
/// on drop (so nesting unwinds in order, and a panic caught by [`ffi_guard`]
/// cannot leave it set).
struct LoweredSolveGuard {
    prev: bool,
}

impl LoweredSolveGuard {
    fn set(lowered: bool) -> Self {
        Self {
            prev: IN_LOWERED_SOLVE.with(|c| c.replace(lowered)),
        }
    }
}

impl Drop for LoweredSolveGuard {
    fn drop(&mut self) {
        IN_LOWERED_SOLVE.with(|c| c.set(self.prev));
    }
}

fn in_lowered_solve() -> bool {
    IN_LOWERED_SOLVE.with(|c| c.get())
}

struct BridgeGuard {
    prev: *const CCallbackTnlp,
}

impl BridgeGuard {
    fn install(bridge: &CCallbackTnlp) -> Self {
        let prev = CURRENT_BRIDGE.with(|c| c.replace(bridge as *const _));
        Self { prev }
    }
}

impl Drop for BridgeGuard {
    fn drop(&mut self) {
        CURRENT_BRIDGE.with(|c| c.set(self.prev));
    }
}

impl CCallbackTnlp {
    /// `∇f + Jᵀλ − z_L + z_U` at the user-space iterate `it`, through the
    /// user's own C callbacks (called directly, not through the TNLP the
    /// callback dispatch holds). `None` if a callback declines.
    fn user_grad_lag(&self, it: &ip_intermediate::UserIterate) -> Option<Vec<Number>> {
        let n = self.n as usize;
        let cb = self.eval_grad_f?;
        let mut grad = vec![0.0; n];
        let x = it.x.as_ptr() as *mut Number;
        if unsafe { cb(self.n, x, TRUE, grad.as_mut_ptr(), self.user_data) } == FALSE {
            return None;
        }
        let nnz = self.nele_jac.max(0) as usize;
        let (mut rows, mut cols, mut vals) = (vec![0; nnz], vec![0; nnz], vec![0.0; nnz]);
        if self.m > 0 && nnz > 0 {
            let jac = self.eval_jac_g?;
            let structure = unsafe {
                jac(
                    self.n,
                    x,
                    FALSE,
                    self.m,
                    self.nele_jac,
                    rows.as_mut_ptr(),
                    cols.as_mut_ptr(),
                    std::ptr::null_mut(),
                    self.user_data,
                )
            };
            let values = unsafe {
                jac(
                    self.n,
                    x,
                    FALSE,
                    self.m,
                    self.nele_jac,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    vals.as_mut_ptr(),
                    self.user_data,
                )
            };
            if structure == FALSE || values == FALSE {
                return None;
            }
        }
        let off = if self.index_style == 1 { 1 } else { 0 };
        let to_usize = |v: &[Index]| -> Vec<usize> {
            v.iter()
                .map(|&k| usize::try_from(k - off).unwrap_or(usize::MAX))
                .collect()
        };
        Some(pounce_nlp::live_iterate::lagrangian_gradient(
            it,
            &grad,
            &to_usize(&rows),
            &to_usize(&cols),
            &vals,
        ))
    }
}

/// Adapter that bridges the user-supplied C callback table to the
/// in-crate [`TNLP`] trait. Mirrors `Interfaces/IpStdInterfaceTNLP.cpp`
/// (`StdInterfaceTNLP`); each TNLP method forwards to the matching
/// `Eval_*_CB` and propagates `false` returns up so the algorithm
/// layer can map them to `Invalid_Number_Detected`.
///
/// Holds a snapshot of bounds and the initial `x`. After `optimize_tnlp`
/// finishes, `finalize_solution` is called by the algorithm layer; the
/// adapter records the final iterate in `final_*` fields, which the
/// outer [`IpoptSolve`] copies back into the caller's buffers.
pub(crate) struct CCallbackTnlp {
    pub(crate) n: Index,
    pub(crate) m: Index,
    pub(crate) nele_jac: Index,
    pub(crate) nele_hess: Index,
    pub(crate) index_style: Index,
    pub(crate) x_l: Vec<Number>,
    pub(crate) x_u: Vec<Number>,
    pub(crate) g_l: Vec<Number>,
    pub(crate) g_u: Vec<Number>,
    pub(crate) initial_x: Vec<Number>,
    /// The caller's `mult_g` buffer (length `m`), or NULL. Read only by
    /// [`TNLP::get_starting_point`] under `init_lambda`, i.e. when the
    /// solve was asked for a dual warm start (`warm_start_init_point=yes`)
    /// — upstream `StdInterfaceTNLP`'s `start_lam`. A caller that has not
    /// opted in may pass an uninitialized buffer, which is why this is a
    /// pointer read lazily under the flag rather than a snapshot taken
    /// up front. Valid for the whole `IpoptSolve` call: the buffer is
    /// overwritten with the solution only after the solve (and any
    /// second-opinion re-solve, which calls `get_starting_point` again)
    /// has finished.
    pub(crate) start_lambda: *const Number,
    /// The caller's `mult_x_L` buffer (length `n`), or NULL. Read under
    /// `init_z`; see [`CCallbackTnlp::start_lambda`].
    pub(crate) start_z_l: *const Number,
    /// The caller's `mult_x_U` buffer (length `n`), or NULL. Read under
    /// `init_z`; see [`CCallbackTnlp::start_lambda`].
    pub(crate) start_z_u: *const Number,
    pub(crate) eval_f: Option<Eval_F_CB>,
    pub(crate) eval_grad_f: Option<Eval_Grad_F_CB>,
    pub(crate) eval_g: Option<Eval_G_CB>,
    pub(crate) eval_jac_g: Option<Eval_Jac_G_CB>,
    pub(crate) eval_h: Option<Eval_H_CB>,
    pub(crate) user_data: *mut c_void,
    /// User-installed intermediate callback, copied at solve time so the
    /// TNLP-trait `intermediate_callback` impl can forward through to it.
    pub(crate) intermediate_cb: Option<Intermediate_CB>,
    /// Snapshot of user-provided scaling captured at solve time.
    pub(crate) user_scaling: Option<UserScaling>,
    /// Snapshot of the nonlinear-variable subset (gh#624), in the
    /// problem's index style.
    pub(crate) nonlinear_vars: Option<Vec<Index>>,
    /// `nlp_lower_bound_inf` / `nlp_upper_bound_inf` of the solve, for the
    /// violations `GetIpoptCurrentViolations` measures against `x_l` …
    /// `g_u` (a side at or beyond these is absent).
    pub(crate) lower_inf: Number,
    pub(crate) upper_inf: Number,
    /// Whether `grad_lag_x` reads `0` at fixed variables: true unless
    /// `fixed_variable_treatment=relax_bounds`, which keeps them in the
    /// problem (upstream: `ResortX(…, usefixedvals=false)`).
    pub(crate) zero_fixed_grad_lag: bool,
    pub(crate) final_status: Option<pounce_nlp::alg_types::SolverReturn>,
    pub(crate) final_x: Vec<Number>,
    pub(crate) final_z_l: Vec<Number>,
    pub(crate) final_z_u: Vec<Number>,
    pub(crate) final_g: Vec<Number>,
    pub(crate) final_lambda: Vec<Number>,
    pub(crate) final_obj: Number,
}

impl TNLP for CCallbackTnlp {
    fn get_nlp_info(&mut self) -> Option<NlpInfo> {
        Some(NlpInfo {
            n: self.n as pounce_common::types::Index,
            m: self.m as pounce_common::types::Index,
            nnz_jac_g: self.nele_jac as pounce_common::types::Index,
            nnz_h_lag: self.nele_hess as pounce_common::types::Index,
            index_style: if self.index_style == 1 {
                IndexStyle::Fortran
            } else {
                IndexStyle::C
            },
        })
    }

    /// gh#624 — serve the subset staged by
    /// [`IpoptSetNonlinearVariables`]. `-1` (no subset) keeps the
    /// upstream default of "all variables are nonlinear".
    fn get_number_of_nonlinear_variables(&mut self) -> pounce_common::types::Index {
        match &self.nonlinear_vars {
            Some(v) => v.len() as pounce_common::types::Index,
            None => -1,
        }
    }

    fn get_list_of_nonlinear_variables(
        &mut self,
        pos_nonlin_vars: &mut [pounce_common::types::Index],
    ) -> bool {
        let Some(v) = self.nonlinear_vars.as_ref() else {
            return false;
        };
        if v.len() != pos_nonlin_vars.len() {
            return false;
        }
        pos_nonlin_vars.copy_from_slice(v);
        true
    }

    fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
        if !self.x_l.is_empty() {
            b.x_l.copy_from_slice(&self.x_l);
        }
        if !self.x_u.is_empty() {
            b.x_u.copy_from_slice(&self.x_u);
        }
        if !self.g_l.is_empty() {
            b.g_l.copy_from_slice(&self.g_l);
        }
        if !self.g_u.is_empty() {
            b.g_u.copy_from_slice(&self.g_u);
        }
        true
    }

    fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
        if !self.initial_x.is_empty() {
            sp.x.copy_from_slice(&self.initial_x);
        }
        // Dual warm start, as upstream `StdInterfaceTNLP::get_starting_point`:
        // under `init_z` / `init_lambda` the caller's `mult_x_L` / `mult_x_U`
        // / `mult_g` buffers are the starting multipliers. Same sign
        // convention as the values `finalize_solution` writes back into those
        // buffers (L = f + lambda'g, z_L, z_U >= 0), so a solve's output feeds
        // the next solve's input unchanged.
        //
        // One deliberate departure: upstream fails the solve when a requested
        // buffer is NULL. Here NULL means "not supplied" and the slot is left
        // untouched, so `OrigIpoptNlp`'s NaN "unseeded" marker (gh#622) stands
        // and the warm-start initializer resolves it, rather than a primal-only
        // warm start becoming an error.
        let copy_in = |dst: &mut [Number], src: *const Number| {
            if !src.is_null() && !dst.is_empty() {
                // SAFETY: `src` is the caller's buffer of the documented
                // length (`n` for the bound multipliers, `m` for `mult_g`),
                // valid for the duration of the enclosing `IpoptSolve`.
                dst.copy_from_slice(unsafe { std::slice::from_raw_parts(src, dst.len()) });
            }
        };
        if sp.init_z {
            copy_in(sp.z_l, self.start_z_l);
            copy_in(sp.z_u, self.start_z_u);
        }
        if sp.init_lambda {
            copy_in(sp.lambda, self.start_lambda);
        }
        true
    }

    fn get_scaling_parameters(&mut self, req: ScalingRequest<'_>) -> bool {
        let Some(s) = self.user_scaling.as_ref() else {
            return false;
        };
        *req.obj_scaling = s.obj_scaling;
        if let Some(x) = s.x_scaling.as_ref() {
            if x.len() == req.x_scaling.len() {
                req.x_scaling.copy_from_slice(x);
                *req.use_x_scaling = true;
            }
        } else {
            *req.use_x_scaling = false;
        }
        if let Some(g) = s.g_scaling.as_ref() {
            if g.len() == req.g_scaling.len() {
                req.g_scaling.copy_from_slice(g);
                *req.use_g_scaling = true;
            }
        } else {
            *req.use_g_scaling = false;
        }
        true
    }

    fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
        let cb = self.eval_f?;
        let mut obj = 0.0;
        let ok = unsafe {
            cb(
                self.n,
                x.as_ptr() as *mut Number,
                if new_x { TRUE } else { FALSE },
                &mut obj,
                self.user_data,
            )
        };
        if ok != FALSE { Some(obj) } else { None }
    }

    fn eval_grad_f(&mut self, x: &[Number], new_x: bool, grad_f: &mut [Number]) -> bool {
        let Some(cb) = self.eval_grad_f else {
            return false;
        };
        let ok = unsafe {
            cb(
                self.n,
                x.as_ptr() as *mut Number,
                if new_x { TRUE } else { FALSE },
                grad_f.as_mut_ptr(),
                self.user_data,
            )
        };
        ok != FALSE
    }

    fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
        if self.m == 0 {
            return true;
        }
        let Some(cb) = self.eval_g else {
            return false;
        };
        let ok = unsafe {
            cb(
                self.n,
                x.as_ptr() as *mut Number,
                if new_x { TRUE } else { FALSE },
                self.m,
                g.as_mut_ptr(),
                self.user_data,
            )
        };
        ok != FALSE
    }

    fn eval_jac_g(&mut self, x: Option<&[Number]>, new_x: bool, mode: SparsityRequest<'_>) -> bool {
        if self.m == 0 || self.nele_jac == 0 {
            return true;
        }
        let Some(cb) = self.eval_jac_g else {
            return false;
        };
        let x_ptr = x
            .map(|s| s.as_ptr() as *mut Number)
            .unwrap_or(std::ptr::null_mut());
        let ok = match mode {
            SparsityRequest::Structure { irow, jcol } => unsafe {
                cb(
                    self.n,
                    x_ptr,
                    if new_x { TRUE } else { FALSE },
                    self.m,
                    self.nele_jac,
                    irow.as_mut_ptr(),
                    jcol.as_mut_ptr(),
                    std::ptr::null_mut(),
                    self.user_data,
                )
            },
            SparsityRequest::Values { values } => unsafe {
                cb(
                    self.n,
                    x_ptr,
                    if new_x { TRUE } else { FALSE },
                    self.m,
                    self.nele_jac,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    values.as_mut_ptr(),
                    self.user_data,
                )
            },
        };
        ok != FALSE
    }

    fn eval_h(
        &mut self,
        x: Option<&[Number]>,
        new_x: bool,
        obj_factor: Number,
        lambda: Option<&[Number]>,
        new_lambda: bool,
        mode: SparsityRequest<'_>,
    ) -> bool {
        let Some(cb) = self.eval_h else {
            return false;
        };
        if self.nele_hess == 0 {
            return true;
        }
        let x_ptr = x
            .map(|s| s.as_ptr() as *mut Number)
            .unwrap_or(std::ptr::null_mut());
        let lambda_ptr = lambda
            .map(|s| s.as_ptr() as *mut Number)
            .unwrap_or(std::ptr::null_mut());
        let ok = match mode {
            SparsityRequest::Structure { irow, jcol } => unsafe {
                cb(
                    self.n,
                    x_ptr,
                    if new_x { TRUE } else { FALSE },
                    obj_factor,
                    self.m,
                    lambda_ptr,
                    if new_lambda { TRUE } else { FALSE },
                    self.nele_hess,
                    irow.as_mut_ptr(),
                    jcol.as_mut_ptr(),
                    std::ptr::null_mut(),
                    self.user_data,
                )
            },
            SparsityRequest::Values { values } => unsafe {
                cb(
                    self.n,
                    x_ptr,
                    if new_x { TRUE } else { FALSE },
                    obj_factor,
                    self.m,
                    lambda_ptr,
                    if new_lambda { TRUE } else { FALSE },
                    self.nele_hess,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    values.as_mut_ptr(),
                    self.user_data,
                )
            },
        };
        ok != FALSE
    }

    /// Only a registered `SetIntermediateCallback` reads the payload, and
    /// the `GetIpoptCurrent*` inspectors are valid only inside it (gh#965).
    fn wants_intermediate_callback(&self) -> bool {
        self.intermediate_cb.is_some()
    }

    /// A registered callback may call `GetIpoptCurrentIterate` /
    /// `GetIpoptCurrentViolations`, and nothing says whether it will, so
    /// the iterate is materialised for every fire it receives.
    fn wants_current_iterate(&self) -> bool {
        self.intermediate_cb.is_some()
    }

    fn intermediate_callback(
        &mut self,
        stats: pounce_nlp::tnlp::IterStats,
        _ip_data: &IpoptData,
        _ip_cq: &IpoptCq,
    ) -> bool {
        let Some(cb) = self.intermediate_cb else {
            return true;
        };
        // `GetIpoptCurrentViolations` evaluates `∇f` and `J` through this
        // bridge's C callbacks (the TNLP itself is mutably borrowed by the
        // dispatch that called us), so it needs the callbacks, `user_data`
        // and the declared bounds for exactly the duration of `cb`.
        let _bridge = BridgeGuard::install(self);
        let ok = unsafe {
            cb(
                stats.mode as Index,
                stats.iter as Index,
                stats.obj_value,
                stats.inf_pr,
                stats.inf_du,
                stats.mu,
                stats.d_norm,
                stats.regularization_size,
                stats.alpha_du,
                stats.alpha_pr,
                stats.ls_trials as Index,
                self.user_data,
            )
        };
        ok != FALSE
    }

    fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
        self.final_status = Some(sol.status);
        if !sol.x.is_empty() {
            self.final_x.copy_from_slice(sol.x);
        }
        if !sol.z_l.is_empty() {
            self.final_z_l.copy_from_slice(sol.z_l);
        }
        if !sol.z_u.is_empty() {
            self.final_z_u.copy_from_slice(sol.z_u);
        }
        if !sol.g.is_empty() {
            self.final_g.copy_from_slice(sol.g);
        }
        if !sol.lambda.is_empty() {
            self.final_lambda.copy_from_slice(sol.lambda);
        }
        self.final_obj = sol.obj_value;
    }
}

/// Enable per-iteration history capture on the underlying
/// `IpoptApplication`. Must be called *before* [`IpoptSolve`] for the
/// trajectory to appear in the report written by
/// [`IpoptWriteSolveReport`]. Off by default — capturing each iterate
/// has a small per-iter cost the IPM core skips otherwise.
///
/// Returns `TRUE` on success, `FALSE` if `ipopt_problem` is NULL.
///
/// # Safety
///
/// `ipopt_problem` must be a valid handle returned by
/// [`CreateIpoptProblem`] (or `NULL`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptEnableIterHistory(ipopt_problem: IpoptProblem) -> Bool {
    if ipopt_problem.is_null() {
        return FALSE;
    }
    let info = unsafe { &mut *ipopt_problem };
    info.app.enable_iter_history();
    TRUE
}

/// Write a `pounce.solve-report/v1` JSON file capturing the most
/// recent [`IpoptSolve`] result. `path` is a NUL-terminated UTF-8
/// filesystem path. `detail` is one of `"summary"` or `"full"`
/// (NUL-terminated); pass `NULL` for the default (`"summary"`).
///
/// When `detail = "full"` and [`IpoptEnableIterHistory`] was called
/// pre-solve, the per-iteration trajectory is embedded so that
/// downstream tools (`diagnose`, `find_stalls`, `convergence_trace`)
/// see the same trace the `pounce` CLI's `--json-output` path
/// produces. The input descriptor is recorded as `tnlp-direct`
/// because the cinterface receives callbacks rather than a file.
///
/// When that solve ran the complementarity driver (pairs were declared),
/// the report carries the `complementarity` block at either detail level,
/// built by the same conversion as the CLI's and Python's reports; it is
/// absent otherwise.
///
/// When that solve took the path without pairs and the second-opinion
/// ladder ran at least one rung, the report carries the `second_opinion`
/// block (gh#850) at either detail level, from the same conversion and
/// under the same condition as the CLI's and Python's; absent when no rung
/// ran, after a driver solve, and after a session solve.
///
/// Returns `TRUE` on a successful write, `FALSE` for NULL handle,
/// no prior solve, an invalid `detail`, a bad path, or an I/O error.
///
/// # Safety
///
/// `ipopt_problem` must be a valid handle; `path` must be a valid
/// NUL-terminated UTF-8 string; `detail` must be NULL or a valid
/// NUL-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn IpoptWriteSolveReport(
    ipopt_problem: IpoptProblem,
    path: *const c_char,
    detail: *const c_char,
) -> Bool {
    use pounce_solve_report::{
        InputDescriptor, ReportBuilder, ReportDetail, status_to_solve_result_num, write_report_file,
    };

    // Guard the report build/write: it clones the retained iterate and runs
    // the `pounce-solve-report` serializer + file I/O, any of which could
    // panic on an unexpected state. A panic unwinding across `extern "C"`
    // aborts the embedding process; report `FALSE` instead. (See `ffi_guard`.)
    ffi_guard(FALSE, || unsafe {
        if ipopt_problem.is_null() || path.is_null() {
            return FALSE;
        }
        let info = &*ipopt_problem;
        let Some(last) = info.last_solve.as_ref() else {
            return FALSE;
        };

        let Ok(path_str) = CStr::from_ptr(path).to_str() else {
            return FALSE;
        };

        let detail_choice = if detail.is_null() {
            ReportDetail::Summary
        } else {
            let Ok(detail_str) = CStr::from_ptr(detail).to_str() else {
                return FALSE;
            };
            match ReportDetail::parse(detail_str) {
                Ok(d) => d,
                Err(_) => return FALSE,
            }
        };

        let mut builder = ReportBuilder::new(detail_choice, InputDescriptor::TnlpDirect);
        builder.problem.n_variables = info.n;
        builder.problem.n_constraints = info.m;
        builder.problem.n_objectives = 1;
        builder.problem.nnz_jac_g = Some(info.nele_jac);
        builder.problem.nnz_h_lag = Some(info.nele_hess);

        builder.solution.status = last.status;
        builder.solution.solve_result_num = status_to_solve_result_num(last.status);
        builder.solution.objective = last.final_obj;
        builder.solution.x = last.final_x.clone();
        builder.solution.lambda = last.final_lambda.clone();

        builder.ingest_stats(&last.stats);
        if let Some(linsol) = last.linear_solver.clone() {
            builder.set_linear_solver_summary(linsol);
        }
        // Declared complementarity (gh#1147): what the driver did, through the
        // same conversion the CLI's `--json-output` and Python's `report_path`
        // use, so the three frontends write one block for one driver outcome.
        // `ingest_stats` above wrote the reported lowered solve's statistics;
        // the block carries every lowered solve and the true total. Absent for
        // a solve that did not run the driver (no pairs declared).
        if let Some(out) = &last.mpcc {
            builder.set_complementarity(out.report_info());
        }
        // gh#850: what the second-opinion ladder did, and what the *base*
        // solve did before it, under the CLI's and Python's `ran()` test and
        // through the same `report_info()`. `ingest_stats` above wrote the
        // promoted rung's iteration count as though it were the solve's;
        // without this block a rescued solve reads as a clean, fast one.
        // Absent when no rung ran, and on a driver solve, which does not run
        // the ladder (the CLI and Python skip it there too).
        if let Some(so) = &last.second_opinion
            && so.ran()
        {
            builder.set_second_opinion(so.report_info());
        }

        let report = builder.finish();
        match write_report_file(std::path::Path::new(path_str), &report) {
            Ok(_) => TRUE,
            Err(_) => FALSE,
        }
    })
}

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

    unsafe extern "C" fn dummy_eval_f(
        _n: Index,
        _x: *const Number,
        _new_x: Bool,
        _obj_value: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        TRUE
    }
    unsafe extern "C" fn dummy_eval_grad_f(
        _n: Index,
        _x: *const Number,
        _new_x: Bool,
        _grad_f: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        TRUE
    }

    fn create_unconstrained() -> IpoptProblem {
        let xl = [-1.0; 4];
        let xu = [1.0; 4];
        unsafe {
            CreateIpoptProblem(
                4,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                10,
                0,
                Some(dummy_eval_f),
                None,
                Some(dummy_eval_grad_f),
                None,
                None,
            )
        }
    }

    #[test]
    fn create_succeeds_for_unconstrained_problem() {
        let p = create_unconstrained();
        assert!(!p.is_null());
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn create_returns_null_on_missing_required_callbacks() {
        // error-path: CreateIpoptProblem
        let xl = [-1.0; 4];
        let xu = [1.0; 4];
        let p = unsafe {
            CreateIpoptProblem(
                4,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                10,
                0,
                None, // missing eval_f
                None,
                Some(dummy_eval_grad_f),
                None,
                None,
            )
        };
        assert!(p.is_null());
    }

    #[test]
    fn create_returns_null_on_negative_n() {
        let p = unsafe {
            CreateIpoptProblem(
                -1,
                std::ptr::null(),
                std::ptr::null(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                10,
                0,
                Some(dummy_eval_f),
                None,
                Some(dummy_eval_grad_f),
                None,
                None,
            )
        };
        assert!(p.is_null());
    }

    #[test]
    fn create_returns_null_on_invalid_index_style() {
        let xl = [0.0; 1];
        let xu = [1.0; 1];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                2, // valid values are 0 and 1
                Some(dummy_eval_f),
                None,
                Some(dummy_eval_grad_f),
                None,
                None,
            )
        };
        assert!(p.is_null());
    }

    #[test]
    fn add_int_option_forwards_to_application() {
        let p = create_unconstrained();
        let key = CString::new("print_level").unwrap();
        let ok = unsafe { AddIpoptIntOption(p, key.as_ptr(), 5) };
        assert_eq!(ok, TRUE);
        let info = unsafe { &*p };
        let (level, found) = info
            .app
            .options()
            .get_integer_value("print_level", "")
            .unwrap();
        assert!(found);
        assert_eq!(level, 5);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn add_str_option_with_invalid_key_returns_false() {
        let p = create_unconstrained();
        let key = CString::new("totally_unknown_option").unwrap();
        let val = CString::new("yes").unwrap();
        let ok = unsafe { AddIpoptStrOption(p, key.as_ptr(), val.as_ptr()) };
        assert_eq!(ok, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn add_options_on_null_problem_returns_false() {
        // error-path: AddIpoptIntOption
        // error-path: AddIpoptNumOption
        // error-path: AddIpoptStrOption
        let key = CString::new("print_level").unwrap();
        let v = CString::new("yes").unwrap();
        unsafe {
            assert_eq!(
                AddIpoptIntOption(std::ptr::null_mut(), key.as_ptr(), 5),
                FALSE
            );
            assert_eq!(
                AddIpoptNumOption(std::ptr::null_mut(), key.as_ptr(), 1.0),
                FALSE
            );
            assert_eq!(
                AddIpoptStrOption(std::ptr::null_mut(), key.as_ptr(), v.as_ptr()),
                FALSE
            );
        }
    }

    unsafe extern "C" fn dummy_intermediate(
        _alg_mod: Index,
        _iter_count: Index,
        _obj_value: Number,
        _inf_pr: Number,
        _inf_du: Number,
        _mu: Number,
        _d_norm: Number,
        _regularization_size: Number,
        _alpha_du: Number,
        _alpha_pr: Number,
        _ls_trials: Index,
        _user_data: *mut c_void,
    ) -> Bool {
        TRUE
    }

    #[test]
    fn set_intermediate_callback_stores_pointer() {
        let p = create_unconstrained();
        let ok = unsafe { SetIntermediateCallback(p, Some(dummy_intermediate)) };
        assert_eq!(ok, TRUE);
        let info = unsafe { &*p };
        assert!(info.intermediate_cb.is_some());
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn solve_returns_internal_error_on_null_problem() {
        // error-path: IpoptSolve
        let rc = unsafe {
            IpoptSolve(
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, -199);
    }

    #[test]
    fn free_null_is_safe() {
        // error-path: FreeIpoptProblem
        unsafe { FreeIpoptProblem(std::ptr::null_mut()) };
    }

    // ---- End-to-end bridge: 1-D unconstrained quadratic ----
    //
    // f(x) = (x - 2)^2, no bounds, no constraints. Newton driver
    // converges in one step.

    unsafe extern "C" fn quad_eval_f(
        _n: Index,
        x: *const Number,
        _new_x: Bool,
        obj_value: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            let v = *x.offset(0);
            *obj_value = (v - 2.0) * (v - 2.0);
            TRUE
        }
    }
    unsafe extern "C" fn quad_eval_grad_f(
        _n: Index,
        x: *const Number,
        _new_x: Bool,
        grad: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            let v = *x.offset(0);
            *grad.offset(0) = 2.0 * (v - 2.0);
            TRUE
        }
    }
    unsafe extern "C" fn quad_eval_h(
        _n: Index,
        _x: *const Number,
        _new_x: Bool,
        obj_factor: Number,
        _m: Index,
        _lambda: *const Number,
        _new_lambda: Bool,
        _nele_hess: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            if !irow.is_null() && !jcol.is_null() && values.is_null() {
                *irow.offset(0) = 0;
                *jcol.offset(0) = 0;
            } else if irow.is_null() && jcol.is_null() && !values.is_null() {
                *values.offset(0) = 2.0 * obj_factor;
            } else {
                return FALSE;
            }
            TRUE
        }
    }

    #[test]
    fn solve_drives_unconstrained_quadratic_through_bridge() {
        // Bounds wide open (kappa1 push won't move us off 0.0 since
        // |0| < 1e19, but the Newton step lands us at 2.0 anyway).
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };
        assert!(!p.is_null());
        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        assert!((x[0] - 2.0).abs() < 1e-6, "x[0] = {}", x[0]);
        assert!(obj.abs() < 1e-10, "obj = {}", obj);
        unsafe { FreeIpoptProblem(p) };
    }

    /// F5: `IpoptSolve` invalidates the retained `last_solve` stats **up
    /// front**, so a solve that bails — or whose pounce-internal panic
    /// `ffi_guard` catches (returning `Internal_Error`) — does not leave the
    /// post-solve accessors (`GetIpoptIterCount`, `IpoptWriteSolveReport`, …)
    /// silently reporting the *previous* solve's stats.
    ///
    /// A caught panic can't be injected deterministically through the public
    /// C ABI (a panic in a user `extern "C"` callback aborts at its own
    /// boundary; see `ffi_guard`). We drive the equivalent control-flow shape:
    /// after a successful solve we corrupt `n` to a negative value so the next
    /// `IpoptSolve` returns `InvalidProblemDefinition` from inside the guarded
    /// body **without** reaching the trailing `last_solve = Some(..)` write —
    /// exactly where a caught panic also bails. The up-front clear makes the
    /// accessor report "no data" (0) in both cases rather than stale data.
    #[test]
    fn stale_stats_cleared_when_resolve_bails() {
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };
        assert!(!p.is_null());

        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        // The successful solve recorded real stats.
        let iters_after_success = unsafe { GetIpoptIterCount(p) };
        assert!(
            iters_after_success >= 1,
            "a converged solve should record >=1 iteration, got {iters_after_success}"
        );
        assert!(unsafe { (*p).last_solve.is_some() });

        // Corrupt the problem so the next solve bails early in the guarded body
        // (the same place a caught panic would land) without recording stats.
        unsafe { (*p).n = -1 };
        let mut x2 = [0.0_f64];
        let rc2 = unsafe {
            IpoptSolve(
                p,
                x2.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(
            rc2,
            ApplicationReturnStatus::InvalidProblemDefinition as Index
        );

        // Post-fix: the up-front invalidation cleared the retained stats, so
        // the accessor reports "no data" (0), not the previous iteration count.
        // Pre-fix this returned `iters_after_success` (stale).
        assert!(
            unsafe { (*p).last_solve.is_none() },
            "a bailed re-solve must clear stale last_solve (F5)"
        );
        assert_eq!(
            unsafe { GetIpoptIterCount(p) },
            0,
            "stale iteration count must not survive a bailed re-solve (F5)"
        );

        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn solve_invalid_problem_definition_when_x_null() {
        let p = create_unconstrained();
        let rc = unsafe {
            IpoptSolve(
                p,
                std::ptr::null_mut(), // x null but n > 0
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(
            rc,
            ApplicationReturnStatus::InvalidProblemDefinition as Index
        );
        unsafe { FreeIpoptProblem(p) };
    }

    // ---- New entry points (issue #19) ----

    #[test]
    fn get_version_writes_pkg_version() {
        let (mut mj, mut mn, mut pt) = (-1, -1, -1);
        unsafe { GetIpoptVersion(&mut mj, &mut mn, &mut pt) };
        let expected = parse_pkg_version(env!("CARGO_PKG_VERSION"));
        assert_eq!((mj, mn, pt), expected);
    }

    #[test]
    fn get_version_tolerates_null_buffers() {
        // error-path: GetIpoptVersion
        // None of these should crash.
        unsafe {
            GetIpoptVersion(
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
    }

    #[test]
    fn set_scaling_stores_user_supplied_arrays() {
        let p = create_unconstrained();
        let xs = [2.0, 3.0, 4.0, 5.0];
        let ok = unsafe { SetIpoptProblemScaling(p, 7.0, xs.as_ptr(), std::ptr::null()) };
        assert_eq!(ok, TRUE);
        let info = unsafe { &*p };
        let s = info.user_scaling.as_ref().unwrap();
        assert_eq!(s.obj_scaling, 7.0);
        assert_eq!(s.x_scaling.as_deref(), Some(&xs[..]));
        assert!(s.g_scaling.is_none());
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn set_scaling_on_null_problem_returns_false() {
        // error-path: SetIpoptProblemScaling
        let ok = unsafe {
            SetIpoptProblemScaling(
                std::ptr::null_mut(),
                1.0,
                std::ptr::null(),
                std::ptr::null(),
            )
        };
        assert_eq!(ok, FALSE);
    }

    #[test]
    fn open_output_file_writes_and_attaches_journal() {
        let p = create_unconstrained();
        let dir = std::env::temp_dir().join("pounce-cinterface-test");
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("output.log");
        let cstr = CString::new(path.to_string_lossy().as_bytes()).unwrap();
        let ok = unsafe { OpenIpoptOutputFile(p, cstr.as_ptr(), 5) };
        assert_eq!(ok, TRUE);
        // Option should be reflected in the app.
        let info = unsafe { &*p };
        let (level, found) = info
            .app
            .options()
            .get_integer_value("file_print_level", "")
            .unwrap();
        assert!(found);
        assert_eq!(level, 5);
        unsafe { FreeIpoptProblem(p) };
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn open_output_file_with_null_inputs_returns_false() {
        // error-path: OpenIpoptOutputFile
        let key = CString::new("nope").unwrap();
        unsafe {
            assert_eq!(
                OpenIpoptOutputFile(std::ptr::null_mut(), key.as_ptr(), 0),
                FALSE
            );
        }
        let p = create_unconstrained();
        unsafe {
            assert_eq!(OpenIpoptOutputFile(p, std::ptr::null(), 0), FALSE);
            FreeIpoptProblem(p);
        }
    }

    #[test]
    fn get_current_iterate_returns_false_outside_callback() {
        // error-path: GetIpoptCurrentIterate
        let p = create_unconstrained();
        let rc = unsafe {
            GetIpoptCurrentIterate(
                p,
                FALSE,
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn get_current_violations_returns_false_outside_callback() {
        // error-path: GetIpoptCurrentViolations
        let p = create_unconstrained();
        let rc = unsafe {
            GetIpoptCurrentViolations(
                p,
                FALSE,
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn post_solve_stats_zero_before_solve() {
        // error-path: GetIpoptIterCount
        // error-path: GetIpoptSolveTime
        // error-path: GetIpoptPrimalInf
        // error-path: GetIpoptDualInf
        // error-path: GetIpoptComplInf
        let p = create_unconstrained();
        unsafe {
            assert_eq!(GetIpoptIterCount(p), 0);
            assert_eq!(GetIpoptSolveTime(p), 0.0);
            assert_eq!(GetIpoptPrimalInf(p), 0.0);
            assert_eq!(GetIpoptDualInf(p), 0.0);
            assert_eq!(GetIpoptComplInf(p), 0.0);
            FreeIpoptProblem(p);
        }
    }

    #[test]
    fn post_solve_stats_populated_after_solve() {
        // Reuse the same quadratic as the end-to-end solve test.
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };
        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        // After a successful solve, iter count is recorded (>= 0) and
        // wall time is non-negative; primal/dual/compl norms exist.
        unsafe {
            assert!(GetIpoptIterCount(p) >= 0);
            assert!(GetIpoptSolveTime(p) >= 0.0);
            assert!(GetIpoptPrimalInf(p).is_finite());
            assert!(GetIpoptDualInf(p).is_finite());
            assert!(GetIpoptComplInf(p).is_finite());
            FreeIpoptProblem(p);
        }
    }

    /// The linear-solver post-mortem is reported for a real solve, and
    /// reports the backend that actually ran rather than the one the
    /// option asked for — which is the question a caller pinning
    /// `linear_solver` is really asking.
    #[test]
    fn linear_solver_stats_populated_after_solve() {
        // error-path: GetPounceLinearSolverStats
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };
        let mut stats = unsafe { std::mem::zeroed::<PounceLinearSolverStats>() };
        // Nothing to report before the first solve.
        assert_eq!(unsafe { GetPounceLinearSolverStats(p, &mut stats) }, FALSE);

        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        assert_eq!(unsafe { GetPounceLinearSolverStats(p, &mut stats) }, TRUE);

        let name = unsafe { CStr::from_ptr(stats.solver_name.as_ptr()) }
            .to_str()
            .expect("solver name is ASCII");
        assert_eq!(name, "feral", "default backend should report itself");
        assert!(stats.n_factors > 0, "n_factors = {}", stats.n_factors);
        assert_eq!(
            stats.n_pattern_reuse + stats.n_pattern_changes,
            stats.n_factors,
            "every factor is either a pattern reuse or a pattern change"
        );
        // Optional fields are either a real value or the documented
        // sentinel — never a silent zero.
        assert!(stats.max_fill_ratio.is_nan() || stats.max_fill_ratio > 0.0);
        assert!(stats.last_nnz_l == -1 || stats.last_nnz_l > 0);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn option_type_reports_the_setter_a_keyword_expects() {
        // error-path: GetPounceOptionType
        let p = create_unconstrained();
        let ty = |s: &str| {
            let c = std::ffi::CString::new(s).unwrap();
            unsafe { GetPounceOptionType(p, c.as_ptr()) }
        };
        assert_eq!(ty("tol"), 1, "tol is a number");
        assert_eq!(ty("max_iter"), 2, "max_iter is an integer");
        assert_eq!(ty("linear_solver"), 3, "linear_solver is a string");
        // `hessian_approximation` is the option the CasADi plugin has to
        // set as a string while the user may well type it as one too.
        assert_eq!(ty("hessian_approximation"), 3);
        // Unregistered, and NULL keyword, both answer "unknown" rather
        // than guessing a type.
        assert_eq!(ty("no_such_option_at_all"), 0);
        assert_eq!(unsafe { GetPounceOptionType(p, std::ptr::null()) }, 0);
        unsafe { FreeIpoptProblem(p) };
    }

    /// A NULL problem handle answers from the same registry — the case a
    /// code generator is in, having no problem to ask.
    #[test]
    fn option_type_answers_without_a_problem_handle() {
        let ty = |s: &str| {
            let c = std::ffi::CString::new(s).unwrap();
            unsafe { GetPounceOptionType(std::ptr::null_mut(), c.as_ptr()) }
        };
        assert_eq!(ty("tol"), 1);
        assert_eq!(ty("max_iter"), 2);
        assert_eq!(ty("linear_solver"), 3);
        assert_eq!(ty("no_such_option_at_all"), 0);

        // …and the same answers a live problem gives, which is the
        // property that keeps the two paths from drifting apart.
        let p = create_unconstrained();
        for name in [
            "tol",
            "max_iter",
            "linear_solver",
            "mu_strategy",
            "print_level",
        ] {
            let c = std::ffi::CString::new(name).unwrap();
            assert_eq!(
                unsafe { GetPounceOptionType(std::ptr::null_mut(), c.as_ptr()) },
                unsafe { GetPounceOptionType(p, c.as_ptr()) },
                "handle-free and problem-bound disagree on {name}"
            );
        }
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn write_solve_report_emits_v1_json_with_iter_history() {
        // Quadratic — Newton driver, single iter; just exercises the
        // post-solve report path end-to-end.
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };

        // Write before any solve must fail.
        let cpath = CString::new("/tmp/pounce_cinterface_no_solve.json").unwrap();
        let bad = unsafe { IpoptWriteSolveReport(p, cpath.as_ptr(), std::ptr::null()) };
        assert_eq!(bad, FALSE);

        // Enable per-iter capture, solve, then write at detail = full.
        assert_eq!(unsafe { IpoptEnableIterHistory(p) }, TRUE);
        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);

        let dir = std::env::temp_dir();
        let path = dir.join("pounce_cinterface_report.json");
        let cpath = CString::new(path.to_str().unwrap()).unwrap();
        let cdetail = CString::new("full").unwrap();
        let ok = unsafe { IpoptWriteSolveReport(p, cpath.as_ptr(), cdetail.as_ptr()) };
        assert_eq!(ok, TRUE);

        // Read it back and check the schema tag + that it parses with
        // the same struct shape pounce-cli uses.
        let txt = std::fs::read_to_string(&path).unwrap();
        assert!(
            txt.contains("\"schema\": \"pounce.solve-report/v1\""),
            "{txt}"
        );
        assert!(txt.contains("\"kind\": \"tnlp-direct\""));
        let parsed: pounce_solve_report::SolveReport = serde_json::from_str(&txt).unwrap();
        assert_eq!(parsed.problem.n_variables, 1);
        assert_eq!(parsed.problem.n_constraints, 0);

        // Invalid detail string is rejected.
        let bad_detail = CString::new("verbose").unwrap();
        let bad = unsafe { IpoptWriteSolveReport(p, cpath.as_ptr(), bad_detail.as_ptr()) };
        assert_eq!(bad, FALSE);

        let _ = std::fs::remove_file(&path);
        unsafe { FreeIpoptProblem(p) };
    }

    // --- Intermediate-callback wiring (issue #19, follow-up) ---
    //
    // The callback only fires on the IPM path (`optimize_constrained`).
    // Unconstrained problems short-circuit through the Newton driver,
    // so these tests use a single-inequality problem to force the IPM.

    unsafe extern "C" fn cb_quad_eval_g(
        _n: Index,
        x: *const Number,
        _new_x: Bool,
        _m: Index,
        g: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            *g.offset(0) = *x.offset(0);
            TRUE
        }
    }
    unsafe extern "C" fn cb_quad_eval_jac_g(
        _n: Index,
        _x: *const Number,
        _new_x: Bool,
        _m: Index,
        nele_jac: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            assert_eq!(nele_jac, 1);
            if !irow.is_null() {
                *irow.offset(0) = 0;
                *jcol.offset(0) = 0;
            }
            if !values.is_null() {
                *values.offset(0) = 1.0;
            }
            TRUE
        }
    }
    unsafe extern "C" fn cb_quad_eval_h(
        _n: Index,
        _x: *const Number,
        _new_x: Bool,
        obj_factor: Number,
        _m: Index,
        _lambda: *const Number,
        _new_lambda: Bool,
        _nele_hess: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        _user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            if !irow.is_null() {
                *irow.offset(0) = 0;
                *jcol.offset(0) = 0;
            }
            if !values.is_null() {
                *values.offset(0) = 2.0 * obj_factor;
            }
            TRUE
        }
    }

    fn create_callback_test_problem() -> IpoptProblem {
        // min (x - 2)^2  s.t.  -10 <= x <= 10 (single inequality).
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let gl = [-10.0];
        let gu = [10.0];
        unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                1,
                gl.as_ptr(),
                gu.as_ptr(),
                1,
                1,
                0,
                Some(quad_eval_f),
                Some(cb_quad_eval_g),
                Some(quad_eval_grad_f),
                Some(cb_quad_eval_jac_g),
                Some(cb_quad_eval_h),
            )
        }
    }

    static CB_ITER_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    static CB_LAST_ITER: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
    static CB_INSPECTOR_OK: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    unsafe extern "C" fn counting_cb(
        _alg_mod: Index,
        iter_count: Index,
        _obj_value: Number,
        _inf_pr: Number,
        _inf_du: Number,
        _mu: Number,
        _d_norm: Number,
        _regularization_size: Number,
        _alpha_du: Number,
        _alpha_pr: Number,
        _ls_trials: Index,
        user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            CB_ITER_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            CB_LAST_ITER.store(iter_count, std::sync::atomic::Ordering::SeqCst);
            // user_data carries the IpoptProblem so we can exercise the
            // inspector from inside the callback.
            let problem = user_data as IpoptProblem;
            let mut x = [0.0_f64];
            let rc = GetIpoptCurrentIterate(
                problem,
                FALSE,
                1,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                1,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            );
            if rc == TRUE && x[0].is_finite() {
                CB_INSPECTOR_OK.store(true, std::sync::atomic::Ordering::SeqCst);
            }
            TRUE
        }
    }

    #[test]
    fn intermediate_callback_fires_per_iteration_and_inspector_reads_x() {
        CB_ITER_COUNTER.store(0, std::sync::atomic::Ordering::SeqCst);
        CB_LAST_ITER.store(-1, std::sync::atomic::Ordering::SeqCst);
        CB_INSPECTOR_OK.store(false, std::sync::atomic::Ordering::SeqCst);

        let p = create_callback_test_problem();
        assert!(!p.is_null());
        let ok = unsafe { SetIntermediateCallback(p, Some(counting_cb)) };
        assert_eq!(ok, TRUE);
        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                p as *mut c_void,
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        // At least the iter-0 fire happened, plus one per accepted step.
        let n_fires = CB_ITER_COUNTER.load(std::sync::atomic::Ordering::SeqCst);
        assert!(n_fires >= 2, "callback fired {n_fires} times, want >=2");
        assert!(
            CB_LAST_ITER.load(std::sync::atomic::Ordering::SeqCst) >= 1,
            "last iter should be >= 1 after at least one accepted step"
        );
        assert!(
            CB_INSPECTOR_OK.load(std::sync::atomic::Ordering::SeqCst),
            "GetIpoptCurrentIterate did not return a usable x"
        );
        unsafe { FreeIpoptProblem(p) };
    }

    static CB_VIOL_OK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

    // Bounded variant of `create_callback_test_problem`: x in [0, 10] with a
    // finite lower bound, so the `x_l_violation` / `x_u_violation` branches of
    // GetIpoptCurrentViolations actually scatter a real `x_L`/`x_U` mapping
    // (not the degenerate "no bound" pack).
    fn create_bounded_callback_test_problem() -> IpoptProblem {
        // min (x - 2)^2  s.t.  -10 <= x <= 10,  x in [0, 10].
        let xl = [0.0];
        let xu = [10.0];
        let gl = [-10.0];
        let gu = [10.0];
        unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                1,
                gl.as_ptr(),
                gu.as_ptr(),
                1,
                1,
                0,
                Some(quad_eval_f),
                Some(cb_quad_eval_g),
                Some(quad_eval_grad_f),
                Some(cb_quad_eval_jac_g),
                Some(cb_quad_eval_h),
            )
        }
    }

    unsafe extern "C" fn violations_inspecting_cb(
        _alg_mod: Index,
        _iter_count: Index,
        _obj_value: Number,
        _inf_pr: Number,
        _inf_du: Number,
        _mu: Number,
        _d_norm: Number,
        _regularization_size: Number,
        _alpha_du: Number,
        _alpha_pr: Number,
        _ls_trials: Index,
        user_data: *mut c_void,
    ) -> Bool {
        unsafe {
            let problem = user_data as IpoptProblem;
            // Exercise the bound-violation branches (n=1, m=1) from inside an
            // installed intermediate context. Pre-L51 these branches indexed
            // `v[i]` without a length guard; the fix makes them return FALSE on
            // a packed-length mismatch instead of panicking across `extern "C"`.
            let mut x_l_viol = [f64::NAN];
            let mut x_u_viol = [f64::NAN];
            let rc = GetIpoptCurrentViolations(
                problem,
                FALSE,
                1,
                x_l_viol.as_mut_ptr(),
                x_u_viol.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                1,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            );
            if rc == TRUE
                && x_l_viol[0].is_finite()
                && x_l_viol[0] >= 0.0
                && x_u_viol[0].is_finite()
                && x_u_viol[0] >= 0.0
            {
                CB_VIOL_OK.store(true, std::sync::atomic::Ordering::SeqCst);
            }
            TRUE
        }
    }

    #[test]
    fn get_current_violations_inside_callback_reports_finite_bounds() {
        CB_VIOL_OK.store(false, std::sync::atomic::Ordering::SeqCst);
        let p = create_bounded_callback_test_problem();
        assert!(!p.is_null());
        let ok = unsafe { SetIntermediateCallback(p, Some(violations_inspecting_cb)) };
        assert_eq!(ok, TRUE);
        let mut x = [5.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                p as *mut c_void,
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        assert!(
            CB_VIOL_OK.load(std::sync::atomic::Ordering::SeqCst),
            "GetIpoptCurrentViolations did not return finite, non-negative \
             bound violations from inside the callback"
        );
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn bound_violation_scatter_rejects_oversized_pack_instead_of_panicking() {
        // L51 fail-first (logic level): reproduce the scatter of the
        // `x_l_violation` / `x_u_violation` branches. The packed vector comes
        // from `pack_z_*_for_user`, whose length must equal the output `n`.
        // Pre-fix the branches scattered it with `for (i, s) in
        // packed.enumerate() { v[i] = ... }` over a `vec![0.0; n]` *without*
        // checking the length; an oversized pack indexes `v[i]` out of bounds
        // and panics — and across the real `extern "C"` boundary that panic
        // aborts the embedding process. The fix adds the same length guard
        // the sibling (`compl_*`, `grad_lag_x`) branches already had.
        let n_us = 1usize;
        let packed = [0.5_f64, -0.3]; // len 2 != n_us == 1

        // Pre-fix: the unguarded scatter panics on the oversized pack.
        let unguarded = std::panic::catch_unwind(|| {
            let mut v = vec![0.0; n_us];
            for (i, s) in packed.iter().enumerate() {
                v[i] = (-s).max(0.0);
            }
            v
        });
        assert!(
            unguarded.is_err(),
            "unguarded scatter should panic (→ abort across extern \"C\") on an oversized pack"
        );

        // Post-fix: the length guard returns an error instead of panicking.
        let guarded: Result<Vec<f64>, ()> = (|| {
            if packed.len() != n_us {
                return Err(());
            }
            let mut v = vec![0.0; n_us];
            for (i, s) in packed.iter().enumerate() {
                v[i] = (-s).max(0.0);
            }
            Ok(v)
        })();
        assert!(
            guarded.is_err(),
            "guarded scatter should reject the length mismatch (return FALSE), not panic"
        );
    }

    unsafe extern "C" fn user_stop_cb(
        _alg_mod: Index,
        _iter_count: Index,
        _obj_value: Number,
        _inf_pr: Number,
        _inf_du: Number,
        _mu: Number,
        _d_norm: Number,
        _regularization_size: Number,
        _alpha_du: Number,
        _alpha_pr: Number,
        _ls_trials: Index,
        _user_data: *mut c_void,
    ) -> Bool {
        FALSE
    }

    #[test]
    fn intermediate_callback_false_surfaces_user_requested_stop() {
        let p = create_callback_test_problem();
        assert!(!p.is_null());
        let ok = unsafe { SetIntermediateCallback(p, Some(user_stop_cb)) };
        assert_eq!(ok, TRUE);
        let mut x = [0.0_f64];
        let rc = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::UserRequestedStop as Index);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn ffi_guard_converts_panic_to_fallback() {
        // L56: a panic in pounce's own Rust code during a solve must be
        // caught at the FFI boundary and reported as `Internal_Error`, never
        // unwound across `extern "C"` (which aborts the embedding process).
        // This exercises the exact mechanism wrapping IpoptSolve /
        // IpoptSolveWarmStart. (The "boom" panic message printing to stderr
        // is expected — the default panic hook still runs before the catch.)
        let fallback = ApplicationReturnStatus::InternalError as Index;
        let got = ffi_guard(fallback, || -> Index {
            panic!("boom inside solver core");
        });
        assert_eq!(got, fallback);
        assert_eq!(got, ApplicationReturnStatus::InternalError as Index);
    }

    #[test]
    fn ffi_guard_is_transparent_on_success() {
        // On the happy path the guard returns the body's value unchanged, so
        // wrapping IpoptSolve does not alter normal solves (the end-to-end
        // solve tests above confirm this at the public-API level).
        let got = ffi_guard(-99, || 7);
        assert_eq!(got, 7);
    }

    #[test]
    fn parse_pkg_version_handles_missing_components() {
        assert_eq!(parse_pkg_version("1.2.3"), (1, 2, 3));
        assert_eq!(parse_pkg_version("4.5"), (4, 5, 0));
        assert_eq!(parse_pkg_version(""), (0, 0, 0));
        assert_eq!(parse_pkg_version("1.x.3"), (1, 0, 3));
    }

    // ---- Solver-session C ABI (crate::solver) ----

    use crate::solver::{
        IpoptCreateSolver, IpoptFreeSolver, IpoptSolverGetKktDim, IpoptSolverKktSolve,
        IpoptSolverSolve,
    };

    #[test]
    fn solver_create_consumes_problem_handle() {
        let mut p = create_unconstrained();
        assert!(!p.is_null());
        let s = unsafe { IpoptCreateSolver(&mut p) };
        assert!(!s.is_null());
        assert!(
            p.is_null(),
            "IpoptCreateSolver should NULL out the caller's handle"
        );
        unsafe { IpoptFreeSolver(s) };
    }

    #[test]
    fn solver_create_null_inputs_return_null() {
        // error-path: IpoptCreateSolver
        // NULL pointer-to-handle.
        let s = unsafe { IpoptCreateSolver(std::ptr::null_mut()) };
        assert!(s.is_null());
        // Pointer to a NULL handle.
        let mut p: IpoptProblem = std::ptr::null_mut();
        let s = unsafe { IpoptCreateSolver(&mut p) };
        assert!(s.is_null());
    }

    #[test]
    fn solver_free_null_is_safe() {
        // error-path: IpoptFreeSolver
        unsafe { IpoptFreeSolver(std::ptr::null_mut()) };
    }

    #[test]
    fn solver_solve_drives_quadratic_and_retains_factor() {
        let xl = [-1.0e20];
        let xu = [1.0e20];
        let mut p = unsafe {
            CreateIpoptProblem(
                1,
                xl.as_ptr(),
                xu.as_ptr(),
                0,
                std::ptr::null(),
                std::ptr::null(),
                0,
                1,
                0,
                Some(quad_eval_f),
                None,
                Some(quad_eval_grad_f),
                None,
                Some(quad_eval_h),
            )
        };
        assert!(!p.is_null());
        let s = unsafe { IpoptCreateSolver(&mut p) };
        assert!(!s.is_null());
        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc = unsafe {
            IpoptSolverSolve(
                s,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc, ApplicationReturnStatus::SolveSucceeded as Index);
        assert!((x[0] - 2.0).abs() < 1e-6);
        assert!(obj.abs() < 1e-10);

        // After convergence the factor is retained — kkt_dim is positive
        // and a zero RHS back-solves to zero.
        let dim = unsafe { IpoptSolverGetKktDim(s) };
        assert!(dim > 0, "expected positive KKT dim, got {dim}");
        let rhs = vec![0.0_f64; dim as usize];
        let mut lhs = vec![1.0_f64; dim as usize];
        let ok = unsafe { IpoptSolverKktSolve(s, rhs.as_ptr(), lhs.as_mut_ptr()) };
        assert_eq!(ok, TRUE);
        for (i, v) in lhs.iter().enumerate() {
            assert!(v.abs() < 1e-10, "lhs[{i}] = {v} not ~0");
        }
        unsafe { IpoptFreeSolver(s) };
    }

    #[test]
    fn solver_kkt_dim_minus_one_before_solve() {
        // error-path: IpoptSolverGetKktDim
        let mut p = create_unconstrained();
        let s = unsafe { IpoptCreateSolver(&mut p) };
        assert_eq!(unsafe { IpoptSolverGetKktDim(s) }, -1);
        unsafe { IpoptFreeSolver(s) };
    }

    // ─────────────────────────────────────────────────────────
    // §7.2 SQP working-set warm-start C ABI tests.
    // ─────────────────────────────────────────────────────────

    #[test]
    fn c_get_working_set_returns_false_before_any_solve() {
        // error-path: IpoptGetWorkingSet
        let p = create_unconstrained();
        let mut bound_buf = [0; 4];
        let rc = unsafe { IpoptGetWorkingSet(p, bound_buf.as_mut_ptr(), std::ptr::null_mut()) };
        assert_eq!(rc, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn c_set_warm_start_with_both_null_returns_false() {
        let p = create_unconstrained();
        let rc = unsafe { IpoptSetWarmStartWorkingSet(p, std::ptr::null(), std::ptr::null()) };
        assert_eq!(rc, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn c_set_warm_start_with_bad_status_code_returns_false() {
        // error-path: IpoptSetWarmStartWorkingSet
        let p = create_unconstrained();
        // Length n = 4; '7' is out of range (valid: 0..=3).
        let bogus = [
            POUNCE_WS_INACTIVE,
            7,
            POUNCE_WS_AT_LOWER,
            POUNCE_WS_INACTIVE,
        ];
        let rc = unsafe { IpoptSetWarmStartWorkingSet(p, bogus.as_ptr(), std::ptr::null()) };
        assert_eq!(rc, FALSE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn c_set_warm_start_then_clear_succeeds() {
        let p = create_unconstrained();
        let in_buf = [POUNCE_WS_INACTIVE; 4];
        let set_rc = unsafe { IpoptSetWarmStartWorkingSet(p, in_buf.as_ptr(), std::ptr::null()) };
        assert_eq!(set_rc, TRUE);
        let clr_rc = unsafe { IpoptClearWarmStartWorkingSet(p) };
        assert_eq!(clr_rc, TRUE);
        unsafe { FreeIpoptProblem(p) };
    }

    #[test]
    fn c_set_warm_start_on_null_problem_returns_false() {
        let in_buf = [POUNCE_WS_INACTIVE; 1];
        let rc = unsafe {
            IpoptSetWarmStartWorkingSet(std::ptr::null_mut(), in_buf.as_ptr(), std::ptr::null())
        };
        assert_eq!(rc, FALSE);
    }

    #[test]
    fn c_solve_warm_start_round_trips_working_set_on_sqp_path() {
        // Use the 1-D `(x − 2)²` quadratic from
        // `create_callback_test_problem`. Set `algorithm
        // active-set-sqp`, solve, then read the working set
        // through `IpoptGetWorkingSet`. Pass it back via
        // `IpoptSolveWarmStart` for a second solve.
        let p = create_callback_test_problem();
        let key = CString::new("algorithm").unwrap();
        let val = CString::new("active-set-sqp").unwrap();
        let ok = unsafe { AddIpoptStrOption(p, key.as_ptr(), val.as_ptr()) };
        assert_eq!(ok, TRUE);

        let mut x = [0.0_f64];
        let mut obj = 0.0_f64;
        let rc1 = unsafe {
            IpoptSolve(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc1, ApplicationReturnStatus::SolveSucceeded as Index);

        let mut bound_buf = [-1; 1];
        let mut cons_buf = [-1; 1];
        let got = unsafe { IpoptGetWorkingSet(p, bound_buf.as_mut_ptr(), cons_buf.as_mut_ptr()) };
        assert_eq!(got, TRUE);
        // Status codes must be in 0..=3.
        assert!((0..=3).contains(&bound_buf[0]));
        assert!((0..=3).contains(&cons_buf[0]));

        // Second solve with the just-retrieved working set as
        // input. Resets x to a non-optimal starting point so the
        // SQP loop actually has work to do; the warm-start
        // should still converge to the optimum.
        x[0] = 0.0;
        let mut obj2 = 0.0_f64;
        let mut bound_out = [-1; 1];
        let mut cons_out = [-1; 1];
        let rc2 = unsafe {
            IpoptSolveWarmStart(
                p,
                x.as_mut_ptr(),
                std::ptr::null_mut(),
                &mut obj2,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                bound_buf.as_ptr(),
                cons_buf.as_ptr(),
                bound_out.as_mut_ptr(),
                cons_out.as_mut_ptr(),
                std::ptr::null_mut(),
            )
        };
        assert_eq!(rc2, ApplicationReturnStatus::SolveSucceeded as Index);
        assert!((0..=3).contains(&bound_out[0]));
        assert!((0..=3).contains(&cons_out[0]));

        unsafe { FreeIpoptProblem(p) };
    }

    // ---- complementarity outcome encodings (gh#1147) ----
    //
    // The integration tests (`tests/complementarity_getters.rs`) reach the
    // S, W, none and not-searched classes, the answer / weak-fallback /
    // verdict reports, the B verdict and a taken polish through real
    // solves. What no in-repo model reaches is held here, on a synthetic
    // driver record: no certificate, a feasible-uncertified report, the
    // not_B and not_checked verdicts, a polish that was not taken, and
    // non-finite reals.

    fn synthetic_outcome() -> pounce_restoration::mpcc_driver::MpccOutcome {
        use pounce_algorithm::mpcc::{
            Certificate, MpccStage, Reported, StationarityClass, Strategy,
        };
        use pounce_restoration::mpcc_driver::{MpccOutcome, MpccSolveRecord};
        MpccOutcome {
            status: ApplicationReturnStatus::SolveSucceeded,
            statistics: SolveStatistics::default(),
            accepted_by: Some(MpccStage::Exact),
            fallback: None,
            reported: Reported::Answer(MpccStage::Exact),
            strategy: Strategy::Continuation,
            solves: vec![MpccSolveRecord {
                stage: MpccStage::Branch,
                tau: None,
                status: ApplicationReturnStatus::MaximumIterationsExceeded,
                iterations: 7,
                budget_iterations: 7,
                max_abs_product: Number::INFINITY,
                seconds: Number::NAN,
            }],
            total_iterations: 7,
            x: vec![0.0],
            max_abs_product: Number::INFINITY,
            certificate: Some(Certificate {
                class: StationarityClass::S,
                n_pairs: 1,
                n_biactive: 0,
                n_neither: 0,
                multipliers_unique: true,
                residual: 0.0,
                resid_tol: Number::INFINITY,
                tight: true,
                primal_violation: 0.0,
                feasible: true,
                worst_biactive_sign: 0.0,
                multipliers: None,
            }),
            b_check: None,
            escapes: 3,
            lifted: 2,
            natural_residual: None,
            polish: None,
            polish_threshold: 1e-7,
        }
    }

    fn c_label(chars: &[c_char]) -> String {
        unsafe { CStr::from_ptr(chars.as_ptr()) }
            .to_str()
            .unwrap()
            .to_string()
    }

    #[test]
    fn complementarity_encodings_absent_certificate_and_non_finite_reals() {
        let mut out = synthetic_outcome();
        out.certificate = None;
        let s = complementarity_stats(&out);
        assert_eq!(s.certificate_class, POUNCE_CC_CLASS_ABSENT);
        assert_eq!(
            (
                s.n_pairs,
                s.n_biactive,
                s.n_neither,
                s.multipliers_unique,
                s.tight,
                s.feasible
            ),
            (-1, -1, -1, -1, -1, -1)
        );
        assert!(s.residual.is_nan() && s.resid_tol.is_nan() && s.primal_violation.is_nan());
        // Non-finite reals read NaN (the report's `null`), an absent
        // natural residual too.
        assert!(s.max_abs_product.is_nan() && s.natural_residual.is_nan());
        assert_eq!(c_label(&s.strategy), "continuation");
        assert_eq!(c_label(&s.accepted_by), "exact product");
        assert_eq!(c_label(&s.fallback), "");
        assert_eq!((s.escapes, s.lifted), (3, 2));
        // The summary still exists without a certificate.
        assert!(complementarity_text(&out, POUNCE_CC_TEXT_SUMMARY).is_some());

        // With a certificate, a non-finite band reads NaN, the rest as is.
        let s = complementarity_stats(&synthetic_outcome());
        assert_eq!(s.certificate_class, POUNCE_CC_CLASS_S);
        assert!(s.resid_tol.is_nan());
        assert_eq!(
            (s.n_pairs, s.multipliers_unique, s.tight, s.feasible),
            (1, 1, 1, 1)
        );

        let r = complementarity_solve(&out.solves[0]);
        assert_eq!(c_label(&r.stage), "branch NLP");
        assert_eq!((r.relaxed, r.status, r.iterations), (0, -1, 7));
        assert!(r.tau.is_nan() && r.max_abs_product.is_nan() && r.seconds.is_nan());
    }

    #[test]
    fn complementarity_encodings_every_reported_and_class() {
        use pounce_algorithm::mpcc::{MpccStage, Reported, StationarityClass};
        let mut out = synthetic_outcome();
        for (reported, code) in [
            (
                Reported::Answer(MpccStage::Exact),
                POUNCE_CC_REPORTED_ANSWER,
            ),
            (
                Reported::WeakFallback(MpccStage::Penalty),
                POUNCE_CC_REPORTED_WEAK_FALLBACK,
            ),
            (
                Reported::FeasibleUncertified(MpccStage::Continuation),
                POUNCE_CC_REPORTED_FEASIBLE_UNCERTIFIED,
            ),
            (Reported::Verdict, POUNCE_CC_REPORTED_VERDICT),
        ] {
            out.reported = reported;
            assert_eq!(complementarity_stats(&out).reported, code, "{reported:?}");
        }
        for (class, code) in [
            (StationarityClass::S, POUNCE_CC_CLASS_S),
            (StationarityClass::W, POUNCE_CC_CLASS_W),
            (StationarityClass::None, POUNCE_CC_CLASS_NONE),
            (StationarityClass::NotSearched, POUNCE_CC_CLASS_NOT_SEARCHED),
        ] {
            out.certificate.as_mut().unwrap().class = class;
            assert_eq!(
                complementarity_stats(&out).certificate_class,
                code,
                "{class:?}"
            );
        }
    }

    #[test]
    fn complementarity_encodings_b_verdicts_and_b_reason() {
        use pounce_algorithm::mpcc::{BCheck, BVerdict};
        let mut out = synthetic_outcome();
        assert_eq!(
            complementarity_stats(&out).b_verdict,
            POUNCE_CC_B_VERDICT_ABSENT
        );
        assert_eq!(complementarity_text(&out, POUNCE_CC_TEXT_B_REASON), None);
        for (verdict, code, reason) in [
            (BVerdict::B, POUNCE_CC_B_VERDICT_B, None),
            (
                BVerdict::NotB {
                    held: vec![],
                    decrease: -1.0,
                },
                POUNCE_CC_B_VERDICT_NOT_B,
                None,
            ),
            (
                BVerdict::NotChecked("a branch LP did not solve"),
                POUNCE_CC_B_VERDICT_NOT_CHECKED,
                Some("a branch LP did not solve"),
            ),
        ] {
            out.b_check = Some(BCheck {
                verdict,
                n_biactive: 12,
                branches_solved: 1,
                enumerated: false,
            });
            let s = complementarity_stats(&out);
            assert_eq!(s.b_verdict, code);
            assert_eq!(
                (s.b_n_biactive, s.b_branches_solved, s.b_enumerated),
                (12, 1, 0)
            );
            assert_eq!(
                complementarity_text(&out, POUNCE_CC_TEXT_B_REASON).as_deref(),
                reason
            );
        }
    }

    #[test]
    fn complementarity_encodings_polish_not_taken_has_a_reason() {
        use pounce_restoration::mpcc_driver::PolishRecord;
        let mut out = synthetic_outcome();
        out.polish = Some(PolishRecord {
            taken: false,
            residual_before: 1e-5,
            residual_after: Number::INFINITY,
            reason: Some("the re-solve did not converge".to_string()),
        });
        let s = complementarity_stats(&out);
        assert_eq!((s.polish_ran, s.polish_taken), (1, 0));
        assert_eq!(s.polish_residual_before, 1e-5);
        assert!(
            s.polish_residual_after.is_nan(),
            "unmeasured after reads NaN"
        );
        assert_eq!(
            complementarity_text(&out, POUNCE_CC_TEXT_POLISH_REASON).as_deref(),
            Some("the re-solve did not converge")
        );
        // Taken: no reason.
        out.polish = Some(PolishRecord {
            taken: true,
            residual_before: 1e-5,
            residual_after: 0.0,
            reason: None,
        });
        assert_eq!(complementarity_stats(&out).polish_taken, 1);
        assert_eq!(
            complementarity_text(&out, POUNCE_CC_TEXT_POLISH_REASON),
            None
        );
        assert_eq!(complementarity_text(&out, 3), None);
    }

    #[test]
    fn complementarity_labels_truncate_and_terminate() {
        let mut a = [0x7f as c_char; 4];
        copy_label(&mut a, "abcdef");
        assert_eq!(a, [b'a' as c_char, b'b' as c_char, b'c' as c_char, 0]);
        copy_label(&mut a, "x");
        assert_eq!(a, [b'x' as c_char, 0, 0, 0], "the tail is cleared");
        // Every stage label fits the 32-byte fields with room for the NUL.
        use pounce_algorithm::mpcc::MpccStage::*;
        for s in [Exact, Continuation, Penalty, Branch, Polish] {
            assert!(s.label().len() < 32, "{}", s.label());
        }
        use pounce_algorithm::mpcc::Strategy;
        for s in [Strategy::Both, Strategy::Exact, Strategy::Continuation] {
            assert!(s.name().len() < 16, "{}", s.name());
        }
    }

    // ----- AddPounceComplementsConstraint (gh#1147): the mapping and the
    // re-validation branch no public call reaches.

    #[test]
    fn complements_row_reads_every_table_row_and_refuses_nan_and_crossed() {
        use ComplementsRow::*;
        let inf = 2e19;
        assert_eq!(complements_row(0.0, 2.0), Some(Mixed));
        assert_eq!(complements_row(-1.0, inf), Some(Lower));
        assert_eq!(complements_row(-inf, 3.0), Some(Upper));
        assert_eq!(complements_row(-inf, inf), Some(RowFixed));
        assert_eq!(complements_row(1.0, 1.0), Some(VarFixed));
        // The ±1e19 convention of the pair classifier: exactly 1e19 is
        // infinite, just inside it is finite.
        assert_eq!(complements_row(-1e19, 1e19), Some(RowFixed));
        assert_eq!(complements_row(-9.9e18, 1e19), Some(Lower));
        assert_eq!(complements_row(2.0, 1.0), None);
        assert_eq!(complements_row(f64::NAN, 1.0), None);
        assert_eq!(complements_row(0.0, f64::NAN), None);
    }

    #[test]
    fn complements_edits_classify_as_the_native_shape_they_declare() {
        // The debug_assert in `add_complements`, as a test: for each pair
        // row of the table, the edited bounds of a free row are exactly the
        // native shape, and a no-pair row declares nothing.
        let inf = 2e19;
        for (xl, xu, want) in [
            (0.0, 2.0, ComplementsRow::Mixed),
            (-1.0, inf, ComplementsRow::Lower),
            (-inf, 3.0, ComplementsRow::Upper),
        ] {
            let row = complements_row(xl, xu).unwrap();
            assert_eq!(row, want);
            let (gl, gu, declares) = row.row_bounds(-inf, inf);
            assert!(declares);
            let shape = classify_pair(xl, xu, gl, gu);
            assert!(row.shape_matches(shape), "{row:?}: {shape:?}");
        }
        assert_eq!(
            ComplementsRow::RowFixed.row_bounds(-inf, inf),
            (0.0, 0.0, false)
        );
        assert_eq!(
            ComplementsRow::VarFixed.row_bounds(-inf, inf),
            (-inf, inf, false)
        );
        // `shape_matches` refuses a wrong shape, so the assert can fire.
        assert!(!ComplementsRow::Mixed.shape_matches(None));
        assert!(!ComplementsRow::Lower.shape_matches(classify_pair(0.0, 2.0, -inf, inf)));
    }

    /// Two variables, two free rows, no callback is ever called.
    fn create_two_by_two(x_l: [Number; 2], x_u: [Number; 2]) -> IpoptProblem {
        let g_l = [-2e19, -2e19];
        let g_u = [2e19, 2e19];
        let p = unsafe {
            CreateIpoptProblem(
                2,
                x_l.as_ptr(),
                x_u.as_ptr(),
                2,
                g_l.as_ptr(),
                g_u.as_ptr(),
                0,
                0,
                0,
                Some(quad_eval_f),
                Some(cb_quad_eval_g),
                Some(quad_eval_grad_f),
                Some(cb_quad_eval_jac_g),
                Some(cb_quad_eval_h),
            )
        };
        assert!(!p.is_null());
        p
    }

    /// Every (row, var) of the declared set and of the Complements ledger is
    /// found by the maps, and nothing else is.
    fn assert_maps_match(p: IpoptProblem) {
        let i = unsafe { &*p };
        for (k, q) in i.complementarity.iter().enumerate() {
            assert_eq!(i.complementarity.of_var(q.var), Some(k));
            assert_eq!(i.complementarity.of_row(q.row), Some(k));
        }
        for (k, u) in i.complements_used.iter().enumerate() {
            assert_eq!(i.complements_used.of_var(u.var), Some(k));
            assert_eq!(i.complements_used.of_row(u.row), Some(k));
        }
        for j in 0..i.n.max(i.m) as usize {
            assert_eq!(
                i.complementarity.of_var(j).is_some(),
                i.complementarity.iter().any(|q| q.var == j)
            );
            assert_eq!(
                i.complementarity.of_row(j).is_some(),
                i.complementarity.iter().any(|q| q.row == j)
            );
            assert_eq!(
                i.complements_used.of_var(j).is_some(),
                i.complements_used.iter().any(|u| u.var == j)
            );
            assert_eq!(
                i.complements_used.of_row(j).is_some(),
                i.complements_used.iter().any(|u| u.row == j)
            );
        }
    }

    #[test]
    fn pair_maps_follow_every_declaration_path() {
        // error-path: AddPounceComplementarityPair
        // gh#1147 Stage 2 (S2-I1): the one-pair declarations find duplicates
        // through var/row maps instead of re-validating the stored set, so
        // the maps must follow Add, Set (accepted and refused), Clear and
        // the Complements helper, and a refused call must leave them as
        // they were.
        let p = create_two_by_two([0.0, 0.0], [2.0, 2.0]);
        unsafe {
            assert_eq!(AddPounceComplementarityPair(p, 0, 0), POUNCE_OK);
            assert_maps_match(p);
            assert_eq!(
                AddPounceComplementarityPair(p, 1, 0),
                POUNCE_ERR_VAR_ALREADY_PAIRED
            );
            assert_eq!(
                AddPounceComplementarityPair(p, 0, 1),
                POUNCE_ERR_ROW_ALREADY_PAIRED
            );
            assert_maps_match(p);
            let (rows, vars) = ([1, 0], [0, 1]);
            assert_eq!(
                SetPounceComplementarityPairs(
                    p,
                    2,
                    rows.as_ptr(),
                    vars.as_ptr(),
                    0,
                    std::ptr::null_mut()
                ),
                POUNCE_OK
            );
            assert_maps_match(p);
            assert_eq!((*p).complementarity.of_var(0), Some(0));
            assert_eq!((*p).complementarity.of_row(1), Some(0));
            let (rows, vars) = ([0, 0], [0, 1]);
            assert_eq!(
                SetPounceComplementarityPairs(
                    p,
                    2,
                    rows.as_ptr(),
                    vars.as_ptr(),
                    0,
                    std::ptr::null_mut()
                ),
                POUNCE_ERR_ROW_ALREADY_PAIRED
            );
            assert_eq!((*p).complementarity.of_row(1), Some(0));
            assert_maps_match(p);
            assert_eq!(ClearPounceComplementarityPairs(p), TRUE);
            assert_maps_match(p);
            assert_eq!((&*p).complementarity.of_var(0), None);
            assert_eq!(
                AddPounceComplementsConstraint(p, 1, 1),
                POUNCE_COMPLEMENTS_PAIR_MIXED
            );
            assert_maps_match(p);
            assert_eq!(
                AddPounceComplementsConstraint(p, 0, 1),
                POUNCE_ERR_VAR_ALREADY_PAIRED
            );
            assert_maps_match(p);
            FreeIpoptProblem(p);
        }
    }

    #[test]
    fn complements_records_the_table_row_and_the_callers_row_bounds() {
        // gh#1147 Stage 2 (S2-I1): the ledger keeps what the edit replaced,
        // which is the user layer SetPounceBounds / GetPounceBounds serve.
        let p = create_two_by_two([0.0, -2e19], [2e19, 2e19]);
        unsafe {
            assert_eq!(
                AddPounceComplementsConstraint(p, 0, 0),
                POUNCE_COMPLEMENTS_PAIR_LOWER
            );
            assert_eq!(
                AddPounceComplementsConstraint(p, 1, 1),
                POUNCE_COMPLEMENTS_ROW_FIXED_NO_PAIR
            );
            let i = &*p;
            assert_eq!(
                i.complements_used[..],
                [
                    ComplementsUse {
                        row: 0,
                        var: 0,
                        table: ComplementsRow::Lower,
                        user_gl: -2e19,
                        user_gu: 2e19
                    },
                    ComplementsUse {
                        row: 1,
                        var: 1,
                        table: ComplementsRow::RowFixed,
                        user_gl: -2e19,
                        user_gu: 2e19
                    },
                ]
            );
            assert_eq!((i.g_l[0], i.g_u[0]), (0.0, 2e19));
            assert_eq!((i.g_l[1], i.g_u[1]), (0.0, 0.0));
            FreeIpoptProblem(p);
        }
    }
}