logicaffeine-kernel 0.9.16

Pure Calculus of Constructions type theory - NO LEXICON
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
//! Term reduction for the Calculus of Constructions.
//!
//! This module implements the evaluation semantics of the kernel. Terms are
//! reduced to normal form using a call-by-name strategy.
//!
//! # Reduction Rules
//!
//! ## Beta Reduction
//! Function application: `(λx. body) arg → body[x := arg]`
//!
//! ## Iota Reduction
//! Pattern matching: `match (Cᵢ args) { ... caseᵢ ... } → caseᵢ(args)`
//!
//! ## Fix Unfolding (Guarded)
//! Recursive definitions: `(fix f. body) (Cᵢ args) → body[f := fix f. body] (Cᵢ args)`
//!
//! Fix unfolding is guarded by requiring the argument to be in constructor form.
//! This ensures termination by structural recursion.
//!
//! ## Delta Reduction
//! Global definitions are expanded when needed during normalization.
//!
//! # Primitive Operations
//!
//! The reducer handles built-in operations on literals:
//! - Arithmetic: `add`, `sub`, `mul`, `div`, `mod`
//! - Comparison: `lt`, `le`, `gt`, `ge`, `eq`
//! - Boolean: `ite` (if-then-else)
//!
//! # Reflection Builtins
//!
//! Special operations for the deep embedding (Syntax type):
//! - `syn_size`: Compute the size of a syntax tree
//! - `syn_max_var`: Find the maximum variable index
//! - `syn_step`, `syn_eval`: Bounded evaluation
//! - `syn_quote`, `syn_diag`: Reification and diagonalization
//!
//! # Fuel Limit
//!
//! Normalization uses a fuel counter (default 10000) to prevent infinite loops.
//! If fuel is exhausted, the current term is returned as-is.

use crate::context::Context;
use crate::omega;
use crate::term::{Literal, Term, Universe};
use crate::type_checker::substitute;

/// Normalize a term to its normal form.
///
/// Repeatedly applies reduction rules until no more reductions are possible.
/// This is a full normalization that reduces under binders.
pub fn normalize(ctx: &Context, term: &Term) -> Term {
    let mut current = term.clone();
    let mut fuel = 10000; // Safety limit to prevent infinite loops

    loop {
        if fuel == 0 {
            // If we hit the fuel limit, return what we have
            return current;
        }
        fuel -= 1;

        let reduced = reduce_step(ctx, &current);
        if reduced == current {
            return current;
        }
        current = reduced;
    }
}

/// Single-step reduction.
///
/// Reduces the outermost redex first (call-by-name), then recurses
/// into subterms for full normalization.
fn reduce_step(ctx: &Context, term: &Term) -> Term {
    match term {
        // Literals are in normal form
        Term::Lit(_) => term.clone(),

        // Beta: (λx. body) arg → body[x := arg]
        Term::App(func, arg) => {
            // First try primitive reduction (add, sub, mul, etc.)
            if let Some(result) = try_primitive_reduce(func, arg) {
                return result;
            }

            // Try reflection builtins (syn_size, syn_max_var)
            if let Some(result) = try_reflection_reduce(ctx, func, arg) {
                return result;
            }

            // Then try to reduce at the head
            match func.as_ref() {
                Term::Lambda { param, body, .. } => {
                    // Beta reduction
                    substitute(body, param, arg)
                }
                // Fix application: (fix f. body) arg
                // We need to check if arg is a constructor to unfold
                Term::Fix { name, body } => {
                    if is_constructor_form(ctx, arg) {
                        // Unfold: (fix f. body) arg → body[f := fix f. body] arg
                        let fix_term = Term::Fix {
                            name: name.clone(),
                            body: body.clone(),
                        };
                        let unfolded = substitute(body, name, &fix_term);
                        Term::App(Box::new(unfolded), arg.clone())
                    } else {
                        // Try reducing the argument first
                        let reduced_arg = reduce_step(ctx, arg);
                        if reduced_arg != **arg {
                            Term::App(func.clone(), Box::new(reduced_arg))
                        } else {
                            term.clone()
                        }
                    }
                }
                // Nested application: ((f x) y) - reduce inner first
                Term::App(_, _) => {
                    let reduced_func = reduce_step(ctx, func);
                    if reduced_func != **func {
                        Term::App(Box::new(reduced_func), arg.clone())
                    } else {
                        // Try reducing argument
                        let reduced_arg = reduce_step(ctx, arg);
                        Term::App(func.clone(), Box::new(reduced_arg))
                    }
                }
                // Other function forms - try reducing function position
                _ => {
                    let reduced_func = reduce_step(ctx, func);
                    if reduced_func != **func {
                        Term::App(Box::new(reduced_func), arg.clone())
                    } else {
                        // Try reducing argument
                        let reduced_arg = reduce_step(ctx, arg);
                        Term::App(func.clone(), Box::new(reduced_arg))
                    }
                }
            }
        }

        // Iota: match (Cᵢ a₁...aₙ) with cases → caseᵢ a₁ ... aₙ
        Term::Match {
            discriminant,
            motive,
            cases,
        } => {
            if let Some((ctor_idx, args)) = extract_constructor(ctx, discriminant) {
                // Select the corresponding case
                let case = &cases[ctor_idx];
                // Apply case to constructor arguments
                let mut result = case.clone();
                for arg in args {
                    result = Term::App(Box::new(result), Box::new(arg));
                }
                // Reduce the result
                reduce_step(ctx, &result)
            } else {
                // Try reducing the discriminant
                let reduced_disc = reduce_step(ctx, discriminant);
                if reduced_disc != **discriminant {
                    Term::Match {
                        discriminant: Box::new(reduced_disc),
                        motive: motive.clone(),
                        cases: cases.clone(),
                    }
                } else {
                    term.clone()
                }
            }
        }

        // Reduce under lambdas (deep normalization)
        Term::Lambda {
            param,
            param_type,
            body,
        } => {
            let reduced_param_type = reduce_step(ctx, param_type);
            let reduced_body = reduce_step(ctx, body);
            if reduced_param_type != **param_type || reduced_body != **body {
                Term::Lambda {
                    param: param.clone(),
                    param_type: Box::new(reduced_param_type),
                    body: Box::new(reduced_body),
                }
            } else {
                term.clone()
            }
        }

        // Reduce under Pi types
        Term::Pi {
            param,
            param_type,
            body_type,
        } => {
            let reduced_param_type = reduce_step(ctx, param_type);
            let reduced_body_type = reduce_step(ctx, body_type);
            if reduced_param_type != **param_type || reduced_body_type != **body_type {
                Term::Pi {
                    param: param.clone(),
                    param_type: Box::new(reduced_param_type),
                    body_type: Box::new(reduced_body_type),
                }
            } else {
                term.clone()
            }
        }

        // Reduce under Fix
        Term::Fix { name, body } => {
            let reduced_body = reduce_step(ctx, body);
            if reduced_body != **body {
                Term::Fix {
                    name: name.clone(),
                    body: Box::new(reduced_body),
                }
            } else {
                term.clone()
            }
        }

        // Base cases: already in normal form
        Term::Sort(_) | Term::Var(_) | Term::Hole => term.clone(),

        // Delta reduction: unfold definitions (but not axioms, constructors, or inductives)
        Term::Global(name) => {
            if let Some(body) = ctx.get_definition_body(name) {
                // Definition found - unfold to body
                body.clone()
            } else {
                // Axiom, constructor, or inductive - no reduction
                term.clone()
            }
        }
    }
}

/// Check if a term is a constructor (possibly applied to arguments).
fn is_constructor_form(ctx: &Context, term: &Term) -> bool {
    extract_constructor(ctx, term).is_some()
}

/// Extract constructor index and VALUE arguments from a term (skipping type arguments).
///
/// Returns `Some((constructor_index, [value_arg1, value_arg2, ...]))` if term is `Cᵢ(type_args..., value_args...)`
/// where `Cᵢ` is the i-th constructor of some inductive type.
///
/// For polymorphic constructors like `Cons A h t`, this returns only [h, t], not [A, h, t].
fn extract_constructor(ctx: &Context, term: &Term) -> Option<(usize, Vec<Term>)> {
    let mut args = Vec::new();
    let mut current = term;

    // Collect arguments from nested applications
    while let Term::App(func, arg) = current {
        args.push((**arg).clone());
        current = func;
    }
    args.reverse();

    // Check if head is a constructor
    if let Term::Global(name) = current {
        if let Some(inductive) = ctx.constructor_inductive(name) {
            let ctors = ctx.get_constructors(inductive);
            for (idx, (ctor_name, ctor_type)) in ctors.iter().enumerate() {
                if *ctor_name == name {
                    // Count type parameters (leading Pis where param_type is a Sort)
                    let num_type_params = count_type_params(ctor_type);

                    // Skip type arguments, return only value arguments
                    let value_args = if num_type_params < args.len() {
                        args[num_type_params..].to_vec()
                    } else {
                        vec![]
                    };

                    return Some((idx, value_args));
                }
            }
        }
    }
    None
}

/// Count leading type parameters in a constructor type.
///
/// Type parameters are Pis where the param_type is a Sort (Type n or Prop).
/// For `Π(A:Type). Π(_:A). Π(_:List A). List A`, this returns 1.
fn count_type_params(ty: &Term) -> usize {
    let mut count = 0;
    let mut current = ty;

    while let Term::Pi { param_type, body_type, .. } = current {
        if is_sort(param_type) {
            count += 1;
            current = body_type;
        } else {
            break;
        }
    }

    count
}

/// Check if a term is a Sort (Type n or Prop).
fn is_sort(term: &Term) -> bool {
    matches!(term, Term::Sort(_))
}

/// Try to reduce a primitive operation.
///
/// Returns Some(result) if this is a fully applied primitive like (add 3 4).
/// Pattern: ((op x) y) where op is a builtin and x, y are literals.
fn try_primitive_reduce(func: &Term, arg: &Term) -> Option<Term> {
    // We need func = (op x) and arg = y
    if let Term::App(op_term, x) = func {
        if let Term::Global(op_name) = op_term.as_ref() {
            if let (Term::Lit(Literal::Int(x_val)), Term::Lit(Literal::Int(y_val))) =
                (x.as_ref(), arg)
            {
                let result = match op_name.as_str() {
                    "add" => x_val.checked_add(*y_val)?,
                    "sub" => x_val.checked_sub(*y_val)?,
                    "mul" => x_val.checked_mul(*y_val)?,
                    "div" => x_val.checked_div(*y_val)?,
                    "mod" => x_val.checked_rem(*y_val)?,
                    _ => return None,
                };
                return Some(Term::Lit(Literal::Int(result)));
            }
        }
    }
    None
}

// -------------------------------------------------------------------------
// Reflection Builtins
// -------------------------------------------------------------------------

/// Try to reduce reflection builtins (syn_size, syn_max_var, syn_lift, syn_subst, syn_beta, syn_step).
///
/// Pattern: (syn_size arg) or (syn_max_var arg) or (syn_step arg) where arg is a Syntax constructor.
/// Pattern: ((syn_beta body) arg) for two-argument builtins.
/// Pattern: (((syn_lift amount) cutoff) term) for three-argument builtins.
/// Pattern: (((syn_subst replacement) index) term) for substitution.
fn try_reflection_reduce(ctx: &Context, func: &Term, arg: &Term) -> Option<Term> {
    // First, check for single-argument builtins
    if let Term::Global(op_name) = func {
        match op_name.as_str() {
            "syn_size" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_syn_size_reduce(ctx, &norm_arg);
            }
            "syn_max_var" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_syn_max_var_reduce(ctx, &norm_arg, 0);
            }
            "syn_step" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_syn_step_reduce(ctx, &norm_arg);
            }
            "syn_quote" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_syn_quote_reduce(ctx, &norm_arg);
            }
            "syn_diag" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_syn_diag_reduce(ctx, &norm_arg);
            }
            "concludes" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_concludes_reduce(ctx, &norm_arg);
            }
            "try_refl" => {
                // Normalize the argument first
                let norm_arg = normalize(ctx, arg);
                return try_try_refl_reduce(ctx, &norm_arg);
            }
            "tact_fail" => {
                // tact_fail always returns error derivation
                return Some(make_error_derivation());
            }
            "try_compute" => {
                // try_compute goal = DCompute goal
                // The validation happens in concludes
                let norm_arg = normalize(ctx, arg);
                return Some(Term::App(
                    Box::new(Term::Global("DCompute".to_string())),
                    Box::new(norm_arg),
                ));
            }
            "try_ring" => {
                // Ring tactic: prove polynomial equalities by normalization
                let norm_arg = normalize(ctx, arg);
                return try_try_ring_reduce(ctx, &norm_arg);
            }
            "try_lia" => {
                // LIA tactic: prove linear inequalities by Fourier-Motzkin
                let norm_arg = normalize(ctx, arg);
                return try_try_lia_reduce(ctx, &norm_arg);
            }
            "try_cc" => {
                // CC tactic: prove equalities by congruence closure
                let norm_arg = normalize(ctx, arg);
                return try_try_cc_reduce(ctx, &norm_arg);
            }
            "try_simp" => {
                // Simp tactic: prove equalities by simplification and arithmetic
                let norm_arg = normalize(ctx, arg);
                return try_try_simp_reduce(ctx, &norm_arg);
            }
            "try_omega" => {
                // Omega tactic: prove integer inequalities with proper rounding
                let norm_arg = normalize(ctx, arg);
                return try_try_omega_reduce(ctx, &norm_arg);
            }
            "try_auto" => {
                // Auto tactic: tries all tactics in sequence
                let norm_arg = normalize(ctx, arg);
                return try_try_auto_reduce(ctx, &norm_arg);
            }
            "try_bitblast" => {
                // Bitblast tactic: prove Bit equalities by normalization
                let norm_arg = normalize(ctx, arg);
                return try_try_bitblast_reduce(ctx, &norm_arg);
            }
            "try_tabulate" => {
                // Tabulate tactic: prove universal Bit goals by exhaustion
                let norm_arg = normalize(ctx, arg);
                return try_try_tabulate_reduce(ctx, &norm_arg);
            }
            "try_hw_auto" => {
                // Hardware auto: tries bitblast, then tabulate, then auto
                let norm_arg = normalize(ctx, arg);
                return try_try_hw_auto_reduce(ctx, &norm_arg);
            }
            "try_inversion" => {
                // Inversion tactic: derives False if no constructor can match
                let norm_arg = normalize(ctx, arg);
                return try_try_inversion_reduce(ctx, &norm_arg);
            }
            "induction_num_cases" => {
                // Returns number of constructors for an inductive type
                let norm_arg = normalize(ctx, arg);
                return try_induction_num_cases_reduce(ctx, &norm_arg);
            }
            _ => {}
        }
    }

    // For multi-argument builtins like syn_lift and syn_subst,
    // we need to check if func is a partial application

    // syn_lift amount cutoff term
    // Structure: (((syn_lift amount) cutoff) term) = App(App(App(syn_lift, amount), cutoff), term)
    // When reduced: func = App(App(syn_lift, amount), cutoff), arg = term
    if let Term::App(partial2, cutoff) = func {
        if let Term::App(partial1, amount) = partial2.as_ref() {
            if let Term::Global(op_name) = partial1.as_ref() {
                if op_name == "syn_lift" {
                    if let (Term::Lit(Literal::Int(amt)), Term::Lit(Literal::Int(cut))) =
                        (amount.as_ref(), cutoff.as_ref())
                    {
                        let norm_term = normalize(ctx, arg);
                        return try_syn_lift_reduce(ctx, *amt, *cut, &norm_term);
                    }
                }
            }
        }
    }

    // syn_subst replacement index term
    // Structure: (((syn_subst replacement) index) term)
    if let Term::App(partial2, index) = func {
        if let Term::App(partial1, replacement) = partial2.as_ref() {
            if let Term::Global(op_name) = partial1.as_ref() {
                if op_name == "syn_subst" {
                    if let Term::Lit(Literal::Int(idx)) = index.as_ref() {
                        let norm_replacement = normalize(ctx, replacement);
                        let norm_term = normalize(ctx, arg);
                        return try_syn_subst_reduce(ctx, &norm_replacement, *idx, &norm_term);
                    }
                }
            }
        }
    }

    // syn_beta body arg (2 arguments)
    // Structure: ((syn_beta body) arg)
    if let Term::App(partial1, body) = func {
        if let Term::Global(op_name) = partial1.as_ref() {
            if op_name == "syn_beta" {
                let norm_body = normalize(ctx, body);
                let norm_arg = normalize(ctx, arg);
                return try_syn_beta_reduce(ctx, &norm_body, &norm_arg);
            }
        }
    }

    // try_cong context eq_proof (2 arguments)
    // Structure: ((try_cong context) eq_proof)
    // Returns: DCong context eq_proof
    if let Term::App(partial1, context) = func {
        if let Term::Global(op_name) = partial1.as_ref() {
            if op_name == "try_cong" {
                let norm_context = normalize(ctx, context);
                let norm_proof = normalize(ctx, arg);
                return Some(Term::App(
                    Box::new(Term::App(
                        Box::new(Term::Global("DCong".to_string())),
                        Box::new(norm_context),
                    )),
                    Box::new(norm_proof),
                ));
            }
        }
    }

    // try_rewrite eq_proof goal (2 arguments)
    // Structure: ((try_rewrite eq_proof) goal)
    // Given eq_proof : Eq A x y, rewrites goal by replacing x with y
    if let Term::App(partial1, eq_proof) = func {
        if let Term::Global(op_name) = partial1.as_ref() {
            if op_name == "try_rewrite" {
                let norm_eq_proof = normalize(ctx, eq_proof);
                let norm_goal = normalize(ctx, arg);
                return try_try_rewrite_reduce(ctx, &norm_eq_proof, &norm_goal, false);
            }
            if op_name == "try_rewrite_rev" {
                let norm_eq_proof = normalize(ctx, eq_proof);
                let norm_goal = normalize(ctx, arg);
                return try_try_rewrite_reduce(ctx, &norm_eq_proof, &norm_goal, true);
            }
        }
    }

    // syn_eval fuel term (2 arguments)
    // Structure: ((syn_eval fuel) term)
    if let Term::App(partial1, fuel_term) = func {
        if let Term::Global(op_name) = partial1.as_ref() {
            if op_name == "syn_eval" {
                if let Term::Lit(Literal::Int(fuel)) = fuel_term.as_ref() {
                    let norm_term = normalize(ctx, arg);
                    return try_syn_eval_reduce(ctx, *fuel, &norm_term);
                }
            }
        }
    }

    // induction_base_goal ind_type motive (2 arguments)
    // Structure: ((induction_base_goal ind_type) motive)
    if let Term::App(partial1, ind_type) = func {
        if let Term::Global(op_name) = partial1.as_ref() {
            if op_name == "induction_base_goal" {
                let norm_ind_type = normalize(ctx, ind_type);
                let norm_motive = normalize(ctx, arg);
                return try_induction_base_goal_reduce(ctx, &norm_ind_type, &norm_motive);
            }
        }
    }

    // tact_orelse t1 t2 goal (3 arguments)
    // Structure: (((tact_orelse t1) t2) goal)
    // Here: func = App(App(tact_orelse, t1), t2), arg = goal
    if let Term::App(partial1, t2) = func {
        if let Term::App(combinator, t1) = partial1.as_ref() {
            if let Term::Global(name) = combinator.as_ref() {
                if name == "tact_orelse" {
                    return try_tact_orelse_reduce(ctx, t1, t2, arg);
                }
                // tact_then t1 t2 goal (3 arguments)
                if name == "tact_then" {
                    return try_tact_then_reduce(ctx, t1, t2, arg);
                }
            }
        }
    }

    // tact_try t goal (2 arguments)
    // Structure: ((tact_try t) goal)
    if let Term::App(combinator, t) = func {
        if let Term::Global(name) = combinator.as_ref() {
            if name == "tact_try" {
                return try_tact_try_reduce(ctx, t, arg);
            }
            // tact_repeat t goal (2 arguments)
            if name == "tact_repeat" {
                return try_tact_repeat_reduce(ctx, t, arg);
            }
            // tact_solve t goal (2 arguments)
            if name == "tact_solve" {
                return try_tact_solve_reduce(ctx, t, arg);
            }
            // tact_first tactics goal (2 arguments)
            if name == "tact_first" {
                return try_tact_first_reduce(ctx, t, arg);
            }
        }
    }

    // induction_step_goal ind_type motive ctor_idx (3 arguments)
    // Structure: (((induction_step_goal ind_type) motive) ctor_idx)
    // Returns the goal for the given constructor index
    if let Term::App(partial1, motive) = func {
        if let Term::App(combinator, ind_type) = partial1.as_ref() {
            if let Term::Global(name) = combinator.as_ref() {
                if name == "induction_step_goal" {
                    let norm_ind_type = normalize(ctx, ind_type);
                    let norm_motive = normalize(ctx, motive);
                    let norm_idx = normalize(ctx, arg);
                    return try_induction_step_goal_reduce(ctx, &norm_ind_type, &norm_motive, &norm_idx);
                }
            }
        }
    }

    // try_induction ind_type motive cases (3 arguments)
    // Structure: (((try_induction ind_type) motive) cases)
    // Returns DElim ind_type motive cases (delegating to existing infrastructure)
    if let Term::App(partial1, motive) = func {
        if let Term::App(combinator, ind_type) = partial1.as_ref() {
            if let Term::Global(name) = combinator.as_ref() {
                if name == "try_induction" {
                    let norm_ind_type = normalize(ctx, ind_type);
                    let norm_motive = normalize(ctx, motive);
                    let norm_cases = normalize(ctx, arg);
                    return try_try_induction_reduce(ctx, &norm_ind_type, &norm_motive, &norm_cases);
                }
            }
        }
    }

    // try_destruct ind_type motive cases (3 arguments)
    // Structure: (((try_destruct ind_type) motive) cases)
    // Case analysis without induction hypotheses
    if let Term::App(partial1, motive) = func {
        if let Term::App(combinator, ind_type) = partial1.as_ref() {
            if let Term::Global(name) = combinator.as_ref() {
                if name == "try_destruct" {
                    let norm_ind_type = normalize(ctx, ind_type);
                    let norm_motive = normalize(ctx, motive);
                    let norm_cases = normalize(ctx, arg);
                    return try_try_destruct_reduce(ctx, &norm_ind_type, &norm_motive, &norm_cases);
                }
            }
        }
    }

    // try_apply hyp_name hyp_proof goal (3 arguments)
    // Structure: (((try_apply hyp_name) hyp_proof) goal)
    // Manual backward chaining
    if let Term::App(partial1, hyp_proof) = func {
        if let Term::App(combinator, hyp_name) = partial1.as_ref() {
            if let Term::Global(name) = combinator.as_ref() {
                if name == "try_apply" {
                    let norm_hyp_name = normalize(ctx, hyp_name);
                    let norm_hyp_proof = normalize(ctx, hyp_proof);
                    let norm_goal = normalize(ctx, arg);
                    return try_try_apply_reduce(ctx, &norm_hyp_name, &norm_hyp_proof, &norm_goal);
                }
            }
        }
    }

    None
}

/// Compute size of a Syntax term.
///
/// SVar n -> 1
/// SGlobal n -> 1
/// SSort u -> 1
/// SApp f x -> 1 + size(f) + size(x)
/// SLam A b -> 1 + size(A) + size(b)
/// SPi A B -> 1 + size(A) + size(B)
fn try_syn_size_reduce(ctx: &Context, term: &Term) -> Option<Term> {
    // Match on the constructor form
    // Unary constructors: (SVar n), (SGlobal n), (SSort u)
    // Binary constructors: ((SApp f) x), ((SLam A) b), ((SPi A) B)

    // Check for unary constructor: (Ctor arg)
    if let Term::App(ctor_term, _inner_arg) = term {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            match ctor_name.as_str() {
                "SVar" | "SGlobal" | "SSort" | "SLit" | "SName" => {
                    return Some(Term::Lit(Literal::Int(1)));
                }
                _ => {}
            }
        }

        // Check for binary constructor: ((Ctor a) b)
        if let Term::App(inner, a) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                match ctor_name.as_str() {
                    "SApp" | "SLam" | "SPi" => {
                        // Get sizes of both children
                        let a_size = try_syn_size_reduce(ctx, a)?;
                        let b_size = try_syn_size_reduce(ctx, _inner_arg)?;

                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
                            (a_size, b_size)
                        {
                            return Some(Term::Lit(Literal::Int(1 + a_n + b_n)));
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    None
}

/// Compute maximum free variable index in a Syntax term.
///
/// The `depth` parameter tracks how many binders we're under.
/// SVar k -> k - depth (returns -1 if bound, k - depth if free)
/// SGlobal _ -> -1 (no free variables)
/// SSort _ -> -1 (no free variables)
/// SApp f x -> max(max_var(f), max_var(x))
/// SLam A b -> max(max_var(A), max_var(b, depth+1))
/// SPi A B -> max(max_var(A), max_var(B, depth+1))
fn try_syn_max_var_reduce(ctx: &Context, term: &Term, depth: i64) -> Option<Term> {
    // Check for unary constructor: (Ctor arg)
    if let Term::App(ctor_term, inner_arg) = term {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            match ctor_name.as_str() {
                "SVar" => {
                    // SVar k -> if k >= depth then k - depth else -1
                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
                        if *k >= depth {
                            // Free variable with adjusted index
                            return Some(Term::Lit(Literal::Int(*k - depth)));
                        } else {
                            // Bound variable
                            return Some(Term::Lit(Literal::Int(-1)));
                        }
                    }
                }
                "SGlobal" | "SSort" | "SLit" | "SName" => {
                    // No free variables
                    return Some(Term::Lit(Literal::Int(-1)));
                }
                _ => {}
            }
        }

        // Check for binary constructor: ((Ctor a) b)
        if let Term::App(inner, a) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                match ctor_name.as_str() {
                    "SApp" => {
                        // SApp f x -> max(max_var(f), max_var(x))
                        let a_max = try_syn_max_var_reduce(ctx, a, depth)?;
                        let b_max = try_syn_max_var_reduce(ctx, inner_arg, depth)?;

                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
                            (a_max, b_max)
                        {
                            return Some(Term::Lit(Literal::Int(a_n.max(b_n))));
                        }
                    }
                    "SLam" | "SPi" => {
                        // SLam A b -> max(max_var(A, depth), max_var(b, depth+1))
                        // The body 'b' is under one additional binder
                        let a_max = try_syn_max_var_reduce(ctx, a, depth)?;
                        let b_max = try_syn_max_var_reduce(ctx, inner_arg, depth + 1)?;

                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
                            (a_max, b_max)
                        {
                            return Some(Term::Lit(Literal::Int(a_n.max(b_n))));
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    None
}

// -------------------------------------------------------------------------
// Substitution Builtins
// -------------------------------------------------------------------------

/// Lift De Bruijn indices in a Syntax term.
///
/// syn_lift amount cutoff term:
/// - Variables with index < cutoff are bound -> unchanged
/// - Variables with index >= cutoff are free -> add amount
fn try_syn_lift_reduce(ctx: &Context, amount: i64, cutoff: i64, term: &Term) -> Option<Term> {
    // Check for unary constructor: (Ctor arg)
    if let Term::App(ctor_term, inner_arg) = term {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            match ctor_name.as_str() {
                "SVar" => {
                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
                        if *k >= cutoff {
                            // Free variable, shift
                            return Some(Term::App(
                                Box::new(Term::Global("SVar".to_string())),
                                Box::new(Term::Lit(Literal::Int(*k + amount))),
                            ));
                        } else {
                            // Bound variable, no shift
                            return Some(term.clone());
                        }
                    }
                }
                "SGlobal" | "SSort" | "SLit" | "SName" => {
                    // No free variables
                    return Some(term.clone());
                }
                _ => {}
            }
        }

        // Check for binary constructor: ((Ctor a) b)
        if let Term::App(inner, a) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                match ctor_name.as_str() {
                    "SApp" => {
                        // No binding, same cutoff for both
                        let a_lifted = try_syn_lift_reduce(ctx, amount, cutoff, a)?;
                        let b_lifted = try_syn_lift_reduce(ctx, amount, cutoff, inner_arg)?;
                        return Some(Term::App(
                            Box::new(Term::App(
                                Box::new(Term::Global("SApp".to_string())),
                                Box::new(a_lifted),
                            )),
                            Box::new(b_lifted),
                        ));
                    }
                    "SLam" | "SPi" => {
                        // Binder: param type at current cutoff, body at cutoff+1
                        let param_lifted = try_syn_lift_reduce(ctx, amount, cutoff, a)?;
                        let body_lifted =
                            try_syn_lift_reduce(ctx, amount, cutoff + 1, inner_arg)?;
                        return Some(Term::App(
                            Box::new(Term::App(
                                Box::new(Term::Global(ctor_name.clone())),
                                Box::new(param_lifted),
                            )),
                            Box::new(body_lifted),
                        ));
                    }
                    _ => {}
                }
            }
        }
    }

    None
}

/// Substitute a term for a variable in a Syntax term.
///
/// syn_subst replacement index term:
/// - If term is SVar k and k == index, return replacement
/// - If term is SVar k and k != index, return term unchanged
/// - For binders, increment index and lift replacement
fn try_syn_subst_reduce(
    ctx: &Context,
    replacement: &Term,
    index: i64,
    term: &Term,
) -> Option<Term> {
    // Check for unary constructor: (Ctor arg)
    if let Term::App(ctor_term, inner_arg) = term {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            match ctor_name.as_str() {
                "SVar" => {
                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
                        if *k == index {
                            // Match! Return replacement
                            return Some(replacement.clone());
                        } else {
                            // No match, return unchanged
                            return Some(term.clone());
                        }
                    }
                }
                "SGlobal" | "SSort" | "SLit" | "SName" => {
                    // No variables to substitute
                    return Some(term.clone());
                }
                _ => {}
            }
        }

        // Check for binary constructor: ((Ctor a) b)
        if let Term::App(inner, a) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                match ctor_name.as_str() {
                    "SApp" => {
                        // No binding, same index and replacement
                        let a_subst = try_syn_subst_reduce(ctx, replacement, index, a)?;
                        let b_subst = try_syn_subst_reduce(ctx, replacement, index, inner_arg)?;
                        return Some(Term::App(
                            Box::new(Term::App(
                                Box::new(Term::Global("SApp".to_string())),
                                Box::new(a_subst),
                            )),
                            Box::new(b_subst),
                        ));
                    }
                    "SLam" | "SPi" => {
                        // Binder: param type at current index, body at index+1
                        // Lift replacement when going under binder
                        let param_subst = try_syn_subst_reduce(ctx, replacement, index, a)?;

                        // Lift the replacement by 1 when going under the binder
                        let lifted_replacement = try_syn_lift_reduce(ctx, 1, 0, replacement)?;
                        let body_subst = try_syn_subst_reduce(
                            ctx,
                            &lifted_replacement,
                            index + 1,
                            inner_arg,
                        )?;

                        return Some(Term::App(
                            Box::new(Term::App(
                                Box::new(Term::Global(ctor_name.clone())),
                                Box::new(param_subst),
                            )),
                            Box::new(body_subst),
                        ));
                    }
                    _ => {}
                }
            }
        }
    }

    None
}

// -------------------------------------------------------------------------
// Computation Builtins
// -------------------------------------------------------------------------

/// Beta reduction: substitute arg for variable 0 in body.
///
/// syn_beta body arg = syn_subst arg 0 body
fn try_syn_beta_reduce(ctx: &Context, body: &Term, arg: &Term) -> Option<Term> {
    // syn_beta is just syn_subst with index 0
    try_syn_subst_reduce(ctx, arg, 0, body)
}

/// Try to reduce arithmetic on Syntax literals.
///
/// Handles: SApp (SApp (SName op) (SLit n)) (SLit m) → SLit result
/// where op is one of: add, sub, mul, div, mod
fn try_syn_arith_reduce(func: &Term, arg: &Term) -> Option<Term> {
    // func should be: SApp (SName op) (SLit n)
    // Pattern: App(App(Global("SApp"), App(Global("SName"), Lit(Text(op)))), App(Global("SLit"), Lit(Int(n))))
    if let Term::App(inner_ctor, n_term) = func {
        if let Term::App(sapp_ctor, op_term) = inner_ctor.as_ref() {
            // Check for SApp constructor
            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
                if ctor_name != "SApp" {
                    return None;
                }
            } else {
                return None;
            }

            // Extract op from SName op
            let op = if let Term::App(sname_ctor, op_str) = op_term.as_ref() {
                if let Term::Global(name) = sname_ctor.as_ref() {
                    if name == "SName" {
                        if let Term::Lit(Literal::Text(op)) = op_str.as_ref() {
                            op.clone()
                        } else {
                            return None;
                        }
                    } else {
                        return None;
                    }
                } else {
                    return None;
                }
            } else {
                return None;
            };

            // Extract n from SLit n
            let n = if let Term::App(slit_ctor, n_val) = n_term.as_ref() {
                if let Term::Global(name) = slit_ctor.as_ref() {
                    if name == "SLit" {
                        if let Term::Lit(Literal::Int(n)) = n_val.as_ref() {
                            *n
                        } else {
                            return None;
                        }
                    } else {
                        return None;
                    }
                } else {
                    return None;
                }
            } else {
                return None;
            };

            // Extract m from SLit m (the arg)
            let m = if let Term::App(slit_ctor, m_val) = arg {
                if let Term::Global(name) = slit_ctor.as_ref() {
                    if name == "SLit" {
                        if let Term::Lit(Literal::Int(m)) = m_val.as_ref() {
                            *m
                        } else {
                            return None;
                        }
                    } else {
                        return None;
                    }
                } else {
                    return None;
                }
            } else {
                return None;
            };

            // Compute result based on operator
            let result = match op.as_str() {
                "add" => n.checked_add(m),
                "sub" => n.checked_sub(m),
                "mul" => n.checked_mul(m),
                "div" => {
                    if m == 0 {
                        return None; // Division by zero: remain stuck
                    }
                    n.checked_div(m)
                }
                "mod" => {
                    if m == 0 {
                        return None; // Mod by zero: remain stuck
                    }
                    n.checked_rem(m)
                }
                _ => None,
            };

            // Build SLit result
            if let Some(r) = result {
                return Some(Term::App(
                    Box::new(Term::Global("SLit".to_string())),
                    Box::new(Term::Lit(Literal::Int(r))),
                ));
            }
        }
    }

    None
}

/// Single-step head reduction.
///
/// Looks for the leftmost-outermost beta redex and reduces it.
/// - If SApp (SLam T body) arg: perform beta reduction
/// - If SApp f x where f is reducible: reduce f
/// - Otherwise: return unchanged (stuck or value)
fn try_syn_step_reduce(ctx: &Context, term: &Term) -> Option<Term> {
    // Check for SApp (binary constructor)
    if let Term::App(ctor_term, arg) = term {
        if let Term::App(inner, func) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                if ctor_name == "SApp" {
                    // We have SApp func arg
                    // First, check for arithmetic primitives: SApp (SApp (SName op) (SLit n)) (SLit m)
                    if let Some(result) = try_syn_arith_reduce(func.as_ref(), arg.as_ref()) {
                        return Some(result);
                    }

                    // Check if func is SLam (beta redex)
                    if let Term::App(lam_inner, body) = func.as_ref() {
                        if let Term::App(lam_ctor, _param_type) = lam_inner.as_ref() {
                            if let Term::Global(lam_name) = lam_ctor.as_ref() {
                                if lam_name == "SLam" {
                                    // Beta redex! (SApp (SLam T body) arg) → syn_beta body arg
                                    return try_syn_beta_reduce(ctx, body.as_ref(), arg.as_ref());
                                }
                            }
                        }
                    }

                    // Delta reduction via kernel normalization:
                    // When the entire SApp tree represents a reducible expression
                    // (e.g., SApp(SApp(SName("bit_and"), SName("B1")), SName("B0"))),
                    // reify to kernel Term, normalize, and convert back to Syntax.
                    // This leverages the kernel's full reduction machinery (delta + iota + beta)
                    // without needing Match support in the Syntax representation.
                    {
                        let full_app = term; // The entire SApp(func, arg) Syntax term
                        if let Some(kernel_term) = syntax_to_term(full_app) {
                            let normalized = normalize(ctx, &kernel_term);
                            if normalized != kernel_term {
                                if let Some(result_syntax) = term_to_syntax(&normalized) {
                                    return Some(result_syntax);
                                }
                            }
                        }
                    }

                    // Not a beta redex or reducible application. Try to step the function.
                    if let Some(stepped_func) = try_syn_step_reduce(ctx, func.as_ref()) {
                        // Check if func actually changed
                        if &stepped_func != func.as_ref() {
                            // func reduced, reconstruct SApp stepped_func arg
                            return Some(Term::App(
                                Box::new(Term::App(
                                    Box::new(Term::Global("SApp".to_string())),
                                    Box::new(stepped_func),
                                )),
                                Box::new(arg.as_ref().clone()),
                            ));
                        }
                    }

                    // func is stuck. Try to step the argument.
                    if let Some(stepped_arg) = try_syn_step_reduce(ctx, arg.as_ref()) {
                        if &stepped_arg != arg.as_ref() {
                            // arg reduced, reconstruct SApp func stepped_arg
                            return Some(Term::App(
                                Box::new(Term::App(
                                    Box::new(Term::Global("SApp".to_string())),
                                    Box::new(func.as_ref().clone()),
                                )),
                                Box::new(stepped_arg),
                            ));
                        }
                    }

                    // Both func and arg are stuck, return original term
                    return Some(term.clone());
                }
            }
        }
    }

    // Not an application - it's a value or stuck term
    // Return unchanged
    Some(term.clone())
}

// -------------------------------------------------------------------------
// Bounded Evaluation
// -------------------------------------------------------------------------

/// Bounded evaluation: reduce for up to N steps.
///
/// syn_eval fuel term:
/// - If fuel <= 0: return term unchanged
/// - Otherwise: step and repeat until normal form or fuel exhausted
fn try_syn_eval_reduce(ctx: &Context, fuel: i64, term: &Term) -> Option<Term> {
    if fuel <= 0 {
        return Some(term.clone());
    }

    // Try one step
    let stepped = try_syn_step_reduce(ctx, term)?;

    // If term didn't change, it's in normal form (or stuck)
    if &stepped == term {
        return Some(term.clone());
    }

    // Continue with reduced fuel
    try_syn_eval_reduce(ctx, fuel - 1, &stepped)
}

// -------------------------------------------------------------------------
// Reification (Quote)
// -------------------------------------------------------------------------

/// Quote a Syntax value: produce Syntax that constructs it.
///
/// syn_quote term:
/// - SVar n → SApp (SName "SVar") (SLit n)
/// - SGlobal n → SApp (SName "SGlobal") (SLit n)
/// - SSort u → SApp (SName "SSort") (quote_univ u)
/// - SApp f x → SApp (SApp (SName "SApp") (quote f)) (quote x)
/// - SLam T b → SApp (SApp (SName "SLam") (quote T)) (quote b)
/// - SPi T B → SApp (SApp (SName "SPi") (quote T)) (quote B)
/// - SLit n → SApp (SName "SLit") (SLit n)
/// - SName s → SName s (self-quoting)
#[allow(dead_code)]
fn try_syn_quote_reduce(ctx: &Context, term: &Term) -> Option<Term> {
    // Helper to build SApp (SName name) arg
    fn sname_app(name: &str, arg: Term) -> Term {
        Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SApp".to_string())),
                Box::new(Term::App(
                    Box::new(Term::Global("SName".to_string())),
                    Box::new(Term::Lit(Literal::Text(name.to_string()))),
                )),
            )),
            Box::new(arg),
        )
    }

    // Helper to build SLit n
    fn slit(n: i64) -> Term {
        Term::App(
            Box::new(Term::Global("SLit".to_string())),
            Box::new(Term::Lit(Literal::Int(n))),
        )
    }

    // Helper to build SName s
    fn sname(s: &str) -> Term {
        Term::App(
            Box::new(Term::Global("SName".to_string())),
            Box::new(Term::Lit(Literal::Text(s.to_string()))),
        )
    }

    // Helper to build SApp (SApp (SName name) a) b
    fn sname_app2(name: &str, a: Term, b: Term) -> Term {
        Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SApp".to_string())),
                Box::new(sname_app(name, a)),
            )),
            Box::new(b),
        )
    }

    // Match on Syntax constructors
    if let Term::App(ctor_term, inner_arg) = term {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            match ctor_name.as_str() {
                "SVar" => {
                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
                        return Some(sname_app("SVar", slit(*n)));
                    }
                }
                "SGlobal" => {
                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
                        return Some(sname_app("SGlobal", slit(*n)));
                    }
                }
                "SSort" => {
                    // Quote the universe
                    let quoted_univ = quote_univ(inner_arg)?;
                    return Some(sname_app("SSort", quoted_univ));
                }
                "SLit" => {
                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
                        return Some(sname_app("SLit", slit(*n)));
                    }
                }
                "SName" => {
                    // SName is self-quoting
                    return Some(term.clone());
                }
                _ => {}
            }
        }

        // Binary constructors: ((Ctor a) b)
        if let Term::App(inner, a) = ctor_term.as_ref() {
            if let Term::Global(ctor_name) = inner.as_ref() {
                match ctor_name.as_str() {
                    "SApp" | "SLam" | "SPi" => {
                        let quoted_a = try_syn_quote_reduce(ctx, a)?;
                        let quoted_b = try_syn_quote_reduce(ctx, inner_arg)?;
                        return Some(sname_app2(ctor_name, quoted_a, quoted_b));
                    }
                    _ => {}
                }
            }
        }
    }

    None
}

/// Quote a Univ value.
///
/// UProp → SName "UProp"
/// UType n → SApp (SName "UType") (SLit n)
fn quote_univ(term: &Term) -> Option<Term> {
    fn sname(s: &str) -> Term {
        Term::App(
            Box::new(Term::Global("SName".to_string())),
            Box::new(Term::Lit(Literal::Text(s.to_string()))),
        )
    }

    fn slit(n: i64) -> Term {
        Term::App(
            Box::new(Term::Global("SLit".to_string())),
            Box::new(Term::Lit(Literal::Int(n))),
        )
    }

    fn sname_app(name: &str, arg: Term) -> Term {
        Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SApp".to_string())),
                Box::new(sname(name)),
            )),
            Box::new(arg),
        )
    }

    if let Term::Global(name) = term {
        if name == "UProp" {
            return Some(sname("UProp"));
        }
    }

    if let Term::App(ctor, arg) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "UType" {
                if let Term::Lit(Literal::Int(n)) = arg.as_ref() {
                    return Some(sname_app("UType", slit(*n)));
                }
            }
        }
    }

    None
}

// -------------------------------------------------------------------------
// Diagonalization (Self-Reference)
// -------------------------------------------------------------------------

/// The diagonal function: syn_diag x = syn_subst (syn_quote x) 0 x
///
/// This takes a term x with free variable 0, quotes x to get its construction
/// code, then substitutes that code for variable 0 in x.
fn try_syn_diag_reduce(ctx: &Context, term: &Term) -> Option<Term> {
    // Step 1: Quote the term
    let quoted = try_syn_quote_reduce(ctx, term)?;

    // Step 2: Substitute the quoted form for variable 0 in the original term
    try_syn_subst_reduce(ctx, &quoted, 0, term)
}

// -------------------------------------------------------------------------
// Inference Rules
// -------------------------------------------------------------------------

/// Extract the conclusion from a derivation.
///
/// concludes d:
/// - DAxiom P → P
/// - DModusPonens d_impl d_ant → extract B from (Implies A B) if A matches antecedent
/// - DUnivIntro d → wrap conclusion in Forall
/// - DUnivElim d term → substitute term into forall body
/// - DRefl T a → Eq T a a
fn try_concludes_reduce(ctx: &Context, deriv: &Term) -> Option<Term> {
    // DAxiom P → P
    if let Term::App(ctor_term, p) = deriv {
        if let Term::Global(ctor_name) = ctor_term.as_ref() {
            if ctor_name == "DAxiom" {
                return Some(p.as_ref().clone());
            }
            if ctor_name == "DUnivIntro" {
                // Get conclusion of inner derivation
                let inner_conc = try_concludes_reduce(ctx, p)?;
                // Lift it by 1 and wrap in Forall
                let lifted = try_syn_lift_reduce(ctx, 1, 0, &inner_conc)?;
                return Some(make_forall_syntax(&lifted));
            }
            if ctor_name == "DCompute" {
                // DCompute goal: verify goal is Eq T A B and eval(A) == eval(B)
                return try_dcompute_conclude(ctx, p);
            }
            if ctor_name == "DRingSolve" {
                // DRingSolve goal: verify goal is Eq T A B and polynomials are equal
                return try_dring_solve_conclude(ctx, p);
            }
            if ctor_name == "DLiaSolve" {
                // DLiaSolve goal: verify goal is an inequality and LIA proves it
                return try_dlia_solve_conclude(ctx, p);
            }
            if ctor_name == "DccSolve" {
                // DccSolve goal: verify goal by congruence closure
                return try_dcc_solve_conclude(ctx, p);
            }
            if ctor_name == "DSimpSolve" {
                // DSimpSolve goal: verify goal by simplification
                return try_dsimp_solve_conclude(ctx, p);
            }
            if ctor_name == "DOmegaSolve" {
                // DOmegaSolve goal: verify goal by integer arithmetic
                return try_domega_solve_conclude(ctx, p);
            }
            if ctor_name == "DAutoSolve" {
                // DAutoSolve goal: verify goal by trying all tactics
                return try_dauto_solve_conclude(ctx, p);
            }
            if ctor_name == "DBitblastSolve" {
                // DBitblastSolve goal: verify Eq Bit by normalization
                return try_dbitblast_solve_conclude(ctx, p);
            }
            if ctor_name == "DTabulateSolve" {
                // DTabulateSolve goal: verify universal Bit by exhaustion
                return try_dtabulate_solve_conclude(ctx, p);
            }
            if ctor_name == "DHwAutoSolve" {
                // DHwAutoSolve goal: verify by hw tactic chain
                return try_dhw_auto_solve_conclude(ctx, p);
            }
            if ctor_name == "DInversion" {
                // DInversion hyp_type: verify no constructor can match, return False
                return try_dinversion_conclude(ctx, p);
            }
        }
    }

    // DRewrite eq_proof old_goal new_goal → new_goal (if verified)
    // Pattern: App(App(App(DRewrite, eq_proof), old_goal), new_goal)
    if let Term::App(partial1, new_goal) = deriv {
        if let Term::App(partial2, old_goal) = partial1.as_ref() {
            if let Term::App(ctor_term, eq_proof) = partial2.as_ref() {
                if let Term::Global(ctor_name) = ctor_term.as_ref() {
                    if ctor_name == "DRewrite" {
                        return try_drewrite_conclude(ctx, eq_proof, old_goal, new_goal);
                    }
                }
            }
        }
    }

    // DDestruct ind_type motive cases → Forall ind_type motive (if verified)
    // Pattern: App(App(App(DDestruct, ind_type), motive), cases)
    if let Term::App(partial1, cases) = deriv {
        if let Term::App(partial2, motive) = partial1.as_ref() {
            if let Term::App(ctor_term, ind_type) = partial2.as_ref() {
                if let Term::Global(ctor_name) = ctor_term.as_ref() {
                    if ctor_name == "DDestruct" {
                        return try_ddestruct_conclude(ctx, ind_type, motive, cases);
                    }
                }
            }
        }
    }

    // DApply hyp_name hyp_proof old_goal new_goal → new_goal (if verified)
    // Pattern: App(App(App(App(DApply, hyp_name), hyp_proof), old_goal), new_goal)
    if let Term::App(partial1, new_goal) = deriv {
        if let Term::App(partial2, old_goal) = partial1.as_ref() {
            if let Term::App(partial3, hyp_proof) = partial2.as_ref() {
                if let Term::App(ctor_term, hyp_name) = partial3.as_ref() {
                    if let Term::Global(ctor_name) = ctor_term.as_ref() {
                        if ctor_name == "DApply" {
                            return try_dapply_conclude(ctx, hyp_name, hyp_proof, old_goal, new_goal);
                        }
                    }
                }
            }
        }
    }

    // DRefl T a → Eq T a a
    if let Term::App(partial, a) = deriv {
        if let Term::App(ctor_term, t) = partial.as_ref() {
            if let Term::Global(ctor_name) = ctor_term.as_ref() {
                if ctor_name == "DRefl" {
                    return Some(make_eq_syntax(t.as_ref(), a.as_ref()));
                }
                if ctor_name == "DCong" {
                    // DCong context eq_proof → Eq T (f a) (f b)
                    // where context = SLam T body, eq_proof proves Eq T a b
                    return try_dcong_conclude(ctx, t, a);
                }
            }
        }
    }

    // DModusPonens d_impl d_ant
    if let Term::App(partial, d_ant) = deriv {
        if let Term::App(ctor_term, d_impl) = partial.as_ref() {
            if let Term::Global(ctor_name) = ctor_term.as_ref() {
                if ctor_name == "DModusPonens" {
                    // Get conclusions of both derivations
                    let impl_conc = try_concludes_reduce(ctx, d_impl)?;
                    let ant_conc = try_concludes_reduce(ctx, d_ant)?;

                    // Check if impl_conc = SApp (SApp (SName "Implies") A) B
                    if let Some((a, b)) = extract_implication(&impl_conc) {
                        // Check if ant_conc equals A
                        if syntax_equal(&ant_conc, &a) {
                            return Some(b);
                        }
                    }
                    // Invalid modus ponens
                    return Some(make_sname_error());
                }
                if ctor_name == "DUnivElim" {
                    // d_impl is the derivation, d_ant is the term to substitute
                    let conc = try_concludes_reduce(ctx, d_impl)?;
                    if let Some(body) = extract_forall_body(&conc) {
                        // Substitute d_ant for var 0 in body
                        return try_syn_subst_reduce(ctx, d_ant, 0, &body);
                    }
                    // Invalid universal elimination
                    return Some(make_sname_error());
                }
            }
        }
    }

    // DInduction motive base step → Forall Nat motive (if verified)
    // Pattern: App(App(App(DInduction, motive), base), step)
    if let Term::App(partial1, step) = deriv {
        if let Term::App(partial2, base) = partial1.as_ref() {
            if let Term::App(ctor_term, motive) = partial2.as_ref() {
                if let Term::Global(ctor_name) = ctor_term.as_ref() {
                    if ctor_name == "DInduction" {
                        return try_dinduction_reduce(ctx, motive, base, step);
                    }
                }
            }
        }
    }

    // DElim ind_type motive cases → Forall ind_type motive (if verified)
    // Pattern: App(App(App(DElim, ind_type), motive), cases)
    if let Term::App(partial1, cases) = deriv {
        if let Term::App(partial2, motive) = partial1.as_ref() {
            if let Term::App(ctor_term, ind_type) = partial2.as_ref() {
                if let Term::Global(ctor_name) = ctor_term.as_ref() {
                    if ctor_name == "DElim" {
                        return try_delim_conclude(ctx, ind_type, motive, cases);
                    }
                }
            }
        }
    }

    None
}

/// Extract (A, B) from SApp (SApp (SName "Implies") A) B
///
/// In kernel representation:
/// SApp X Y = App(App(SApp, X), Y)
/// So SApp (SApp (SName "Implies") A) B =
///   App(App(SApp, App(App(SApp, App(SName, "Implies")), A)), B)
fn extract_implication(term: &Term) -> Option<(Term, Term)> {
    // term = App(App(SApp, X), B)
    if let Term::App(outer, b) = term {
        if let Term::App(sapp_outer, x) = outer.as_ref() {
            if let Term::Global(ctor) = sapp_outer.as_ref() {
                if ctor == "SApp" {
                    // x = App(App(SApp, App(SName, "Implies")), A)
                    if let Term::App(inner, a) = x.as_ref() {
                        if let Term::App(sapp_inner, sname_implies) = inner.as_ref() {
                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
                                if ctor2 == "SApp" {
                                    // sname_implies = App(SName, "Implies")
                                    if let Term::App(sname, text) = sname_implies.as_ref() {
                                        if let Term::Global(sname_ctor) = sname.as_ref() {
                                            if sname_ctor == "SName" {
                                                if let Term::Lit(Literal::Text(s)) = text.as_ref() {
                                                    if s == "Implies" || s == "implies" {
                                                        return Some((
                                                            a.as_ref().clone(),
                                                            b.as_ref().clone(),
                                                        ));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract all hypotheses from a chain of nested implications.
///
/// For `A -> B -> C`, returns `([A, B], C)`.
/// For non-implications, returns `([], term)`.
fn extract_implications(term: &Term) -> Option<(Vec<Term>, Term)> {
    let mut hyps = Vec::new();
    let mut current = term.clone();

    while let Some((hyp, rest)) = extract_implication(&current) {
        hyps.push(hyp);
        current = rest;
    }

    if hyps.is_empty() {
        None
    } else {
        Some((hyps, current))
    }
}

/// Extract body from SApp (SApp (SName "Forall") T) (SLam T body)
///
/// In kernel representation:
/// Extract body from Forall syntax (two forms supported):
/// Form 1: SApp (SName "Forall") (SLam T body)
/// Form 2: SApp (SApp (SName "Forall") T) (SLam T body)
fn extract_forall_body(term: &Term) -> Option<Term> {
    // term = App(App(SApp, X), lam)
    if let Term::App(outer, lam) = term {
        if let Term::App(sapp_outer, x) = outer.as_ref() {
            if let Term::Global(ctor) = sapp_outer.as_ref() {
                if ctor == "SApp" {
                    // Form 1: X = App(SName, "Forall")
                    if let Term::App(sname, text) = x.as_ref() {
                        if let Term::Global(sname_ctor) = sname.as_ref() {
                            if sname_ctor == "SName" {
                                if let Term::Lit(Literal::Text(s)) = text.as_ref() {
                                    if s == "Forall" {
                                        // Extract body from SLam
                                        return extract_slam_body(lam);
                                    }
                                }
                            }
                        }
                    }

                    // Form 2: X = App(App(SApp, App(SName, "Forall")), T)
                    if let Term::App(inner, _t) = x.as_ref() {
                        if let Term::App(sapp_inner, sname_forall) = inner.as_ref() {
                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
                                if ctor2 == "SApp" {
                                    if let Term::App(sname, text) = sname_forall.as_ref() {
                                        if let Term::Global(sname_ctor) = sname.as_ref() {
                                            if sname_ctor == "SName" {
                                                if let Term::Lit(Literal::Text(s)) = text.as_ref() {
                                                    if s == "Forall" {
                                                        return extract_slam_body(lam);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract body from ((SLam T) body)
fn extract_slam_body(term: &Term) -> Option<Term> {
    if let Term::App(inner, body) = term {
        if let Term::App(slam, _t) = inner.as_ref() {
            if let Term::Global(name) = slam.as_ref() {
                if name == "SLam" {
                    return Some(body.as_ref().clone());
                }
            }
        }
    }
    None
}

/// Structural equality check for Syntax terms
fn syntax_equal(a: &Term, b: &Term) -> bool {
    a == b
}

/// Build SName "Error"
fn make_sname_error() -> Term {
    Term::App(
        Box::new(Term::Global("SName".to_string())),
        Box::new(Term::Lit(Literal::Text("Error".to_string()))),
    )
}

/// Build SName from a string
fn make_sname(s: &str) -> Term {
    Term::App(
        Box::new(Term::Global("SName".to_string())),
        Box::new(Term::Lit(Literal::Text(s.to_string()))),
    )
}

/// Build SLit from an integer
fn make_slit(n: i64) -> Term {
    Term::App(
        Box::new(Term::Global("SLit".to_string())),
        Box::new(Term::Lit(Literal::Int(n))),
    )
}

/// Build SApp f x
fn make_sapp(f: Term, x: Term) -> Term {
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(f),
        )),
        Box::new(x),
    )
}

/// Build SPi A B
fn make_spi(a: Term, b: Term) -> Term {
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SPi".to_string())),
            Box::new(a),
        )),
        Box::new(b),
    )
}

/// Build SLam A b
fn make_slam(a: Term, b: Term) -> Term {
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SLam".to_string())),
            Box::new(a),
        )),
        Box::new(b),
    )
}

/// Build SSort u
fn make_ssort(u: Term) -> Term {
    Term::App(
        Box::new(Term::Global("SSort".to_string())),
        Box::new(u),
    )
}

/// Build SVar n
fn make_svar(n: i64) -> Term {
    Term::App(
        Box::new(Term::Global("SVar".to_string())),
        Box::new(Term::Lit(Literal::Int(n))),
    )
}

/// Convert a kernel Term to Syntax encoding (S* form).
///
/// This converts semantic Terms to their syntactic representation:
/// - Global(n) → SName n
/// - Var(n) → SName n (for named variables)
/// - App(f, x) → SApp (convert f) (convert x)
/// - Pi { param, param_type, body_type } → SPi (convert param_type) (convert body_type)
/// - Lambda { param, param_type, body } → SLam (convert param_type) (convert body)
/// - Sort(Type n) → SSort (UType n)
/// - Sort(Prop) → SSort UProp
/// - Lit(Int n) → SLit n
/// - Lit(Text s) → SName s
fn term_to_syntax(term: &Term) -> Option<Term> {
    match term {
        Term::Global(name) => Some(make_sname(name)),

        Term::Var(name) => {
            // Named variables become SName in syntax representation
            Some(make_sname(name))
        }

        Term::App(f, x) => {
            let sf = term_to_syntax(f)?;
            let sx = term_to_syntax(x)?;
            Some(make_sapp(sf, sx))
        }

        Term::Pi { param_type, body_type, .. } => {
            let sp = term_to_syntax(param_type)?;
            let sb = term_to_syntax(body_type)?;
            Some(make_spi(sp, sb))
        }

        Term::Lambda { param_type, body, .. } => {
            let sp = term_to_syntax(param_type)?;
            let sb = term_to_syntax(body)?;
            Some(make_slam(sp, sb))
        }

        Term::Sort(Universe::Type(n)) => {
            let u = Term::App(
                Box::new(Term::Global("UType".to_string())),
                Box::new(Term::Lit(Literal::Int(*n as i64))),
            );
            Some(make_ssort(u))
        }

        Term::Sort(Universe::Prop) => {
            let u = Term::Global("UProp".to_string());
            Some(make_ssort(u))
        }

        Term::Lit(Literal::Int(n)) => Some(make_slit(*n)),

        Term::Lit(Literal::Text(s)) => Some(make_sname(s)),

        // Float, Duration, Date, and Moment literals - skip for now as they're rarely used in proofs
        Term::Lit(Literal::Float(_))
        | Term::Lit(Literal::Duration(_))
        | Term::Lit(Literal::Date(_))
        | Term::Lit(Literal::Moment(_)) => None,

        // Match expressions, Fix, and Hole are complex - skip for now
        Term::Match { .. } | Term::Fix { .. } | Term::Hole => None,
    }
}

/// Build DHint derivation that references a hint by name.
///
/// Uses DAxiom (SName "hint_name") to indicate the proof uses this hint.
fn make_hint_derivation(hint_name: &str, goal: &Term) -> Term {
    // Build: DAxiom (SApp (SName "Hint") (SName hint_name))
    // This distinguishes hints from error derivations
    let hint_marker = make_sapp(make_sname("Hint"), make_sname(hint_name));

    // Actually, let's use a simpler approach: DAutoSolve goal
    // This indicates auto succeeded, and we can trace which hint was used through debugging
    Term::App(
        Box::new(Term::Global("DAutoSolve".to_string())),
        Box::new(goal.clone()),
    )
}

/// Try to apply a hint to prove a goal.
///
/// Returns Some(derivation) if the hint's type matches the goal,
/// otherwise returns None.
fn try_apply_hint(ctx: &Context, hint_name: &str, hint_type: &Term, goal: &Term) -> Option<Term> {
    // Convert hint type to syntax form
    let hint_syntax = term_to_syntax(hint_type)?;

    // Normalize both for comparison
    let norm_hint = normalize(ctx, &hint_syntax);
    let norm_goal = normalize(ctx, goal);

    // Direct match: hint type equals goal
    if syntax_equal(&norm_hint, &norm_goal) {
        return Some(make_hint_derivation(hint_name, goal));
    }

    // Try backward chaining for implications: if hint is P → Q and goal is Q,
    // try to prove P using auto and then apply the hint
    if let Term::App(outer, q) = &hint_syntax {
        if let Term::App(pi_ctor, p) = outer.as_ref() {
            if let Term::Global(name) = pi_ctor.as_ref() {
                if name == "SPi" {
                    // hint_type is SPi P Q, goal might be Q
                    let norm_q = normalize(ctx, q);
                    if syntax_equal(&norm_q, &norm_goal) {
                        // Need to prove P first, then apply hint
                        // This would require recursive auto call - skip for now
                        // to avoid infinite recursion
                    }
                }
            }
        }
    }

    None
}

/// Build Forall Type0 (SLam Type0 body)
fn make_forall_syntax(body: &Term) -> Term {
    let type0 = Term::App(
        Box::new(Term::Global("SSort".to_string())),
        Box::new(Term::App(
            Box::new(Term::Global("UType".to_string())),
            Box::new(Term::Lit(Literal::Int(0))),
        )),
    );

    // SLam Type0 body
    let slam = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SLam".to_string())),
            Box::new(type0.clone()),
        )),
        Box::new(body.clone()),
    );

    // SApp (SApp (SName "Forall") Type0) slam
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(Term::App(
                Box::new(Term::App(
                    Box::new(Term::Global("SApp".to_string())),
                    Box::new(Term::App(
                        Box::new(Term::Global("SName".to_string())),
                        Box::new(Term::Lit(Literal::Text("Forall".to_string()))),
                    )),
                )),
                Box::new(type0),
            )),
        )),
        Box::new(slam),
    )
}

// -------------------------------------------------------------------------
// Core Tactics
// -------------------------------------------------------------------------

/// Build SApp (SApp (SApp (SName "Eq") type_s) term) term
///
/// Constructs the Syntax representation of (Eq type_s term term)
fn make_eq_syntax(type_s: &Term, term: &Term) -> Term {
    let eq_name = Term::App(
        Box::new(Term::Global("SName".to_string())),
        Box::new(Term::Lit(Literal::Text("Eq".to_string()))),
    );

    // SApp (SName "Eq") type_s
    let app1 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(eq_name),
        )),
        Box::new(type_s.clone()),
    );

    // SApp (SApp (SName "Eq") type_s) term
    let app2 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app1),
        )),
        Box::new(term.clone()),
    );

    // SApp (SApp (SApp (SName "Eq") type_s) term) term
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app2),
        )),
        Box::new(term.clone()),
    )
}

/// Extract (T, a, b) from SApp (SApp (SApp (SName "Eq") T) a) b
///
/// Pattern matches against the Syntax representation of (Eq T a b)
fn extract_eq(term: &Term) -> Option<(Term, Term, Term)> {
    // term = App(App(SApp, X), b)
    if let Term::App(outer, b) = term {
        if let Term::App(sapp_outer, x) = outer.as_ref() {
            if let Term::Global(ctor) = sapp_outer.as_ref() {
                if ctor == "SApp" {
                    // x = App(App(SApp, Y), a)
                    if let Term::App(inner, a) = x.as_ref() {
                        if let Term::App(sapp_inner, y) = inner.as_ref() {
                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
                                if ctor2 == "SApp" {
                                    // y = App(App(SApp, eq_name), t)
                                    if let Term::App(inner2, t) = y.as_ref() {
                                        if let Term::App(sapp_inner2, sname_eq) = inner2.as_ref() {
                                            if let Term::Global(ctor3) = sapp_inner2.as_ref() {
                                                if ctor3 == "SApp" {
                                                    // sname_eq = App(SName, "Eq")
                                                    if let Term::App(sname, text) = sname_eq.as_ref()
                                                    {
                                                        if let Term::Global(sname_ctor) =
                                                            sname.as_ref()
                                                        {
                                                            if sname_ctor == "SName" {
                                                                if let Term::Lit(Literal::Text(s)) =
                                                                    text.as_ref()
                                                                {
                                                                    if s == "Eq" {
                                                                        return Some((
                                                                            t.as_ref().clone(),
                                                                            a.as_ref().clone(),
                                                                            b.as_ref().clone(),
                                                                        ));
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Build DRefl type_s term
fn make_drefl(type_s: &Term, term: &Term) -> Term {
    let drefl = Term::Global("DRefl".to_string());
    let app1 = Term::App(Box::new(drefl), Box::new(type_s.clone()));
    Term::App(Box::new(app1), Box::new(term.clone()))
}

/// Build DAxiom (SName "Error")
fn make_error_derivation() -> Term {
    let daxiom = Term::Global("DAxiom".to_string());
    let error = make_sname_error();
    Term::App(Box::new(daxiom), Box::new(error))
}

/// Build DAxiom goal (identity derivation)
fn make_daxiom(goal: &Term) -> Term {
    let daxiom = Term::Global("DAxiom".to_string());
    Term::App(Box::new(daxiom), Box::new(goal.clone()))
}

/// Reflexivity tactic: try to prove a goal by reflexivity.
///
/// try_refl goal:
/// - If goal matches (Eq T a b) and a == b, return DRefl T a
/// - Otherwise return DAxiom (SName "Error")
fn try_try_refl_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Normalize the goal first
    let norm_goal = normalize(ctx, goal);

    // Pattern match: SApp (SApp (SApp (SName "Eq") T) a) b
    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
        // Check if left == right (structural equality)
        if syntax_equal(&left, &right) {
            // Success! Return DRefl T a
            return Some(make_drefl(&type_s, &left));
        }
    }

    // Failure: return error derivation
    Some(make_error_derivation())
}

// =============================================================================
// RING TACTIC (POLYNOMIAL EQUALITY)
// =============================================================================

use crate::ring;
use crate::lia;
use crate::cc;
use crate::simp;

/// Ring tactic: try to prove a goal by polynomial normalization.
///
/// try_ring goal:
/// - If goal matches (Eq T a b) where T is Int or Nat
/// - And poly(a) == poly(b) after normalization
/// - Returns DRingSolve goal
/// - Otherwise returns DAxiom (SName "Error")
fn try_try_ring_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Normalize the goal first
    let norm_goal = normalize(ctx, goal);

    // Pattern match: SApp (SApp (SApp (SName "Eq") T) a) b
    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
        // Check type is Int or Nat (ring types)
        if !is_ring_type(&type_s) {
            return Some(make_error_derivation());
        }

        // Reify both sides to polynomials
        let poly_left = match ring::reify(&left) {
            Ok(p) => p,
            Err(_) => return Some(make_error_derivation()),
        };
        let poly_right = match ring::reify(&right) {
            Ok(p) => p,
            Err(_) => return Some(make_error_derivation()),
        };

        // Check canonical equality
        if poly_left.canonical_eq(&poly_right) {
            // Success! Return DRingSolve goal
            return Some(Term::App(
                Box::new(Term::Global("DRingSolve".to_string())),
                Box::new(norm_goal),
            ));
        }
    }

    // Failure: return error derivation
    Some(make_error_derivation())
}

/// Verify DRingSolve proof.
///
/// DRingSolve goal → goal (if verified)
fn try_dring_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Extract T, lhs, rhs from Eq T lhs rhs
    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
        // Verify type is a ring type
        if !is_ring_type(&type_s) {
            return Some(make_sname_error());
        }

        // Reify and verify
        let poly_left = match ring::reify(&left) {
            Ok(p) => p,
            Err(_) => return Some(make_sname_error()),
        };
        let poly_right = match ring::reify(&right) {
            Ok(p) => p,
            Err(_) => return Some(make_sname_error()),
        };

        if poly_left.canonical_eq(&poly_right) {
            return Some(norm_goal);
        }
    }

    Some(make_sname_error())
}

/// Check if a Syntax type is a ring type (Int or Nat)
fn is_ring_type(type_term: &Term) -> bool {
    if let Some(name) = extract_sname_from_syntax(type_term) {
        return name == "Int" || name == "Nat";
    }
    false
}

/// Extract name from SName term
fn extract_sname_from_syntax(term: &Term) -> Option<String> {
    if let Term::App(ctor, arg) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = arg.as_ref() {
                    return Some(s.clone());
                }
            }
        }
    }
    None
}

// =============================================================================
// LIA TACTIC (LINEAR INTEGER ARITHMETIC)
// =============================================================================

/// LIA tactic: try to prove a goal by Fourier-Motzkin elimination.
///
/// try_lia goal:
/// - If goal matches (Lt/Le/Gt/Ge a b)
/// - And Fourier-Motzkin shows the negation is unsatisfiable
/// - Returns DLiaSolve goal
/// - Otherwise returns DAxiom (SName "Error")
fn try_try_lia_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Normalize the goal first
    let norm_goal = normalize(ctx, goal);

    // Extract comparison: (SApp (SApp (SName "Lt"|"Le"|etc) a) b)
    if let Some((rel, lhs_term, rhs_term)) = lia::extract_comparison(&norm_goal) {
        // Reify both sides to linear expressions
        let lhs = match lia::reify_linear(&lhs_term) {
            Ok(l) => l,
            Err(_) => return Some(make_error_derivation()),
        };
        let rhs = match lia::reify_linear(&rhs_term) {
            Ok(r) => r,
            Err(_) => return Some(make_error_derivation()),
        };

        // Convert to negated constraint for validity checking
        if let Some(negated) = lia::goal_to_negated_constraint(&rel, &lhs, &rhs) {
            // If the negation is unsatisfiable, the goal is valid
            if lia::fourier_motzkin_unsat(&[negated]) {
                // Success! Return DLiaSolve goal
                return Some(Term::App(
                    Box::new(Term::Global("DLiaSolve".to_string())),
                    Box::new(norm_goal),
                ));
            }
        }
    }

    // Failure: return error derivation
    Some(make_error_derivation())
}

/// Verify DLiaSolve proof.
///
/// DLiaSolve goal → goal (if verified)
fn try_dlia_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Extract comparison and verify
    if let Some((rel, lhs_term, rhs_term)) = lia::extract_comparison(&norm_goal) {
        // Reify both sides
        let lhs = match lia::reify_linear(&lhs_term) {
            Ok(l) => l,
            Err(_) => return Some(make_sname_error()),
        };
        let rhs = match lia::reify_linear(&rhs_term) {
            Ok(r) => r,
            Err(_) => return Some(make_sname_error()),
        };

        // Verify via Fourier-Motzkin
        if let Some(negated) = lia::goal_to_negated_constraint(&rel, &lhs, &rhs) {
            if lia::fourier_motzkin_unsat(&[negated]) {
                return Some(norm_goal);
            }
        }
    }

    Some(make_sname_error())
}

// =============================================================================
// CONGRUENCE CLOSURE TACTIC
// =============================================================================

/// CC tactic: try to prove a goal by congruence closure.
///
/// try_cc goal:
/// - If goal is a direct equality (Eq a b) or an implication with hypotheses
/// - And congruence closure shows the conclusion follows
/// - Returns DccSolve goal
/// - Otherwise returns DAxiom (SName "Error")
fn try_try_cc_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Normalize the goal first
    let norm_goal = normalize(ctx, goal);

    // Use cc::check_goal which handles both:
    // - Direct equalities: (Eq a b)
    // - Implications: (implies (Eq x y) (Eq (f x) (f y)))
    if cc::check_goal(&norm_goal) {
        // Success! Return DccSolve goal
        return Some(Term::App(
            Box::new(Term::Global("DccSolve".to_string())),
            Box::new(norm_goal),
        ));
    }

    // Failure: return error derivation
    Some(make_error_derivation())
}

/// Verify DccSolve proof.
///
/// DccSolve goal → goal (if verified)
fn try_dcc_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Re-verify using congruence closure
    if cc::check_goal(&norm_goal) {
        return Some(norm_goal);
    }

    Some(make_sname_error())
}

// =============================================================================
// SIMP TACTIC (SIMPLIFICATION)
// =============================================================================

/// try_simp goal:
/// - Prove equalities by simplification and arithmetic evaluation
/// - Handles hypotheses via implications: (implies (Eq x 0) (Eq (add x 1) 1))
/// - Returns DSimpSolve goal on success
/// - Otherwise returns DAxiom (SName "Error")
fn try_try_simp_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Normalize the goal first
    let norm_goal = normalize(ctx, goal);

    // Use simp::check_goal which handles:
    // - Reflexive equalities: (Eq a a)
    // - Constant folding: (Eq (add 2 3) 5)
    // - Hypothesis substitution: (implies (Eq x 0) (Eq (add x 1) 1))
    if simp::check_goal(&norm_goal) {
        // Success! Return DSimpSolve goal
        return Some(Term::App(
            Box::new(Term::Global("DSimpSolve".to_string())),
            Box::new(norm_goal),
        ));
    }

    // Failure: return error derivation
    Some(make_error_derivation())
}

/// Verify DSimpSolve proof.
///
/// DSimpSolve goal → goal (if verified)
fn try_dsimp_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Re-verify using simplification
    if simp::check_goal(&norm_goal) {
        return Some(norm_goal);
    }

    Some(make_sname_error())
}

// =============================================================================
// OMEGA TACTIC (TRUE INTEGER ARITHMETIC)
// =============================================================================

/// try_omega goal:
///
/// Omega tactic using integer-aware Fourier-Motzkin elimination.
/// Unlike lia (which uses rationals), omega handles integers properly:
/// - x > 1 means x >= 2 (strict-to-nonstrict conversion)
/// - 3x <= 10 means x <= 3 (floor division)
///
/// - Extracts comparison (Lt, Le, Gt, Ge) from goal
/// - Reifies to integer linear expressions
/// - Converts to negated constraint (validity = negation is unsat)
/// - Applies omega test
/// - Returns DOmegaSolve goal on success
fn try_try_omega_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Handle implications: extract hypotheses and check conclusion
    if let Some((hyps, conclusion)) = extract_implications(&norm_goal) {
        // Convert hypotheses to constraints
        let mut constraints = Vec::new();

        for hyp in &hyps {
            // Try to extract a comparison from the hypothesis
            if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(hyp) {
                if let (Some(lhs), Some(rhs)) =
                    (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
                {
                    // Add hypothesis as a constraint (it's given, so it's a fact)
                    // For Lt(a, b): a - b < 0, i.e., (a - b) < 0
                    // Constraint form: (a - b + 1) <= 0 for integers (since a < b means a <= b - 1)
                    match rel.as_str() {
                        "Lt" | "lt" => {
                            // a < b means a - b <= -1, i.e., (a - b + 1) <= 0
                            let mut expr = lhs.sub(&rhs);
                            expr.constant += 1;
                            constraints.push(omega::IntConstraint { expr, strict: false });
                        }
                        "Le" | "le" => {
                            // a <= b means a - b <= 0
                            constraints.push(omega::IntConstraint {
                                expr: lhs.sub(&rhs),
                                strict: false,
                            });
                        }
                        "Gt" | "gt" => {
                            // a > b means a - b >= 1, i.e., (b - a + 1) <= 0
                            let mut expr = rhs.sub(&lhs);
                            expr.constant += 1;
                            constraints.push(omega::IntConstraint { expr, strict: false });
                        }
                        "Ge" | "ge" => {
                            // a >= b means b - a <= 0
                            constraints.push(omega::IntConstraint {
                                expr: rhs.sub(&lhs),
                                strict: false,
                            });
                        }
                        _ => {}
                    }
                }
            }
        }

        // Now check if the conclusion is provable given the constraints
        if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&conclusion) {
            if let (Some(lhs), Some(rhs)) =
                (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
            {
                // To prove the conclusion, check if its negation is unsat
                if let Some(neg_constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
                    let mut all_constraints = constraints;
                    all_constraints.push(neg_constraint);

                    if omega::omega_unsat(&all_constraints) {
                        return Some(Term::App(
                            Box::new(Term::Global("DOmegaSolve".to_string())),
                            Box::new(norm_goal),
                        ));
                    }
                }
            }
        }

        // Failure
        return Some(make_error_derivation());
    }

    // Direct comparison (no hypotheses)
    if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&norm_goal) {
        if let (Some(lhs), Some(rhs)) =
            (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
        {
            if let Some(constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
                if omega::omega_unsat(&[constraint]) {
                    return Some(Term::App(
                        Box::new(Term::Global("DOmegaSolve".to_string())),
                        Box::new(norm_goal),
                    ));
                }
            }
        }
    }

    Some(make_error_derivation())
}

/// Verify DOmegaSolve proof.
///
/// DOmegaSolve goal → goal (if verified)
fn try_domega_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Re-verify using omega test
    // Handle implications
    if let Some((hyps, conclusion)) = extract_implications(&norm_goal) {
        let mut constraints = Vec::new();

        for hyp in &hyps {
            if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(hyp) {
                if let (Some(lhs), Some(rhs)) =
                    (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
                {
                    match rel.as_str() {
                        "Lt" | "lt" => {
                            let mut expr = lhs.sub(&rhs);
                            expr.constant += 1;
                            constraints.push(omega::IntConstraint { expr, strict: false });
                        }
                        "Le" | "le" => {
                            constraints.push(omega::IntConstraint {
                                expr: lhs.sub(&rhs),
                                strict: false,
                            });
                        }
                        "Gt" | "gt" => {
                            let mut expr = rhs.sub(&lhs);
                            expr.constant += 1;
                            constraints.push(omega::IntConstraint { expr, strict: false });
                        }
                        "Ge" | "ge" => {
                            constraints.push(omega::IntConstraint {
                                expr: rhs.sub(&lhs),
                                strict: false,
                            });
                        }
                        _ => {}
                    }
                }
            }
        }

        if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&conclusion) {
            if let (Some(lhs), Some(rhs)) =
                (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
            {
                if let Some(neg_constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
                    let mut all_constraints = constraints;
                    all_constraints.push(neg_constraint);

                    if omega::omega_unsat(&all_constraints) {
                        return Some(norm_goal);
                    }
                }
            }
        }

        return Some(make_sname_error());
    }

    // Direct comparison
    if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&norm_goal) {
        if let (Some(lhs), Some(rhs)) =
            (omega::reify_int_linear(&lhs_term), omega::reify_int_linear(&rhs_term))
        {
            if let Some(constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
                if omega::omega_unsat(&[constraint]) {
                    return Some(norm_goal);
                }
            }
        }
    }

    Some(make_sname_error())
}

// =============================================================================
// AUTO TACTIC (THE INFINITY GAUNTLET)
// =============================================================================

/// Check if a derivation is an error derivation.
///
/// Error derivations have the pattern: DAxiom (SApp (SName "Error") ...)
fn is_error_derivation(term: &Term) -> bool {
    // Check for DAxiom constructor
    if let Term::App(ctor, arg) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "DAxiom" {
                // Check if arg is SName "Error" or SApp (SName "Error") ...
                if let Term::App(sname, inner) = arg.as_ref() {
                    if let Term::Global(sn) = sname.as_ref() {
                        if sn == "SName" {
                            if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                                return s == "Error";
                            }
                        }
                        if sn == "SApp" {
                            // Recursively check - could be SApp (SName "Error") ...
                            return true; // For now, treat any DAxiom as potential error
                        }
                    }
                }
                // DAxiom with SName "Error"
                if let Term::Global(sn) = arg.as_ref() {
                    // This shouldn't happen but just in case
                    return sn == "Error";
                }
                return true; // Any DAxiom is treated as error for auto purposes
            }
        }
    }
    false
}

/// Auto tactic: tries each decision procedure in sequence.
///
/// Order: True/False → simp → ring → cc → omega → lia
/// Returns the first successful derivation, or error if all fail.
// =============================================================================
// HARDWARE TACTICS (bitblast, tabulate, hw_auto)
// =============================================================================

/// Bitblast tactic: prove Eq Bit lhs rhs by normalizing both sides.
///
/// Operates on Syntax terms: SApp(SApp(SApp(SName("Eq"), SName("Bit")), lhs), rhs)
/// Normalizes lhs and rhs to concrete Bit values (B0/B1) and checks equality.
fn try_try_bitblast_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Extract Eq T lhs rhs from Syntax
    if let Some((type_s, left, right)) = extract_eq_syntax_parts(&norm_goal) {
        // Check type is Bit (or BVec — for future extension)
        if !is_bit_type(&type_s) {
            return Some(make_error_derivation());
        }

        // Evaluate both sides using syn_eval with delta reduction support.
        // syn_step now handles definition unfolding (delta reduction),
        // so syn_eval correctly reduces expressions like
        // SApp(SApp(SName("bit_and"), SName("B1")), SName("B0")) → SName("B0")
        let fuel = 1000;
        let left_eval = try_syn_eval_reduce(ctx, fuel, &left)?;
        let right_eval = try_syn_eval_reduce(ctx, fuel, &right)?;

        if syntax_equal(&left_eval, &right_eval) {
            return Some(Term::App(
                Box::new(Term::Global("DBitblastSolve".to_string())),
                Box::new(norm_goal),
            ));
        }
    }

    Some(make_error_derivation())
}

/// Convert a Syntax deep embedding back to a kernel Term.
///
/// This is the proper bridge between the reflected Syntax representation
/// and the kernel's native Term language. The kernel normalizer handles
/// all reduction strategies (delta, iota, beta, fix), so reifying to Term
/// and normalizing there gives correct results for hardware gate expressions.
///
/// Handles: SName, SApp, SLit, SVar, SLam, SPi, SSort, SMatch
fn syntax_to_term(syntax: &Term) -> Option<Term> {
    if let Term::App(ctor, inner) = syntax {
        if let Term::Global(name) = ctor.as_ref() {
            match name.as_str() {
                "SName" => {
                    if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                        return Some(Term::Global(s.clone()));
                    }
                }
                "SLit" => {
                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
                        return Some(Term::Lit(Literal::Int(*n)));
                    }
                }
                "SVar" => {
                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
                        return Some(Term::Var(format!("v{}", n)));
                    }
                }
                "SGlobal" => {
                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
                        return Some(Term::Var(format!("g{}", n)));
                    }
                }
                _ => {}
            }
        }
    }

    // Two-argument constructors: SApp, SLam, SPi
    if let Term::App(outer, second) = syntax {
        if let Term::App(sctor, first) = outer.as_ref() {
            if let Term::Global(name) = sctor.as_ref() {
                match name.as_str() {
                    "SApp" => {
                        let f = syntax_to_term(first)?;
                        let x = syntax_to_term(second)?;
                        return Some(Term::App(Box::new(f), Box::new(x)));
                    }
                    "SLam" => {
                        let param_type = syntax_to_term(first)?;
                        let body = syntax_to_term(second)?;
                        return Some(Term::Lambda {
                            param: "_".to_string(),
                            param_type: Box::new(param_type),
                            body: Box::new(body),
                        });
                    }
                    "SPi" => {
                        let param_type = syntax_to_term(first)?;
                        let body_type = syntax_to_term(second)?;
                        return Some(Term::Pi {
                            param: "_".to_string(),
                            param_type: Box::new(param_type),
                            body_type: Box::new(body_type),
                        });
                    }
                    _ => {}
                }
            }
        }
    }

    // Three-argument: SMatch discriminant motive cases
    // (SApp (SApp (SApp (SName "SMatch") disc) motive) cases)
    if let Term::App(outer, third) = syntax {
        if let Term::App(mid, second) = outer.as_ref() {
            if let Term::App(inner, first) = mid.as_ref() {
                if let Term::Global(name) = inner.as_ref() {
                    if name == "SMatch" {
                        let disc = syntax_to_term(first)?;
                        let motive = syntax_to_term(second)?;
                        // cases would need list handling — skip for now
                        let _ = third;
                        return Some(Term::Match {
                            discriminant: Box::new(disc),
                            motive: Box::new(motive),
                            cases: vec![],
                        });
                    }
                }
            }
        }
    }

    None
}

/// Check if a Syntax type term represents Bit.
fn is_bit_type(term: &Term) -> bool {
    // SName "Bit"
    if let Term::App(ctor, inner) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                    return s == "Bit";
                }
            }
        }
    }
    false
}

/// Substitute SVar(idx) with `replacement` in a Syntax term, shifting de Bruijn
/// indices under binders (SPi, SLam).
fn syntax_subst_var(term: &Term, idx: i64, replacement: &Term) -> Term {
    // Check for SVar n
    if let Term::App(ctor, inner) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SVar" {
                if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
                    if *n == idx {
                        return replacement.clone();
                    } else if *n > idx {
                        // Free variable above the binder — shift down
                        return make_svar(*n - 1);
                    } else {
                        return term.clone();
                    }
                }
            }
        }
    }

    // Two-argument constructors: SApp, SLam, SPi
    if let Term::App(outer, second) = term {
        if let Term::App(sctor, first) = outer.as_ref() {
            if let Term::Global(name) = sctor.as_ref() {
                match name.as_str() {
                    "SApp" => {
                        let f = syntax_subst_var(first, idx, replacement);
                        let x = syntax_subst_var(second, idx, replacement);
                        return make_sapp(f, x);
                    }
                    "SPi" => {
                        // Under a binder, shift the index
                        let param_t = syntax_subst_var(first, idx, replacement);
                        let body = syntax_subst_var(second, idx + 1, replacement);
                        return make_spi(param_t, body);
                    }
                    "SLam" => {
                        let param_t = syntax_subst_var(first, idx, replacement);
                        let body = syntax_subst_var(second, idx + 1, replacement);
                        return make_slam(param_t, body);
                    }
                    _ => {}
                }
            }
        }
    }

    // One-argument constructors that don't bind: SName, SLit, SSort — return as-is
    term.clone()
}

/// Tabulate tactic: prove universally quantified Bit goals by exhaustive enumeration.
///
/// For a goal of the form SPi(SName("Bit"), body):
/// 1. Substitute SVar 0 with SName("B0") in body → body_b0
/// 2. Substitute SVar 0 with SName("B1") in body → body_b1
/// 3. Recursively verify both substituted bodies
/// 4. If both succeed, return DTabulateSolve(goal)
///
/// Handles nested Pi binders (e.g., Pi(a:Bit). Pi(b:Bit). P(a,b)) by recursion.
/// Rejects non-Bit quantification.
fn try_try_tabulate_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Try to extract SPi(param_type, body)
    if let Some((param_type, body)) = extract_spi(&norm_goal) {
        // Only handle Bit quantification
        if !is_bit_type(&param_type) {
            return Some(make_error_derivation());
        }

        // Substitute SVar 0 with B0 and B1
        let body_b0 = syntax_subst_var(&body, 0, &make_sname("B0"));
        let body_b1 = syntax_subst_var(&body, 0, &make_sname("B1"));

        // Recursively verify both cases
        let ok_b0 = tabulate_verify_case(ctx, &body_b0);
        let ok_b1 = tabulate_verify_case(ctx, &body_b1);

        if ok_b0 && ok_b1 {
            return Some(Term::App(
                Box::new(Term::Global("DTabulateSolve".to_string())),
                Box::new(norm_goal),
            ));
        }

        return Some(make_error_derivation());
    }

    // Not a Pi — not a quantified goal
    Some(make_error_derivation())
}

/// Verify a single case for tabulation. The case is either:
/// - An Eq(Bit, lhs, rhs) — verify by normalizing both sides
/// - Another SPi(Bit, ...) — recurse (nested quantification)
/// - A formula that reduces to SName("True") — trivially true
fn tabulate_verify_case(ctx: &Context, case: &Term) -> bool {
    let norm = normalize(ctx, case);

    // If it's another Pi over Bit, recurse
    if let Some((param_type, _)) = extract_spi(&norm) {
        if is_bit_type(&param_type) {
            if let Some(result) = try_try_tabulate_reduce(ctx, &norm) {
                return !is_error_derivation(&result);
            }
        }
        return false;
    }

    // Try to verify as an Eq
    if let Some((type_s, left, right)) = extract_eq_syntax_parts(&norm) {
        let fuel = 1000;
        if let (Some(left_eval), Some(right_eval)) = (
            try_syn_eval_reduce(ctx, fuel, &left),
            try_syn_eval_reduce(ctx, fuel, &right),
        ) {
            return syntax_equal(&left_eval, &right_eval);
        }
        // Try evaluating the whole equality — might reduce to True
        if let Some(full_eval) = try_syn_eval_reduce(ctx, fuel, &norm) {
            if is_sname_with_value(&full_eval, "True") {
                return true;
            }
        }
        return false;
    }

    // Try evaluating the whole formula — might be SName("True")
    let fuel = 1000;
    if let Some(eval) = try_syn_eval_reduce(ctx, fuel, &norm) {
        if is_sname_with_value(&eval, "True") {
            return true;
        }
    }

    false
}

/// Check if a Syntax term is SName(value)
fn is_sname_with_value(term: &Term, value: &str) -> bool {
    if let Term::App(ctor, inner) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                    return s == value;
                }
            }
        }
    }
    false
}

/// Verify DBitblastSolve proof by re-evaluating via syn_eval.
fn try_dbitblast_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);
    if let Some((type_s, left, right)) = extract_eq_syntax_parts(&norm_goal) {
        if is_bit_type(&type_s) {
            let fuel = 1000;
            let left_eval = try_syn_eval_reduce(ctx, fuel, &left)?;
            let right_eval = try_syn_eval_reduce(ctx, fuel, &right)?;
            if syntax_equal(&left_eval, &right_eval) {
                return Some(norm_goal);
            }
        }
    }
    None
}

/// Verify DTabulateSolve proof by re-running exhaustive enumeration.
fn try_dtabulate_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);
    // Re-verify: the goal must be a provable Pi-over-Bit
    if let Some((param_type, _)) = extract_spi(&norm_goal) {
        if is_bit_type(&param_type) {
            if let Some(result) = try_try_tabulate_reduce(ctx, &norm_goal) {
                if !is_error_derivation(&result) {
                    return Some(norm_goal);
                }
            }
        }
    }
    None
}

/// Verify DHwAutoSolve proof by re-running hw tactic chain.
fn try_dhw_auto_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    // Try bitblast conclude first
    if let Some(result) = try_dbitblast_solve_conclude(ctx, goal) {
        return Some(result);
    }
    // Fall back to auto conclude
    try_dauto_solve_conclude(ctx, goal)
}

/// Hardware auto: tries bitblast, then tabulate, then falls back to auto.
fn try_try_hw_auto_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Try bitblast first (fast, for concrete Bit equalities)
    if let Some(result) = try_try_bitblast_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try tabulate (for universal Bit quantification)
    if let Some(result) = try_try_tabulate_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Fall back to auto
    try_try_auto_reduce(ctx, &norm_goal)
}

fn try_try_auto_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Handle trivial cases: True and False
    // SName "True" is trivially provable
    if let Term::App(ctor, inner) = &norm_goal {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                    if s == "True" {
                        // True is always provable - use DAutoSolve
                        return Some(Term::App(
                            Box::new(Term::Global("DAutoSolve".to_string())),
                            Box::new(norm_goal),
                        ));
                    }
                    if s == "False" {
                        // False is never provable
                        return Some(make_error_derivation());
                    }
                }
            }
        }
    }

    // Try simp (handles equalities with simplification)
    if let Some(result) = try_try_simp_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try ring (polynomial equalities)
    if let Some(result) = try_try_ring_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try cc (congruence closure)
    if let Some(result) = try_try_cc_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try omega (integer arithmetic - most precise)
    if let Some(result) = try_try_omega_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try lia (linear arithmetic - fallback)
    if let Some(result) = try_try_lia_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(result);
        }
    }

    // Try registered hints
    for hint_name in ctx.get_hints() {
        if let Some(hint_type) = ctx.get_global(hint_name) {
            if let Some(result) = try_apply_hint(ctx, hint_name, hint_type, &norm_goal) {
                return Some(result);
            }
        }
    }

    // All tactics failed
    Some(make_error_derivation())
}

/// Verify DAutoSolve proof by re-running tactic search.
fn try_dauto_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Handle trivial cases: True
    if let Term::App(ctor, inner) = &norm_goal {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
                    if s == "True" {
                        return Some(norm_goal.clone());
                    }
                }
            }
        }
    }

    // Try each tactic - if any succeeds, the proof is valid
    if let Some(result) = try_try_simp_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(norm_goal.clone());
        }
    }
    if let Some(result) = try_try_ring_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(norm_goal.clone());
        }
    }
    if let Some(result) = try_try_cc_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(norm_goal.clone());
        }
    }
    if let Some(result) = try_try_omega_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(norm_goal.clone());
        }
    }
    if let Some(result) = try_try_lia_reduce(ctx, &norm_goal) {
        if !is_error_derivation(&result) {
            return Some(norm_goal.clone());
        }
    }

    // Try registered hints
    for hint_name in ctx.get_hints() {
        if let Some(hint_type) = ctx.get_global(hint_name) {
            if try_apply_hint(ctx, hint_name, hint_type, &norm_goal).is_some() {
                return Some(norm_goal);
            }
        }
    }

    Some(make_sname_error())
}

// =============================================================================
// GENERIC INDUCTION HELPERS (induction_num_cases, induction_base_goal, etc.)
// =============================================================================

/// Returns the number of constructors for an inductive type.
///
/// induction_num_cases (SName "Nat") → Succ (Succ Zero) = 2
/// induction_num_cases (SName "Bool") → Succ (Succ Zero) = 2
/// induction_num_cases (SApp (SName "List") A) → Succ (Succ Zero) = 2
fn try_induction_num_cases_reduce(ctx: &Context, ind_type: &Term) -> Option<Term> {
    // Extract inductive name from Syntax
    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
        Some(name) => name,
        None => {
            // Not a valid inductive type syntax
            return Some(Term::Global("Zero".to_string()));
        }
    };

    // Look up constructors
    let constructors = ctx.get_constructors(&ind_name);
    let num_ctors = constructors.len();

    // Build Nat representation: Succ (Succ (... Zero))
    let mut result = Term::Global("Zero".to_string());
    for _ in 0..num_ctors {
        result = Term::App(
            Box::new(Term::Global("Succ".to_string())),
            Box::new(result),
        );
    }

    Some(result)
}

/// Returns the base case goal for induction (first constructor).
///
/// Given ind_type and motive (SLam T body), returns motive[ctor0/var].
fn try_induction_base_goal_reduce(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
) -> Option<Term> {
    // Extract inductive name
    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
        Some(name) => name,
        None => return Some(make_sname_error()),
    };

    // Get constructors
    let constructors = ctx.get_constructors(&ind_name);
    if constructors.is_empty() {
        return Some(make_sname_error());
    }

    // Extract motive body
    let motive_body = match extract_slam_body(motive) {
        Some(body) => body,
        None => return Some(make_sname_error()),
    };

    // Build goal for first constructor (base case)
    let (ctor_name, _) = constructors[0];
    build_case_expected(ctx, ctor_name, &constructors, &motive_body, ind_type)
}

/// Returns the goal for a specific constructor index.
///
/// Given ind_type, motive, and constructor index (as Nat), returns the case goal.
fn try_induction_step_goal_reduce(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
    ctor_idx: &Term,
) -> Option<Term> {
    // Extract inductive name
    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
        Some(name) => name,
        None => return Some(make_sname_error()),
    };

    // Get constructors
    let constructors = ctx.get_constructors(&ind_name);
    if constructors.is_empty() {
        return Some(make_sname_error());
    }

    // Convert Nat to index
    let idx = nat_to_usize(ctor_idx)?;
    if idx >= constructors.len() {
        return Some(make_sname_error());
    }

    // Extract motive body
    let motive_body = match extract_slam_body(motive) {
        Some(body) => body,
        None => return Some(make_sname_error()),
    };

    // Build goal for the specified constructor
    let (ctor_name, _) = constructors[idx];
    build_case_expected(ctx, ctor_name, &constructors, &motive_body, ind_type)
}

/// Convert a Nat term to usize.
///
/// Zero → 0
/// Succ Zero → 1
/// Succ (Succ Zero) → 2
fn nat_to_usize(term: &Term) -> Option<usize> {
    match term {
        Term::Global(name) if name == "Zero" => Some(0),
        Term::App(succ, inner) => {
            if let Term::Global(name) = succ.as_ref() {
                if name == "Succ" {
                    return nat_to_usize(inner).map(|n| n + 1);
                }
            }
            None
        }
        _ => None,
    }
}

/// Generic induction tactic.
///
/// try_induction ind_type motive cases → DElim ind_type motive cases
///
/// Delegates to existing DElim infrastructure after basic validation.
fn try_try_induction_reduce(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
    cases: &Term,
) -> Option<Term> {
    // Extract inductive name to validate
    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
        Some(name) => name,
        None => return Some(make_error_derivation()),
    };

    // Get constructors to validate count
    let constructors = ctx.get_constructors(&ind_name);
    if constructors.is_empty() {
        return Some(make_error_derivation());
    }

    // Extract case proofs to validate count
    let case_proofs = match extract_case_proofs(cases) {
        Some(proofs) => proofs,
        None => return Some(make_error_derivation()),
    };

    // Verify case count matches constructor count
    if case_proofs.len() != constructors.len() {
        return Some(make_error_derivation());
    }

    // Build DElim term (delegates verification to existing infrastructure)
    Some(Term::App(
        Box::new(Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("DElim".to_string())),
                Box::new(ind_type.clone()),
            )),
            Box::new(motive.clone()),
        )),
        Box::new(cases.clone()),
    ))
}

// -------------------------------------------------------------------------
// Deep Induction
// -------------------------------------------------------------------------

/// DInduction reduction with verification.
///
/// DInduction motive base step → Forall Nat motive (if verified)
///
/// Verification:
/// 1. Extract motive body from SLam Nat body
/// 2. Check that concludes(base) = motive[Zero/0]
/// 3. Check that concludes(step) = ∀k:Nat. P(k) → P(Succ k)
/// 4. If all checks pass, return Forall Nat motive
/// 5. Otherwise, return Error
fn try_dinduction_reduce(
    ctx: &Context,
    motive: &Term,
    base: &Term,
    step: &Term,
) -> Option<Term> {
    // Normalize all inputs
    let norm_motive = normalize(ctx, motive);
    let norm_base = normalize(ctx, base);
    let norm_step = normalize(ctx, step);

    // 1. Extract motive body (should be SLam (SName "Nat") body)
    let motive_body = match extract_slam_body(&norm_motive) {
        Some(body) => body,
        None => return Some(make_sname_error()),
    };

    // 2. Compute expected base: motive body with Zero substituted for SVar 0
    let zero = make_sname("Zero");
    let expected_base = match try_syn_subst_reduce(ctx, &zero, 0, &motive_body) {
        Some(b) => b,
        None => return Some(make_sname_error()),
    };

    // 3. Get actual base conclusion
    let base_conc = match try_concludes_reduce(ctx, &norm_base) {
        Some(c) => c,
        None => return Some(make_sname_error()),
    };

    // 4. Verify base matches expected
    if !syntax_equal(&base_conc, &expected_base) {
        return Some(make_sname_error());
    }

    // 5. Build expected step formula: ∀k:Nat. P(k) → P(Succ k)
    let expected_step = match build_induction_step_formula(ctx, &motive_body) {
        Some(s) => s,
        None => return Some(make_sname_error()),
    };

    // 6. Get actual step conclusion
    let step_conc = match try_concludes_reduce(ctx, &norm_step) {
        Some(c) => c,
        None => return Some(make_sname_error()),
    };

    // 7. Verify step matches expected
    if !syntax_equal(&step_conc, &expected_step) {
        return Some(make_sname_error());
    }

    // 8. Return conclusion: Forall Nat motive
    Some(make_forall_nat_syntax(&norm_motive))
}

/// Build step formula: ∀k:Nat. P(k) → P(Succ k)
///
/// Given motive body P (which uses SVar 0 for k), builds:
/// Forall (SName "Nat") (SLam (SName "Nat") (Implies P P[Succ(SVar 0)/SVar 0]))
fn build_induction_step_formula(ctx: &Context, motive_body: &Term) -> Option<Term> {
    // P(k) = motive_body (uses SVar 0 for k)
    let p_k = motive_body.clone();

    // P(Succ k) = motive_body with (SApp (SName "Succ") (SVar 0)) substituted
    let succ_var = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(make_sname("Succ")),
        )),
        Box::new(Term::App(
            Box::new(Term::Global("SVar".to_string())),
            Box::new(Term::Lit(Literal::Int(0))),
        )),
    );
    let p_succ_k = try_syn_subst_reduce(ctx, &succ_var, 0, motive_body)?;

    // Implies P(k) P(Succ k)
    let implies_body = make_implies_syntax(&p_k, &p_succ_k);

    // SLam (SName "Nat") implies_body
    let slam = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SLam".to_string())),
            Box::new(make_sname("Nat")),
        )),
        Box::new(implies_body),
    );

    // Forall (SName "Nat") slam
    Some(make_forall_syntax_with_type(&make_sname("Nat"), &slam))
}

/// Build SApp (SApp (SName "Implies") a) b
fn make_implies_syntax(a: &Term, b: &Term) -> Term {
    // SApp (SName "Implies") a
    let app1 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(make_sname("Implies")),
        )),
        Box::new(a.clone()),
    );

    // SApp (SApp (SName "Implies") a) b
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app1),
        )),
        Box::new(b.clone()),
    )
}

/// Build SApp (SApp (SName "Forall") (SName "Nat")) motive
fn make_forall_nat_syntax(motive: &Term) -> Term {
    make_forall_syntax_with_type(&make_sname("Nat"), motive)
}

/// Build SApp (SApp (SName "Forall") type_s) body
fn make_forall_syntax_with_type(type_s: &Term, body: &Term) -> Term {
    // SApp (SName "Forall") type_s
    let app1 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(make_sname("Forall")),
        )),
        Box::new(type_s.clone()),
    );

    // SApp (SApp (SName "Forall") type_s) body
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app1),
        )),
        Box::new(body.clone()),
    )
}

// -------------------------------------------------------------------------
// Solver (Computational Reflection)
// -------------------------------------------------------------------------

/// DCompute reduction with verification.
///
/// DCompute goal → goal (if verified by computation)
///
/// Verification:
/// 1. Check that goal is (Eq T A B) as Syntax
/// 2. Evaluate A and B using syn_eval with bounded fuel
/// 3. If eval(A) == eval(B), return goal
/// 4. Otherwise, return Error
fn try_dcompute_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Extract T, A, B from Eq T A B (as Syntax)
    // Pattern: SApp (SApp (SApp (SName "Eq") T) A) B
    let parts = extract_eq_syntax_parts(&norm_goal);
    if parts.is_none() {
        // Goal is not an equality - return Error
        return Some(make_sname_error());
    }
    let (_, a, b) = parts.unwrap();

    // Evaluate A and B with generous fuel
    let fuel = 1000;
    let a_eval = match try_syn_eval_reduce(ctx, fuel, &a) {
        Some(e) => e,
        None => return Some(make_sname_error()),
    };
    let b_eval = match try_syn_eval_reduce(ctx, fuel, &b) {
        Some(e) => e,
        None => return Some(make_sname_error()),
    };

    // Compare normalized results
    if syntax_equal(&a_eval, &b_eval) {
        Some(norm_goal)
    } else {
        Some(make_sname_error())
    }
}

/// Extract T, A, B from Eq T A B (as Syntax)
///
/// Pattern: SApp (SApp (SApp (SName "Eq") T) A) B
fn extract_eq_syntax_parts(term: &Term) -> Option<(Term, Term, Term)> {
    // term = SApp X B where X = SApp Y A where Y = SApp (SName "Eq") T
    // Structure: App(App(SApp, App(App(SApp, App(App(SApp, App(SName, "Eq")), T)), A)), B)
    if let Term::App(partial2, b) = term {
        if let Term::App(sapp2, inner2) = partial2.as_ref() {
            if let Term::Global(sapp2_name) = sapp2.as_ref() {
                if sapp2_name != "SApp" {
                    return None;
                }
            } else {
                return None;
            }

            if let Term::App(partial1, a) = inner2.as_ref() {
                if let Term::App(sapp1, inner1) = partial1.as_ref() {
                    if let Term::Global(sapp1_name) = sapp1.as_ref() {
                        if sapp1_name != "SApp" {
                            return None;
                        }
                    } else {
                        return None;
                    }

                    if let Term::App(eq_t, t) = inner1.as_ref() {
                        if let Term::App(sapp0, eq_sname) = eq_t.as_ref() {
                            if let Term::Global(sapp0_name) = sapp0.as_ref() {
                                if sapp0_name != "SApp" {
                                    return None;
                                }
                            } else {
                                return None;
                            }

                            // Check if eq_sname is SName "Eq"
                            if let Term::App(sname_ctor, eq_str) = eq_sname.as_ref() {
                                if let Term::Global(ctor) = sname_ctor.as_ref() {
                                    if ctor == "SName" {
                                        if let Term::Lit(Literal::Text(s)) = eq_str.as_ref() {
                                            if s == "Eq" {
                                                return Some((
                                                    t.as_ref().clone(),
                                                    a.as_ref().clone(),
                                                    b.as_ref().clone(),
                                                ));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

// -------------------------------------------------------------------------
// Tactic Combinators
// -------------------------------------------------------------------------

/// Reduce tact_orelse t1 t2 goal
///
/// - Apply t1 to goal
/// - If concludes returns Error, apply t2 to goal
/// - Otherwise return t1's result
fn try_tact_orelse_reduce(
    ctx: &Context,
    t1: &Term,
    t2: &Term,
    goal: &Term,
) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Apply t1 to goal
    let d1_app = Term::App(Box::new(t1.clone()), Box::new(norm_goal.clone()));
    let d1 = normalize(ctx, &d1_app);

    // Check if t1 succeeded by looking at concludes
    if let Some(conc1) = try_concludes_reduce(ctx, &d1) {
        if is_error_syntax(&conc1) {
            // t1 failed, try t2
            let d2_app = Term::App(Box::new(t2.clone()), Box::new(norm_goal));
            return Some(normalize(ctx, &d2_app));
        } else {
            // t1 succeeded
            return Some(d1);
        }
    }

    // Couldn't evaluate concludes - return error
    Some(make_error_derivation())
}

/// Check if a Syntax term is SName "Error"
fn is_error_syntax(term: &Term) -> bool {
    // Pattern: SName "Error" = App(Global("SName"), Lit(Text("Error")))
    if let Term::App(ctor, arg) = term {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SName" {
                if let Term::Lit(Literal::Text(s)) = arg.as_ref() {
                    return s == "Error";
                }
            }
        }
    }
    false
}

/// Reduce tact_try t goal
///
/// - Apply t to goal
/// - If concludes returns Error, return identity (DAxiom goal)
/// - Otherwise return t's result
fn try_tact_try_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Apply t to goal
    let d_app = Term::App(Box::new(t.clone()), Box::new(norm_goal.clone()));
    let d = normalize(ctx, &d_app);

    // Check if t succeeded by looking at concludes
    if let Some(conc) = try_concludes_reduce(ctx, &d) {
        if is_error_syntax(&conc) {
            // t failed, return identity (DAxiom goal)
            return Some(make_daxiom(&norm_goal));
        } else {
            // t succeeded
            return Some(d);
        }
    }

    // Couldn't evaluate concludes - return identity
    Some(make_daxiom(&norm_goal))
}

/// Reduce tact_repeat t goal
///
/// Apply t repeatedly until it fails or makes no progress.
/// Returns the accumulated derivation or identity if first application fails.
fn try_tact_repeat_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
    const MAX_ITERATIONS: usize = 100;

    let norm_goal = normalize(ctx, goal);
    let mut current_goal = norm_goal.clone();
    let mut last_successful_deriv: Option<Term> = None;

    for _ in 0..MAX_ITERATIONS {
        // Apply t to current goal
        let d_app = Term::App(Box::new(t.clone()), Box::new(current_goal.clone()));
        let d = normalize(ctx, &d_app);

        // Check result
        if let Some(conc) = try_concludes_reduce(ctx, &d) {
            if is_error_syntax(&conc) {
                // Tactic failed - stop and return what we have
                break;
            }

            // Check for no-progress (fixed point)
            if syntax_equal(&conc, &current_goal) {
                // No progress made - stop
                break;
            }

            // Progress made - continue
            current_goal = conc;
            last_successful_deriv = Some(d);
        } else {
            // Couldn't evaluate concludes - stop
            break;
        }
    }

    // Return final derivation or identity
    last_successful_deriv.or_else(|| Some(make_daxiom(&norm_goal)))
}

/// Reduce tact_then t1 t2 goal
///
/// - Apply t1 to goal
/// - If t1 fails, return Error
/// - Otherwise apply t2 to the result of t1
fn try_tact_then_reduce(
    ctx: &Context,
    t1: &Term,
    t2: &Term,
    goal: &Term,
) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Apply t1 to goal
    let d1_app = Term::App(Box::new(t1.clone()), Box::new(norm_goal.clone()));
    let d1 = normalize(ctx, &d1_app);

    // Check if t1 succeeded
    if let Some(conc1) = try_concludes_reduce(ctx, &d1) {
        if is_error_syntax(&conc1) {
            // t1 failed
            return Some(make_error_derivation());
        }

        // t1 succeeded - apply t2 to the new goal (conc1)
        let d2_app = Term::App(Box::new(t2.clone()), Box::new(conc1));
        let d2 = normalize(ctx, &d2_app);

        // The result is d2 (which may succeed or fail)
        return Some(d2);
    }

    // Couldn't evaluate concludes - return error
    Some(make_error_derivation())
}

/// Reduce tact_first tactics goal
///
/// Try each tactic in the list until one succeeds.
/// Returns Error if all fail or list is empty.
fn try_tact_first_reduce(ctx: &Context, tactics: &Term, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Extract tactics from TList
    let tactic_vec = extract_tlist(tactics)?;

    for tactic in tactic_vec {
        // Apply this tactic to goal
        let d_app = Term::App(Box::new(tactic), Box::new(norm_goal.clone()));
        let d = normalize(ctx, &d_app);

        // Check if it succeeded
        if let Some(conc) = try_concludes_reduce(ctx, &d) {
            if !is_error_syntax(&conc) {
                // Success!
                return Some(d);
            }
            // Failed - try next
        }
    }

    // All failed
    Some(make_error_derivation())
}

/// Extract elements from a TList term
///
/// TList is polymorphic: TNil A and TCons A h t
/// So the structure is:
/// - TNil A = App(Global("TNil"), type)
/// - TCons A h t = App(App(App(Global("TCons"), type), head), tail)
fn extract_tlist(term: &Term) -> Option<Vec<Term>> {
    let mut result = Vec::new();
    let mut current = term.clone();

    loop {
        match &current {
            // TNil A = App(Global("TNil"), type)
            Term::App(tnil, _type) => {
                if let Term::Global(name) = tnil.as_ref() {
                    if name == "TNil" {
                        // Empty list
                        break;
                    }
                }
                // Try TCons A h t = App(App(App(Global("TCons"), type), head), tail)
                if let Term::App(partial2, tail) = &current {
                    if let Term::App(partial1, head) = partial2.as_ref() {
                        if let Term::App(tcons, _type) = partial1.as_ref() {
                            if let Term::Global(name) = tcons.as_ref() {
                                if name == "TCons" {
                                    result.push(head.as_ref().clone());
                                    current = tail.as_ref().clone();
                                    continue;
                                }
                            }
                        }
                    }
                }
                // Not a valid TList structure
                return None;
            }
            // Bare Global("TNil") without type argument - also valid
            Term::Global(name) if name == "TNil" => {
                break;
            }
            _ => {
                // Not a valid TList
                return None;
            }
        }
    }

    Some(result)
}

/// Reduce tact_solve t goal
///
/// - Apply t to goal
/// - If t fails (Error), return Error
/// - If t succeeds, return its result
fn try_tact_solve_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
    let norm_goal = normalize(ctx, goal);

    // Apply t to goal
    let d_app = Term::App(Box::new(t.clone()), Box::new(norm_goal.clone()));
    let d = normalize(ctx, &d_app);

    // Check if t succeeded
    if let Some(conc) = try_concludes_reduce(ctx, &d) {
        if is_error_syntax(&conc) {
            // t failed
            return Some(make_error_derivation());
        }
        // t succeeded - return its derivation
        return Some(d);
    }

    // Couldn't evaluate concludes - return error
    Some(make_error_derivation())
}

// -------------------------------------------------------------------------
// Congruence Closure
// -------------------------------------------------------------------------

/// Validate DCong proof by congruence.
///
/// DCong context eq_proof where:
/// - context is SLam param_type body
/// - eq_proof proves Eq T a b
/// Returns: Eq param_type (body[0:=a]) (body[0:=b])
fn try_dcong_conclude(ctx: &Context, context: &Term, eq_proof: &Term) -> Option<Term> {
    // Get the conclusion of the equality proof
    let eq_conc = try_concludes_reduce(ctx, eq_proof)?;

    // Extract T, a, b from Eq T a b
    let parts = extract_eq_syntax_parts(&eq_conc);
    if parts.is_none() {
        // Not an equality proof
        return Some(make_sname_error());
    }
    let (_type_term, lhs, rhs) = parts.unwrap();

    // Normalize context and check it's a lambda
    let norm_context = normalize(ctx, context);

    // Extract (param_type, body) from SLam param_type body
    let slam_parts = extract_slam_parts(&norm_context);
    if slam_parts.is_none() {
        // Not a lambda context
        return Some(make_sname_error());
    }
    let (param_type, body) = slam_parts.unwrap();

    // Substitute lhs and rhs into body at index 0
    let fa = try_syn_subst_reduce(ctx, &lhs, 0, &body)?;
    let fb = try_syn_subst_reduce(ctx, &rhs, 0, &body)?;

    // Build result: Eq param_type fa fb
    Some(make_eq_syntax_three(&param_type, &fa, &fb))
}

/// Extract (param_type, body) from SLam param_type body
///
/// Pattern: App(App(Global("SLam"), param_type), body)
fn extract_slam_parts(term: &Term) -> Option<(Term, Term)> {
    if let Term::App(inner, body) = term {
        if let Term::App(slam_ctor, param_type) = inner.as_ref() {
            if let Term::Global(name) = slam_ctor.as_ref() {
                if name == "SLam" {
                    return Some((param_type.as_ref().clone(), body.as_ref().clone()));
                }
            }
        }
    }
    None
}

/// Build SApp (SApp (SApp (SName "Eq") type_s) a) b
///
/// Constructs the Syntax representation of (Eq type_s a b)
fn make_eq_syntax_three(type_s: &Term, a: &Term, b: &Term) -> Term {
    let eq_name = Term::App(
        Box::new(Term::Global("SName".to_string())),
        Box::new(Term::Lit(Literal::Text("Eq".to_string()))),
    );

    // SApp (SName "Eq") type_s
    let app1 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(eq_name),
        )),
        Box::new(type_s.clone()),
    );

    // SApp (SApp (SName "Eq") type_s) a
    let app2 = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app1),
        )),
        Box::new(a.clone()),
    );

    // SApp (SApp (SApp (SName "Eq") type_s) a) b
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(app2),
        )),
        Box::new(b.clone()),
    )
}

// -------------------------------------------------------------------------
// Generic Elimination
// -------------------------------------------------------------------------

/// DElim reduction with verification.
///
/// DElim ind_type motive cases → Forall ind_type motive (if verified)
///
/// Verification:
/// 1. Extract inductive name from ind_type Syntax
/// 2. Look up constructors for that inductive
/// 3. Extract case proofs from DCase chain
/// 4. Verify case count matches constructor count
/// 5. For each constructor, verify case conclusion matches expected
/// 6. Return Forall ind_type motive
fn try_delim_conclude(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
    cases: &Term,
) -> Option<Term> {
    // Normalize inputs
    let norm_ind_type = normalize(ctx, ind_type);
    let norm_motive = normalize(ctx, motive);
    let norm_cases = normalize(ctx, cases);

    // 1. Extract inductive name from Syntax
    let ind_name = match extract_inductive_name_from_syntax(&norm_ind_type) {
        Some(name) => name,
        None => return Some(make_sname_error()),
    };

    // 2. Look up constructors for this inductive
    let constructors = ctx.get_constructors(&ind_name);
    if constructors.is_empty() {
        // Unknown inductive type
        return Some(make_sname_error());
    }

    // 3. Extract case proofs from DCase chain
    let case_proofs = match extract_case_proofs(&norm_cases) {
        Some(proofs) => proofs,
        None => return Some(make_sname_error()),
    };

    // 4. Verify case count matches constructor count
    if case_proofs.len() != constructors.len() {
        return Some(make_sname_error());
    }

    // 5. Extract motive body (should be SLam param_type body)
    let motive_body = match extract_slam_body(&norm_motive) {
        Some(body) => body,
        None => return Some(make_sname_error()),
    };

    // 6. For each constructor, verify case conclusion matches expected
    for (i, (ctor_name, _ctor_type)) in constructors.iter().enumerate() {
        let case_proof = &case_proofs[i];

        // Get actual conclusion of this case proof
        let case_conc = match try_concludes_reduce(ctx, case_proof) {
            Some(c) => c,
            None => return Some(make_sname_error()),
        };

        // Build expected conclusion based on constructor
        // For base case (0-ary constructor): motive[ctor/var]
        // For step case (recursive constructor): requires IH pattern
        let expected = match build_case_expected(ctx, ctor_name, &constructors, &motive_body, &norm_ind_type) {
            Some(e) => e,
            None => return Some(make_sname_error()),
        };

        // Verify conclusion matches expected
        if !syntax_equal(&case_conc, &expected) {
            return Some(make_sname_error());
        }
    }

    // 7. Return conclusion: Forall ind_type motive
    Some(make_forall_syntax_generic(&norm_ind_type, &norm_motive))
}

/// Extract inductive name from Syntax term.
///
/// Handles:
/// - SName "Nat" → "Nat"
/// - SApp (SName "List") A → "List"
fn extract_inductive_name_from_syntax(term: &Term) -> Option<String> {
    // Case 1: SName "X"
    if let Term::App(sname, text) = term {
        if let Term::Global(ctor) = sname.as_ref() {
            if ctor == "SName" {
                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
                    return Some(name.clone());
                }
            }
        }
    }

    // Case 2: SApp (SName "X") args → extract "X" from the function position
    if let Term::App(inner, _arg) = term {
        if let Term::App(sapp, func) = inner.as_ref() {
            if let Term::Global(ctor) = sapp.as_ref() {
                if ctor == "SApp" {
                    // Recursively extract from the function
                    return extract_inductive_name_from_syntax(func);
                }
            }
        }
    }

    None
}

/// Extract case proofs from DCase chain.
///
/// DCase p1 (DCase p2 DCaseEnd) → [p1, p2]
fn extract_case_proofs(term: &Term) -> Option<Vec<Term>> {
    let mut proofs = Vec::new();
    let mut current = term;

    loop {
        // DCaseEnd - end of list
        if let Term::Global(name) = current {
            if name == "DCaseEnd" {
                return Some(proofs);
            }
        }

        // DCase head tail - Pattern: App(App(DCase, head), tail)
        if let Term::App(inner, tail) = current {
            if let Term::App(dcase, head) = inner.as_ref() {
                if let Term::Global(name) = dcase.as_ref() {
                    if name == "DCase" {
                        proofs.push(head.as_ref().clone());
                        current = tail.as_ref();
                        continue;
                    }
                }
            }
        }

        // Unrecognized structure
        return None;
    }
}

/// Build expected case conclusion for a constructor.
///
/// For base case constructors (no recursive args): motive[ctor/var]
/// For recursive constructors: ∀args. IH → motive[ctor args/var]
fn build_case_expected(
    ctx: &Context,
    ctor_name: &str,
    _constructors: &[(&str, &Term)],
    motive_body: &Term,
    ind_type: &Term,
) -> Option<Term> {
    // Extract inductive name to determine constructor patterns
    let ind_name = extract_inductive_name_from_syntax(ind_type)?;

    // Special case for Nat - we know its structure
    if ind_name == "Nat" {
        if ctor_name == "Zero" {
            // Base case: motive[Zero/var]
            let zero = make_sname("Zero");
            return try_syn_subst_reduce(ctx, &zero, 0, motive_body);
        } else if ctor_name == "Succ" {
            // Step case: ∀k:Nat. P(k) → P(Succ k)
            // Use the same logic as DInduction
            return build_induction_step_formula(ctx, motive_body);
        }
    }

    // For other inductives, use heuristic based on constructor type
    // Build the constructor as Syntax: SName "CtorName"
    let ctor_syntax = make_sname(ctor_name);

    // For polymorphic types, we need to apply the type argument to the constructor
    // e.g., for List A, Nil becomes (SApp (SName "Nil") A)
    let ctor_applied = apply_type_args_to_ctor(&ctor_syntax, ind_type);

    // Get constructor type from context to determine if it's recursive
    if let Some(ctor_ty) = ctx.get_global(ctor_name) {
        // Check if constructor type contains the inductive type (recursive)
        if is_recursive_constructor(ctx, ctor_ty, &ind_name, ind_type) {
            // For recursive constructors, build the IH pattern
            return build_recursive_case_formula(ctx, ctor_name, ctor_ty, motive_body, ind_type, &ind_name);
        }
    }

    // Simple base case: substitute ctor into motive body
    try_syn_subst_reduce(ctx, &ctor_applied, 0, motive_body)
}

/// Apply type arguments from ind_type to a constructor.
///
/// If ind_type = SApp (SName "List") A, and ctor = SName "Nil",
/// result = SApp (SName "Nil") A
fn apply_type_args_to_ctor(ctor: &Term, ind_type: &Term) -> Term {
    // Extract type arguments from ind_type
    let args = extract_type_args(ind_type);

    if args.is_empty() {
        return ctor.clone();
    }

    // Apply each arg: SApp (... (SApp ctor arg1) ...) argN
    args.iter().fold(ctor.clone(), |acc, arg| {
        Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SApp".to_string())),
                Box::new(acc),
            )),
            Box::new(arg.clone()),
        )
    })
}

/// Extract type arguments from polymorphic Syntax.
///
/// SApp (SApp (SName "Either") A) B → [A, B]
/// SApp (SName "List") A → [A]
/// SName "Nat" → []
fn extract_type_args(term: &Term) -> Vec<Term> {
    let mut args = Vec::new();
    let mut current = term;

    // Traverse SApp chain from outside in
    loop {
        if let Term::App(inner, arg) = current {
            if let Term::App(sapp, func) = inner.as_ref() {
                if let Term::Global(ctor) = sapp.as_ref() {
                    if ctor == "SApp" {
                        args.push(arg.as_ref().clone());
                        current = func.as_ref();
                        continue;
                    }
                }
            }
        }
        break;
    }

    // Reverse because we collected outside-in but want inside-out
    args.reverse();
    args
}

/// Build Forall Syntax for generic inductive type.
///
/// Forall ind_type motive = SApp (SApp (SName "Forall") ind_type) motive
fn make_forall_syntax_generic(ind_type: &Term, motive: &Term) -> Term {
    // SApp (SName "Forall") ind_type
    let forall_type = Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(make_sname("Forall")),
        )),
        Box::new(ind_type.clone()),
    );

    // SApp forall_type motive
    Term::App(
        Box::new(Term::App(
            Box::new(Term::Global("SApp".to_string())),
            Box::new(forall_type),
        )),
        Box::new(motive.clone()),
    )
}

/// Check if a constructor is recursive (has arguments of the inductive type).
fn is_recursive_constructor(
    _ctx: &Context,
    ctor_ty: &Term,
    ind_name: &str,
    _ind_type: &Term,
) -> bool {
    // Traverse the constructor type looking for the inductive type in argument positions
    // For Cons : Π(A:Type). A -> List A -> List A
    // The "List A" argument makes it recursive

    fn contains_inductive(term: &Term, ind_name: &str) -> bool {
        match term {
            Term::Global(name) => name == ind_name,
            Term::App(f, a) => {
                contains_inductive(f, ind_name) || contains_inductive(a, ind_name)
            }
            Term::Pi { param_type, body_type, .. } => {
                contains_inductive(param_type, ind_name) || contains_inductive(body_type, ind_name)
            }
            Term::Lambda { param_type, body, .. } => {
                contains_inductive(param_type, ind_name) || contains_inductive(body, ind_name)
            }
            _ => false,
        }
    }

    // Check if any parameter type (not the final result) contains the inductive
    fn check_params(term: &Term, ind_name: &str) -> bool {
        match term {
            Term::Pi { param_type, body_type, .. } => {
                // Check if this parameter has the inductive type
                if contains_inductive(param_type, ind_name) {
                    return true;
                }
                // Check remaining parameters
                check_params(body_type, ind_name)
            }
            _ => false,
        }
    }

    check_params(ctor_ty, ind_name)
}

/// Build the case formula for a recursive constructor.
///
/// For Cons : Π(A:Type). A -> List A -> List A
/// with motive P : List A -> Prop
/// Expected case: ∀x:A. ∀xs:List A. P(xs) -> P(Cons A x xs)
fn build_recursive_case_formula(
    ctx: &Context,
    ctor_name: &str,
    ctor_ty: &Term,
    motive_body: &Term,
    ind_type: &Term,
    ind_name: &str,
) -> Option<Term> {
    // Extract type args from ind_type for matching
    let type_args = extract_type_args(ind_type);

    // Collect constructor arguments (skipping type parameters)
    let args = collect_ctor_args(ctor_ty, ind_name, &type_args);

    if args.is_empty() {
        // No non-type arguments, treat as base case
        let ctor_applied = apply_type_args_to_ctor(&make_sname(ctor_name), ind_type);
        return try_syn_subst_reduce(ctx, &ctor_applied, 0, motive_body);
    }

    // Build from inside out:
    // 1. Build ctor application: Cons A x xs (with de Bruijn indices for args)
    // 2. Build P(ctor args): motive_body[ctor args/var]
    // 3. For each recursive arg, wrap with IH: P(xs) ->
    // 4. For each arg, wrap with forall: ∀xs:List A.

    // Build constructor application with de Bruijn indices
    let mut ctor_app = apply_type_args_to_ctor(&make_sname(ctor_name), ind_type);
    for (i, _) in args.iter().enumerate() {
        // Index from end: last arg is index 0, second-to-last is 1, etc.
        let idx = (args.len() - 1 - i) as i64;
        let var = Term::App(
            Box::new(Term::Global("SVar".to_string())),
            Box::new(Term::Lit(Literal::Int(idx))),
        );
        ctor_app = Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SApp".to_string())),
                Box::new(ctor_app),
            )),
            Box::new(var),
        );
    }

    // P(ctor args) - substitute ctor_app into motive
    let p_ctor = try_syn_subst_reduce(ctx, &ctor_app, 0, motive_body)?;

    // Build implications from inside out (for recursive args)
    let mut body = p_ctor;
    for (i, (arg_ty, is_recursive)) in args.iter().enumerate().rev() {
        if *is_recursive {
            // Add IH: P(arg) -> body
            // arg is at index (args.len() - 1 - i)
            let idx = (args.len() - 1 - i) as i64;
            let var = Term::App(
                Box::new(Term::Global("SVar".to_string())),
                Box::new(Term::Lit(Literal::Int(idx))),
            );
            let p_arg = try_syn_subst_reduce(ctx, &var, 0, motive_body)?;
            body = make_implies_syntax(&p_arg, &body);
        }
        // Skip non-recursive args in the implication chain
        let _ = (i, arg_ty); // suppress unused warning
    }

    // Wrap with foralls from inside out
    for (arg_ty, _) in args.iter().rev() {
        // SLam arg_ty body
        let slam = Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("SLam".to_string())),
                Box::new(arg_ty.clone()),
            )),
            Box::new(body.clone()),
        );
        // Forall arg_ty slam
        body = make_forall_syntax_with_type(arg_ty, &slam);
    }

    Some(body)
}

/// Collect constructor arguments, skipping type parameters.
/// Returns (arg_type, is_recursive) pairs.
fn collect_ctor_args(ctor_ty: &Term, ind_name: &str, type_args: &[Term]) -> Vec<(Term, bool)> {
    let mut args = Vec::new();
    let mut current = ctor_ty;
    let mut skip_count = type_args.len();

    loop {
        match current {
            Term::Pi { param_type, body_type, .. } => {
                if skip_count > 0 {
                    // Skip type parameter
                    skip_count -= 1;
                } else {
                    // Regular argument
                    let is_recursive = contains_inductive_term(param_type, ind_name);
                    // Convert kernel type to Syntax representation
                    let arg_ty_syntax = kernel_type_to_syntax(param_type);
                    args.push((arg_ty_syntax, is_recursive));
                }
                current = body_type;
            }
            _ => break,
        }
    }

    args
}

/// Check if a kernel Term contains the inductive type.
fn contains_inductive_term(term: &Term, ind_name: &str) -> bool {
    match term {
        Term::Global(name) => name == ind_name,
        Term::App(f, a) => {
            contains_inductive_term(f, ind_name) || contains_inductive_term(a, ind_name)
        }
        Term::Pi { param_type, body_type, .. } => {
            contains_inductive_term(param_type, ind_name) || contains_inductive_term(body_type, ind_name)
        }
        Term::Lambda { param_type, body, .. } => {
            contains_inductive_term(param_type, ind_name) || contains_inductive_term(body, ind_name)
        }
        _ => false,
    }
}

/// Convert a kernel Term (type) to its Syntax representation.
fn kernel_type_to_syntax(term: &Term) -> Term {
    match term {
        Term::Global(name) => make_sname(name),
        Term::Var(name) => make_sname(name), // Named variable
        Term::App(f, a) => {
            let f_syn = kernel_type_to_syntax(f);
            let a_syn = kernel_type_to_syntax(a);
            // SApp f_syn a_syn
            Term::App(
                Box::new(Term::App(
                    Box::new(Term::Global("SApp".to_string())),
                    Box::new(f_syn),
                )),
                Box::new(a_syn),
            )
        }
        Term::Pi { param, param_type, body_type } => {
            let pt_syn = kernel_type_to_syntax(param_type);
            let bt_syn = kernel_type_to_syntax(body_type);
            // SPi pt_syn bt_syn
            Term::App(
                Box::new(Term::App(
                    Box::new(Term::Global("SPi".to_string())),
                    Box::new(pt_syn),
                )),
                Box::new(bt_syn),
            )
        }
        Term::Sort(univ) => {
            // SSort univ
            Term::App(
                Box::new(Term::Global("SSort".to_string())),
                Box::new(univ_to_syntax(univ)),
            )
        }
        Term::Lit(lit) => {
            // SLit lit
            Term::App(
                Box::new(Term::Global("SLit".to_string())),
                Box::new(Term::Lit(lit.clone())),
            )
        }
        _ => {
            // Fallback for complex terms
            make_sname("Unknown")
        }
    }
}

/// Convert a Universe to Syntax.
fn univ_to_syntax(univ: &crate::term::Universe) -> Term {
    match univ {
        crate::term::Universe::Prop => Term::Global("UProp".to_string()),
        crate::term::Universe::Type(n) => Term::App(
            Box::new(Term::Global("UType".to_string())),
            Box::new(Term::Lit(Literal::Int(*n as i64))),
        ),
    }
}

// -------------------------------------------------------------------------
// Inversion Tactic
// -------------------------------------------------------------------------

/// Inversion tactic: analyze hypothesis to derive False if no constructor matches.
///
/// Given hypothesis H of form `SApp (SName "IndName") args`, check if any constructor
/// of IndName can produce those args. If no constructor can match, return DInversion H.
fn try_try_inversion_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
    // Extract inductive name and arguments from the hypothesis type
    let (ind_name, hyp_args) = match extract_applied_inductive_from_syntax(goal) {
        Some((name, args)) => (name, args),
        None => return Some(make_error_derivation()),
    };

    // Check if the inductive type actually exists
    if !ctx.is_inductive(&ind_name) {
        // Unknown inductive type - cannot derive anything
        return Some(make_error_derivation());
    }

    // Get constructors for this inductive
    let constructors = ctx.get_constructors(&ind_name);

    // Check each constructor to see if it can match
    let mut any_possible = false;
    for (_ctor_name, ctor_type) in constructors.iter() {
        if can_constructor_match_args(ctx, ctor_type, &hyp_args, &ind_name) {
            any_possible = true;
            break;
        }
    }

    if any_possible {
        // Cannot derive False - some constructor could match
        return Some(make_error_derivation());
    }

    // All constructors impossible → build DInversion
    Some(Term::App(
        Box::new(Term::Global("DInversion".to_string())),
        Box::new(goal.clone()),
    ))
}

/// Verify DInversion proof: check that no constructor can match the hypothesis.
fn try_dinversion_conclude(ctx: &Context, hyp_type: &Term) -> Option<Term> {
    let norm_hyp = normalize(ctx, hyp_type);

    let (ind_name, hyp_args) = match extract_applied_inductive_from_syntax(&norm_hyp) {
        Some((name, args)) => (name, args),
        None => return Some(make_sname_error()),
    };

    // Check if the inductive type actually exists
    if !ctx.is_inductive(&ind_name) {
        return Some(make_sname_error());
    }

    let constructors = ctx.get_constructors(&ind_name);

    // Verify ALL constructors are impossible
    for (_ctor_name, ctor_type) in constructors.iter() {
        if can_constructor_match_args(ctx, ctor_type, &hyp_args, &ind_name) {
            return Some(make_sname_error());
        }
    }

    // All impossible → concludes False
    Some(make_sname("False"))
}

/// Extract inductive name and arguments from Syntax.
///
/// SApp (SApp (SName "Even") x) y → ("Even", [x, y])
/// SName "False" → ("False", [])
fn extract_applied_inductive_from_syntax(term: &Term) -> Option<(String, Vec<Term>)> {
    // Base case: SName "X"
    if let Term::App(ctor, text) = term {
        if let Term::Global(ctor_name) = ctor.as_ref() {
            if ctor_name == "SName" {
                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
                    return Some((name.clone(), vec![]));
                }
            }
        }
    }

    // Recursive case: SApp f x
    if let Term::App(inner, arg) = term {
        if let Term::App(sapp_ctor, func) = inner.as_ref() {
            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
                if ctor_name == "SApp" {
                    // Recursively extract from the function
                    let (name, mut args) = extract_applied_inductive_from_syntax(func)?;
                    args.push(arg.as_ref().clone());
                    return Some((name, args));
                }
            }
        }
    }

    None
}

/// Check if a constructor can possibly match the given arguments.
///
/// For constructor `even_succ : ∀n. Even n → Even (Succ (Succ n))`:
/// - The constructor's result pattern is `Even (Succ (Succ n))`
/// - If hyp_args is `[Succ (Succ (Succ Zero))]` (representing 3):
///   - Unify `Succ (Succ n)` with `Succ (Succ (Succ Zero))`
///   - This succeeds with n = Succ Zero = 1
///   - But then we need to check if `Even 1` is constructible (recursive)
fn can_constructor_match_args(
    ctx: &Context,
    ctor_type: &Term,
    hyp_args: &[Term],
    ind_name: &str,
) -> bool {
    // Decompose constructor type to get result pattern and bound variable names
    let (result, pattern_vars) = decompose_ctor_type_with_vars(ctor_type);

    // Extract result's arguments (what the constructor produces)
    let result_args = match extract_applied_inductive_from_syntax(&kernel_type_to_syntax(&result)) {
        Some((name, args)) if name == *ind_name => args,
        _ => return false,
    };

    // If argument counts don't match, can't unify
    if result_args.len() != hyp_args.len() {
        return false;
    }

    // Try syntactic unification of all arguments together (tracking bindings across args)
    let mut bindings: std::collections::HashMap<String, Term> = std::collections::HashMap::new();

    for (pattern, concrete) in result_args.iter().zip(hyp_args.iter()) {
        if !can_unify_syntax_terms_with_bindings(ctx, pattern, concrete, &pattern_vars, &mut bindings) {
            return false;
        }
    }

    // If we get here, the constructor could match
    // (We don't check recursive hypotheses for simplicity - that would require
    // full inversion with backtracking)
    true
}

/// Decompose a constructor type to get the result type and bound variable names.
///
/// `∀n:Nat. Even n → Even (Succ (Succ n))` → (`Even (Succ (Succ n))`, ["n"])
/// `∀A:Type. ∀x:A. Eq A x x` → (`Eq A x x`, ["A", "x"])
/// `Bool` → (`Bool`, [])
fn decompose_ctor_type_with_vars(ty: &Term) -> (Term, Vec<String>) {
    let mut vars = Vec::new();
    let mut current = ty;
    loop {
        match current {
            Term::Pi { param, body_type, .. } => {
                vars.push(param.clone());
                current = body_type;
            }
            _ => break,
        }
    }
    (current.clone(), vars)
}

/// Check if two Syntax terms can unify, tracking variable bindings.
///
/// Pattern variables (names in `pattern_vars`) can bind to any concrete value,
/// but must bind consistently (same variable must bind to same value).
/// Other SNames must match exactly.
/// SApp recurses on function and argument.
fn can_unify_syntax_terms_with_bindings(
    ctx: &Context,
    pattern: &Term,
    concrete: &Term,
    pattern_vars: &[String],
    bindings: &mut std::collections::HashMap<String, Term>,
) -> bool {
    // SVar can match anything (explicit unification variable)
    if let Term::App(ctor, _idx) = pattern {
        if let Term::Global(name) = ctor.as_ref() {
            if name == "SVar" {
                return true;
            }
        }
    }

    // SName: check if it's a pattern variable or a constant
    if let Term::App(ctor1, text1) = pattern {
        if let Term::Global(n1) = ctor1.as_ref() {
            if n1 == "SName" {
                if let Term::Lit(Literal::Text(var_name)) = text1.as_ref() {
                    // Check if this is a pattern variable
                    if pattern_vars.contains(var_name) {
                        // Pattern variable: check existing binding or create new one
                        if let Some(existing) = bindings.get(var_name) {
                            // Already bound: concrete must match existing binding
                            return syntax_terms_equal(existing, concrete);
                        } else {
                            // Not yet bound: bind to concrete value
                            bindings.insert(var_name.clone(), concrete.clone());
                            return true;
                        }
                    }
                }
                // Not a pattern variable: must match exactly
                if let Term::App(ctor2, text2) = concrete {
                    if let Term::Global(n2) = ctor2.as_ref() {
                        if n2 == "SName" {
                            return text1 == text2;
                        }
                    }
                }
                return false;
            }
        }
    }

    // SApp: recurse on both function and argument
    if let (Term::App(inner1, arg1), Term::App(inner2, arg2)) = (pattern, concrete) {
        if let (Term::App(sapp1, func1), Term::App(sapp2, func2)) =
            (inner1.as_ref(), inner2.as_ref())
        {
            if let (Term::Global(n1), Term::Global(n2)) = (sapp1.as_ref(), sapp2.as_ref()) {
                if n1 == "SApp" && n2 == "SApp" {
                    return can_unify_syntax_terms_with_bindings(ctx, func1, func2, pattern_vars, bindings)
                        && can_unify_syntax_terms_with_bindings(ctx, arg1.as_ref(), arg2.as_ref(), pattern_vars, bindings);
                }
            }
        }
    }

    // SLit: compare literal values
    if let (Term::App(ctor1, lit1), Term::App(ctor2, lit2)) = (pattern, concrete) {
        if let (Term::Global(n1), Term::Global(n2)) = (ctor1.as_ref(), ctor2.as_ref()) {
            if n1 == "SLit" && n2 == "SLit" {
                return lit1 == lit2;
            }
        }
    }

    // Fall back to exact structural equality
    pattern == concrete
}

/// Check if two Syntax terms are structurally equal.
fn syntax_terms_equal(a: &Term, b: &Term) -> bool {
    match (a, b) {
        (Term::App(f1, x1), Term::App(f2, x2)) => {
            syntax_terms_equal(f1, f2) && syntax_terms_equal(x1, x2)
        }
        (Term::Global(n1), Term::Global(n2)) => n1 == n2,
        (Term::Lit(l1), Term::Lit(l2)) => l1 == l2,
        _ => a == b,
    }
}

// -------------------------------------------------------------------------
// Operator Tactics (rewrite, destruct, apply)
// -------------------------------------------------------------------------

/// Extract Eq A x y components from a Syntax term.
///
/// SApp (SApp (SApp (SName "Eq") A) x) y → Some((A, x, y))
fn extract_eq_components_from_syntax(term: &Term) -> Option<(Term, Term, Term)> {
    // term = SApp (SApp (SApp (SName "Eq") A) x) y
    // In kernel representation: App(App(SApp, App(App(SApp, App(App(SApp, SName "Eq"), A)), x)), y)

    // Peel off outermost SApp to get ((SApp (SApp (SName "Eq") A) x), y)
    let (eq_a_x, y) = extract_sapp(term)?;

    // Peel off next SApp to get ((SApp (SName "Eq") A), x)
    let (eq_a, x) = extract_sapp(&eq_a_x)?;

    // Peel off next SApp to get ((SName "Eq"), A)
    let (eq, a) = extract_sapp(&eq_a)?;

    // Verify it's SName "Eq"
    let eq_name = extract_sname(&eq)?;
    if eq_name != "Eq" {
        return None;
    }

    Some((a, x, y))
}

/// Extract (f, x) from SApp f x (in kernel representation).
fn extract_sapp(term: &Term) -> Option<(Term, Term)> {
    // SApp f x = App(App(Global("SApp"), f), x)
    if let Term::App(inner, x) = term {
        if let Term::App(sapp_ctor, f) = inner.as_ref() {
            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
                if ctor_name == "SApp" {
                    return Some((f.as_ref().clone(), x.as_ref().clone()));
                }
            }
        }
    }
    None
}

/// Extract name from SName "name".
fn extract_sname(term: &Term) -> Option<String> {
    if let Term::App(ctor, text) = term {
        if let Term::Global(ctor_name) = ctor.as_ref() {
            if ctor_name == "SName" {
                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
                    return Some(name.clone());
                }
            }
        }
    }
    None
}

/// Check if a Syntax term contains a specific subterm.
fn contains_subterm_syntax(term: &Term, target: &Term) -> bool {
    if syntax_equal(term, target) {
        return true;
    }

    // Check SApp f x
    if let Some((f, x)) = extract_sapp(term) {
        if contains_subterm_syntax(&f, target) || contains_subterm_syntax(&x, target) {
            return true;
        }
    }

    // Check SLam T body
    if let Some((t, body)) = extract_slam(term) {
        if contains_subterm_syntax(&t, target) || contains_subterm_syntax(&body, target) {
            return true;
        }
    }

    // Check SPi T body
    if let Some((t, body)) = extract_spi(term) {
        if contains_subterm_syntax(&t, target) || contains_subterm_syntax(&body, target) {
            return true;
        }
    }

    false
}

/// Extract (T, body) from SLam T body.
fn extract_slam(term: &Term) -> Option<(Term, Term)> {
    if let Term::App(inner, body) = term {
        if let Term::App(slam_ctor, t) = inner.as_ref() {
            if let Term::Global(ctor_name) = slam_ctor.as_ref() {
                if ctor_name == "SLam" {
                    return Some((t.as_ref().clone(), body.as_ref().clone()));
                }
            }
        }
    }
    None
}

/// Extract (T, body) from SPi T body.
fn extract_spi(term: &Term) -> Option<(Term, Term)> {
    if let Term::App(inner, body) = term {
        if let Term::App(spi_ctor, t) = inner.as_ref() {
            if let Term::Global(ctor_name) = spi_ctor.as_ref() {
                if ctor_name == "SPi" {
                    return Some((t.as_ref().clone(), body.as_ref().clone()));
                }
            }
        }
    }
    None
}

/// Replace first occurrence of target with replacement in a Syntax term.
fn replace_first_subterm_syntax(term: &Term, target: &Term, replacement: &Term) -> Option<Term> {
    // If term equals target, return replacement
    if syntax_equal(term, target) {
        return Some(replacement.clone());
    }

    // Try to replace in SApp f x
    if let Some((f, x)) = extract_sapp(term) {
        // First try to replace in f
        if let Some(new_f) = replace_first_subterm_syntax(&f, target, replacement) {
            return Some(make_sapp(new_f, x));
        }
        // Then try to replace in x
        if let Some(new_x) = replace_first_subterm_syntax(&x, target, replacement) {
            return Some(make_sapp(f, new_x));
        }
    }

    // Try to replace in SLam T body
    if let Some((t, body)) = extract_slam(term) {
        if let Some(new_t) = replace_first_subterm_syntax(&t, target, replacement) {
            return Some(make_slam(new_t, body));
        }
        if let Some(new_body) = replace_first_subterm_syntax(&body, target, replacement) {
            return Some(make_slam(t, new_body));
        }
    }

    // Try to replace in SPi T body
    if let Some((t, body)) = extract_spi(term) {
        if let Some(new_t) = replace_first_subterm_syntax(&t, target, replacement) {
            return Some(make_spi(new_t, body));
        }
        if let Some(new_body) = replace_first_subterm_syntax(&body, target, replacement) {
            return Some(make_spi(t, new_body));
        }
    }

    // No replacement found
    None
}

/// Rewrite tactic: given eq_proof (concluding Eq A x y) and goal,
/// replaces x with y (or y with x if reverse=true) in goal.
fn try_try_rewrite_reduce(
    ctx: &Context,
    eq_proof: &Term,
    goal: &Term,
    reverse: bool,
) -> Option<Term> {
    // Get the conclusion of eq_proof
    let eq_conclusion = try_concludes_reduce(ctx, eq_proof)?;

    // Extract Eq A x y components
    let (ty, lhs, rhs) = match extract_eq_components_from_syntax(&eq_conclusion) {
        Some(components) => components,
        None => return Some(make_error_derivation()),
    };

    // Determine what to replace based on direction
    let (target, replacement) = if reverse { (rhs, lhs) } else { (lhs, rhs) };

    // Check if target exists in goal
    if !contains_subterm_syntax(goal, &target) {
        return Some(make_error_derivation());
    }

    // Replace target with replacement in goal
    let new_goal = match replace_first_subterm_syntax(goal, &target, &replacement) {
        Some(ng) => ng,
        None => return Some(make_error_derivation()),
    };

    // Build DRewrite eq_proof goal new_goal
    Some(Term::App(
        Box::new(Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("DRewrite".to_string())),
                Box::new(eq_proof.clone()),
            )),
            Box::new(goal.clone()),
        )),
        Box::new(new_goal),
    ))
}

/// Verify DRewrite derivation and return the new goal.
fn try_drewrite_conclude(
    ctx: &Context,
    eq_proof: &Term,
    old_goal: &Term,
    new_goal: &Term,
) -> Option<Term> {
    // Get the conclusion of eq_proof
    let eq_conclusion = try_concludes_reduce(ctx, eq_proof)?;

    // Extract Eq A x y components
    let (_ty, lhs, rhs) = match extract_eq_components_from_syntax(&eq_conclusion) {
        Some(components) => components,
        None => return Some(make_sname_error()),
    };

    // Verify: new_goal = old_goal[lhs := rhs] OR new_goal = old_goal[rhs := lhs]
    // Check forward direction first
    if let Some(computed_new) = replace_first_subterm_syntax(old_goal, &lhs, &rhs) {
        if syntax_equal(&computed_new, new_goal) {
            return Some(new_goal.clone());
        }
    }

    // Check reverse direction
    if let Some(computed_new) = replace_first_subterm_syntax(old_goal, &rhs, &lhs) {
        if syntax_equal(&computed_new, new_goal) {
            return Some(new_goal.clone());
        }
    }

    // Verification failed
    Some(make_sname_error())
}

/// Destruct tactic: case analysis without induction hypotheses.
fn try_try_destruct_reduce(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
    cases: &Term,
) -> Option<Term> {
    // For now, destruct is essentially the same as induction
    // The key difference is in what goals are expected for each case
    // (no IH for recursive constructors)
    //
    // We simply build a DDestruct and let verification check case proofs

    Some(Term::App(
        Box::new(Term::App(
            Box::new(Term::App(
                Box::new(Term::Global("DDestruct".to_string())),
                Box::new(ind_type.clone()),
            )),
            Box::new(motive.clone()),
        )),
        Box::new(cases.clone()),
    ))
}

/// Verify DDestruct derivation.
fn try_ddestruct_conclude(
    ctx: &Context,
    ind_type: &Term,
    motive: &Term,
    cases: &Term,
) -> Option<Term> {
    // Similar to DElim but without verifying IH in step cases
    // For now, we accept the derivation and return Forall ind_type motive

    // Extract the inductive type name
    let ind_name = extract_inductive_name_from_syntax(ind_type)?;

    // Verify it's actually an inductive type
    if !ctx.is_inductive(&ind_name) {
        return Some(make_sname_error());
    }

    let constructors = ctx.get_constructors(&ind_name);

    // Extract case proofs
    let case_proofs = match extract_case_proofs(cases) {
        Some(proofs) => proofs,
        None => return Some(make_sname_error()),
    };

    // Verify case count matches
    if case_proofs.len() != constructors.len() {
        return Some(make_sname_error());
    }

    // For each case, verify the conclusion matches the expected goal (without IH)
    // For simplicity, we just check case count matches for now
    // Full verification would check each case proves P(ctor args)

    // Build Forall ind_type motive
    Some(make_forall_syntax_with_type(ind_type, motive))
}

/// Apply tactic: manual backward chaining.
fn try_try_apply_reduce(
    ctx: &Context,
    hyp_name: &Term,
    hyp_proof: &Term,
    goal: &Term,
) -> Option<Term> {
    // Get the conclusion of hyp_proof
    let hyp_conclusion = try_concludes_reduce(ctx, hyp_proof)?;

    // Check if it's an implication: SPi A B where B doesn't use the bound var
    if let Some((antecedent, consequent)) = extract_spi(&hyp_conclusion) {
        // Check if consequent matches goal
        if syntax_equal(&consequent, goal) {
            // Build DApply hyp_name hyp_proof goal antecedent
            return Some(Term::App(
                Box::new(Term::App(
                    Box::new(Term::App(
                        Box::new(Term::App(
                            Box::new(Term::Global("DApply".to_string())),
                            Box::new(hyp_name.clone()),
                        )),
                        Box::new(hyp_proof.clone()),
                    )),
                    Box::new(goal.clone()),
                )),
                Box::new(antecedent),
            ));
        }
    }

    // Check if it's a forall that could match
    if let Some(forall_body) = extract_forall_body(&hyp_conclusion) {
        // Try to match goal with forall body (simple syntactic check)
        // For now, if goal appears to be an instance of the forall body, accept it
        // Full implementation would do proper unification

        // Build DApply with new goal being True (trivially satisfied)
        return Some(Term::App(
            Box::new(Term::App(
                Box::new(Term::App(
                    Box::new(Term::App(
                        Box::new(Term::Global("DApply".to_string())),
                        Box::new(hyp_name.clone()),
                    )),
                    Box::new(hyp_proof.clone()),
                )),
                Box::new(goal.clone()),
            )),
            Box::new(make_sname("True")),
        ));
    }

    // If hypothesis directly matches goal, we're done
    if syntax_equal(&hyp_conclusion, goal) {
        return Some(Term::App(
            Box::new(Term::App(
                Box::new(Term::App(
                    Box::new(Term::App(
                        Box::new(Term::Global("DApply".to_string())),
                        Box::new(hyp_name.clone()),
                    )),
                    Box::new(hyp_proof.clone()),
                )),
                Box::new(goal.clone()),
            )),
            Box::new(make_sname("True")),
        ));
    }

    // Cannot apply this hypothesis to this goal
    Some(make_error_derivation())
}

/// Verify DApply derivation.
fn try_dapply_conclude(
    ctx: &Context,
    hyp_name: &Term,
    hyp_proof: &Term,
    old_goal: &Term,
    new_goal: &Term,
) -> Option<Term> {
    // Get the conclusion of hyp_proof
    let hyp_conclusion = try_concludes_reduce(ctx, hyp_proof)?;

    // If hypothesis is an implication A -> B and old_goal is B
    // then new_goal should be A
    if let Some((antecedent, consequent)) = extract_spi(&hyp_conclusion) {
        if syntax_equal(&consequent, old_goal) {
            if syntax_equal(&antecedent, new_goal) || extract_sname(new_goal) == Some("True".to_string()) {
                return Some(new_goal.clone());
            }
        }
    }

    // If hypothesis is a forall and goal matches instantiation
    if let Some(_forall_body) = extract_forall_body(&hyp_conclusion) {
        // For forall application, the new goal is typically True or the instantiated body
        if extract_sname(new_goal) == Some("True".to_string()) {
            return Some(new_goal.clone());
        }
    }

    // If hypothesis directly matches old_goal
    if syntax_equal(&hyp_conclusion, old_goal) {
        if extract_sname(new_goal) == Some("True".to_string()) {
            return Some(new_goal.clone());
        }
    }

    // Verification failed
    Some(make_sname_error())
}