llvm-native-core 0.1.11

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
//! clang_projects_deep_x86 — Deep project compilation support for major
//! open-source C/C++ projects on X86 targets with full build orchestration,
//! testing, and optimization infrastructure.
//!
//! ## Overview
//!
//! This module provides comprehensive build configurations, dependency resolution,
//! compilation orchestration, testing, and performance optimization for 15+ major
//! open-source projects compiled with Clang on X86 architecture. It handles the
//! full lifecycle: configure → build → test → optimize.
//!
//! ## Supported Projects
//!
//! | Project         | Build System    | Key Features                        |
//! |-----------------|-----------------|-------------------------------------|
//! | LLVM/Clang      | CMake           | Bootstrap, stage1/stage2, LTO       |
//! | Linux Kernel    | Kbuild/Make     | Kconfig, x86_64/i386, bzImage       |
//! | Qt              | CMake/qmake     | Widget, GUI, platform plugins       |
//! | Boost           | b2              | Library selection, address-model    |
//! | FFmpeg          | configure/Make  | Codecs, SIMD (MMX/SSE/AVX)          |
//! | OpenCV          | CMake           | SIMD, CUDA, OpenCL interop          |
//! | TensorFlow Lite | CMake           | XNNPACK, NEON→SSE mapping           |
//! | Protobuf        | CMake           | Proto compiler, well-known types    |
//! | gRPC            | CMake           | Protobuf plugin, SSL/TLS backends   |
//! | Abseil          | CMake           | C++17, core libraries               |
//! | LevelDB         | CMake           | Snappy compression                  |
//! | RocksDB         | CMake           | Compression, SIMD CRC               |
//! | DuckDB          | CMake           | Vectorized execution engine         |
//! | ClickHouse      | CMake           | SIMD hash tables, compression       |
//! | ScyllaDB/Seastar| CMake           | DPDK, async framework               |
//!
//! ## Components
//!
//! - `X86ProjectsDeep` — Central project registry and configuration manager
//! - `X86ProjectBuild` — Build orchestration, dep ordering, caching, CDB generation
//! - `X86ProjectTest` — Test discovery, execution, regression, benchmarks
//! - `X86ProjectOptimize` — PGO training, LTO, BOLT, FMV/CPU dispatch
//!
//! ## Integration Points
//!
//! - `crate::clang::*` — Clang frontend types, driver, codegen, diagnostics
//! - `crate::clang::clang_real_projects_x86::*` — Real-world project infrastructure
//! - `crate::x86::*` — X86 backend types (target machine, ISA, registers, etc.)
//!
//! Clean-room behavioral reconstruction from published project documentation,
//! build system manuals, and public build scripts. Zero LLVM source code consultation.

use std::collections::{BTreeMap, BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::fs;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::clang::clang_real_projects_x86::{
    self, X86BuildResult, X86BuildSystem, X86CompileDiagnostic, X86DiagLevel, X86ProjectConfig,
    X86RealProjectCompiler, X86TestSuiteResult, DEFAULT_CACHE_DIR, DEFAULT_CACHE_MAX_SIZE,
    DEFAULT_PARALLEL_JOBS, X86_32_LINUX_TRIPLE, X86_64_DARWIN_TRIPLE, X86_64_LINUX_TRIPLE,
    X86_64_WINDOWS_TRIPLE, X86_CPU_FEATURES, X86_MICROARCHS,
};
use crate::clang::clang_x86_pipeline::{
    self, CompilationCache, PipelineResult, X86CompileOptions, X86OptLevel, X86OutputFormat,
    X86Pipeline,
};
use crate::clang::{
    self, compile_c_file, compile_c_string, CLangStandard, ClangCodeGen, ClangDriver, ClangOptions,
    DiagSeverity, DiagnosticBuilder, DiagnosticEngine, DiagnosticOptions,
};
use crate::x86::{
    self, X86CallingConvention, X86FrameInfo, X86FrameLowering, X86InstrInfo, X86IsaFeature,
    X86RegisterInfo, X86Subtarget, X86TargetMachine, X86_64_REG_COUNT, X86_PAGE_SIZE,
    X86_RED_ZONE_SIZE_64, X86_STACK_ALIGNMENT_32, X86_STACK_ALIGNMENT_64,
};

// ═══════════════════════════════════════════════════════════════════════════════
// X86 Deep Project Constants

// ═══════════════════════════════════════════════════════════════════════════════
// Compiler Diagnostic Comparison
// ═══════════════════════════════════════════════════════════════════════════════

/// Utility to compare compiler diagnostic output between two compilers.
pub fn compare_diagnostics(clang_output: &str, gcc_output: &str) -> DiagnosticComparison {
    let clang_errors = count_diagnostic_lines(clang_output, "error:");
    let clang_warnings = count_diagnostic_lines(clang_output, "warning:");
    let gcc_errors = count_diagnostic_lines(gcc_output, "error:");
    let gcc_warnings = count_diagnostic_lines(gcc_output, "warning:");

    DiagnosticComparison {
        clang_errors,
        clang_warnings,
        gcc_errors,
        gcc_warnings,
        clang_unique_warnings: extract_unique_diagnostics(clang_output, gcc_output, "warning:"),
        gcc_unique_warnings: extract_unique_diagnostics(gcc_output, clang_output, "warning:"),
    }
}

fn count_diagnostic_lines(output: &str, prefix: &str) -> usize {
    output.lines().filter(|l| l.contains(prefix)).count()
}

fn extract_unique_diagnostics(a: &str, b: &str, prefix: &str) -> Vec<String> {
    let a_diags: HashSet<String> = a
        .lines()
        .filter(|l| l.contains(prefix))
        .map(|l| l.trim().to_string())
        .collect();
    let b_diags: HashSet<String> = b
        .lines()
        .filter(|l| l.contains(prefix))
        .map(|l| l.trim().to_string())
        .collect();
    a_diags.difference(&b_diags).cloned().collect()
}

/// Result of comparing diagnostics between two compilers.
#[derive(Debug, Clone)]
pub struct DiagnosticComparison {
    pub clang_errors: usize,
    pub clang_warnings: usize,
    pub gcc_errors: usize,
    pub gcc_warnings: usize,
    pub clang_unique_warnings: Vec<String>,
    pub gcc_unique_warnings: Vec<String>,
}

impl DiagnosticComparison {
    pub fn summary(&self) -> String {
        format!(
            "Diagnostic Comparison:
\n             Clang: {} errors, {} warnings
\n             GCC:   {} errors, {} warnings
\n             Clang-unique warnings: {}
\n             GCC-unique warnings: {}",
            self.clang_errors,
            self.clang_warnings,
            self.gcc_errors,
            self.gcc_warnings,
            self.clang_unique_warnings.len(),
            self.gcc_unique_warnings.len(),
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Environment Health Check
// ═══════════════════════════════════════════════════════════════════════════════

/// Results of a build environment health check.
#[derive(Debug, Clone)]
pub struct HealthCheckResult {
    pub all_passed: bool,
    pub checks: Vec<HealthCheckItem>,
    pub timestamp: SystemTime,
}

#[derive(Debug, Clone)]
pub struct HealthCheckItem {
    pub name: String,
    pub passed: bool,
    pub message: String,
    pub severity: HealthCheckSeverity,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HealthCheckSeverity {
    Info,
    Warning,
    Error,
}

/// Runs a comprehensive health check of the build environment.
pub fn check_build_environment() -> HealthCheckResult {
    let mut checks = Vec::new();

    // Check for Clang
    let has_clang = which::which("clang").is_ok();
    checks.push(HealthCheckItem {
        name: "Clang compiler".to_string(),
        passed: has_clang,
        message: if has_clang {
            let version = Command::new("clang")
                .arg("--version")
                .output()
                .ok()
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .and_then(|s| s.lines().next().map(|l| l.to_string()))
                .unwrap_or_else(|| "unknown version".to_string());
            format!("Clang found: {}", version)
        } else {
            "Clang not found in PATH".to_string()
        },
        severity: if has_clang {
            HealthCheckSeverity::Info
        } else {
            HealthCheckSeverity::Error
        },
    });

    // Check for LLD
    let has_lld = which::which("ld.lld")
        .or_else(|_| which::which("lld"))
        .is_ok();
    checks.push(HealthCheckItem {
        name: "LLD linker".to_string(),
        passed: has_lld,
        message: if has_lld {
            "LLD found".to_string()
        } else {
            "LLD not found".to_string()
        },
        severity: if has_lld {
            HealthCheckSeverity::Info
        } else {
            HealthCheckSeverity::Warning
        },
    });

    // Check for CMake
    let has_cmake = which::which("cmake").is_ok();
    checks.push(HealthCheckItem {
        name: "CMake".to_string(),
        passed: has_cmake,
        message: if has_cmake {
            "CMake found".to_string()
        } else {
            "CMake not found".to_string()
        },
        severity: if has_cmake {
            HealthCheckSeverity::Info
        } else {
            HealthCheckSeverity::Error
        },
    });

    // Check for Ninja
    let has_ninja = which::which("ninja").is_ok();
    checks.push(HealthCheckItem {
        name: "Ninja".to_string(),
        passed: has_ninja,
        message: if has_ninja {
            "Ninja found".to_string()
        } else {
            "Ninja not found".to_string()
        },
        severity: if has_ninja {
            HealthCheckSeverity::Info
        } else {
            HealthCheckSeverity::Warning
        },
    });

    // Check disk space
    if let Ok(output) = Command::new("df").arg("-h").arg(".").output() {
        let df = String::from_utf8_lossy(&output.stdout);
        let available = df
            .lines()
            .nth(1)
            .map(|l| {
                let parts: Vec<&str> = l.split_whitespace().collect();
                parts.get(3).map(|s| s.to_string()).unwrap_or_default()
            })
            .unwrap_or_default();
        checks.push(HealthCheckItem {
            name: "Disk space".to_string(),
            passed: true,
            message: format!("Available: {}", available),
            severity: HealthCheckSeverity::Info,
        });
    }

    // Check memory
    let mem_mb = detect_system_memory_mb();
    let mem_ok = mem_mb >= 4096;
    checks.push(HealthCheckItem {
        name: "System memory".to_string(),
        passed: mem_ok,
        message: format!(
            "{} MB available ({} for heavy builds)",
            mem_mb,
            if mem_ok { "sufficient" } else { "insufficient" }
        ),
        severity: if mem_ok {
            HealthCheckSeverity::Info
        } else {
            HealthCheckSeverity::Warning
        },
    });

    let all_passed = checks
        .iter()
        .all(|c| c.passed || c.severity != HealthCheckSeverity::Error);

    HealthCheckResult {
        all_passed,
        checks,
        timestamp: SystemTime::now(),
    }
}

impl HealthCheckResult {
    pub fn print_report(&self) -> String {
        let mut report = String::from(
            "Build Environment Health Check
",
        );
        report.push_str(
            "================================

",
        );
        for check in &self.checks {
            let icon = if check.passed { "[PASS]" } else { "[FAIL]" };
            report.push_str(&format!(
                "{} {}: {}
",
                icon, check.name, check.message
            ));
        }
        report.push_str(&format!(
            "
Overall: {}
",
            if self.all_passed {
                "HEALTHY"
            } else {
                "ISSUES FOUND"
            }
        ));
        report
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Script Template Generation
// ═══════════════════════════════════════════════════════════════════════════════

/// Generates a complete shell build script for a project.
pub fn generate_build_script(config: &DeepProjectConfig, registry: &X86ProjectsDeep) -> String {
    let mut script = String::from(
        "#!/usr/bin/env bash
",
    );
    script.push_str(
        "set -euo pipefail

",
    );
    script.push_str(&format!(
        "# Auto-generated build script for {}
",
        config.name
    ));
    script.push_str(&format!(
        "# Generated by LLVM-native

"
    ));

    script.push_str(
        "export CC=clang
",
    );
    script.push_str(
        "export CXX=clang++
",
    );
    script.push_str(&format!("export CFLAGS=\"{}\"\n", config.cflags.join(" ")));
    script.push_str(&format!(
        "export CXXFLAGS=\"{}\"\n",
        config.cxxflags.join(" ")
    ));
    script.push_str(&format!(
        "export LDFLAGS=\"{}\"\n",
        config.ldflags.join(" ")
    ));
    script.push_str(
        "
",
    );

    let source_dir = registry.project_source_dir(config.id);
    let build_dir = registry.project_build_dir(config.id, config.stage);

    match config.build_system {
        DeepBuildSystem::Cmake => {
            script.push_str(&format!(
                "cmake -G Ninja -S {} -B {}\n
",
                source_dir.display(),
                build_dir.display()
            ));
            for (key, value) in &config.cmake_vars {
                script.push_str(&format!(
                    "  -D{}={} \
",
                    key, value
                ));
            }
            script.push_str(&format!(
                "
ninja -C {} -j16
",
                build_dir.display()
            ));
        }
        DeepBuildSystem::Autotools => {
            script.push_str(&format!(
                "cd {}
",
                source_dir.display()
            ));
            script.push_str("./configure ");
            for flag in &config.configure_flags {
                script.push_str(&format!("{} ", flag));
            }
            script.push_str(
                "
",
            );
            script.push_str(
                "make -j16
",
            );
        }
        DeepBuildSystem::Kbuild => {
            script.push_str(&format!(
                "cd {}
",
                source_dir.display()
            ));
            script.push_str(
                "make defconfig ARCH=x86_64
",
            );
            script.push_str(
                "make -j16 bzImage modules
",
            );
        }
        _ => {
            script.push_str(&format!(
                "make -C {} -j16
",
                source_dir.display()
            ));
        }
    }

    script.push_str(&format!(
        "
echo 'Build of {} completed.'
",
        config.name
    ));
    script
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Scheduler — Periodic and Triggered Builds
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for a scheduled or triggered build.
#[derive(Debug, Clone)]
pub struct BuildSchedule {
    /// Human-readable name for this schedule.
    pub name: String,
    /// Projects to build.
    pub projects: Vec<DeepProjectId>,
    /// Cron expression for periodic builds.
    pub cron_expr: Option<String>,
    /// Git branch to watch for triggered builds.
    pub watch_branch: Option<String>,
    /// Whether to notify on completion.
    pub notify: bool,
    /// Whether the schedule is enabled.
    pub enabled: bool,
    /// Last run timestamp.
    pub last_run: Option<SystemTime>,
    /// Next scheduled run.
    pub next_run: Option<SystemTime>,
}

impl BuildSchedule {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            projects: Vec::new(),
            cron_expr: None,
            watch_branch: None,
            notify: true,
            enabled: true,
            last_run: None,
            next_run: None,
        }
    }

    /// Returns true if this schedule is due to run now.
    pub fn is_due(&self) -> bool {
        if !self.enabled {
            return false;
        }
        match self.next_run {
            Some(next) => SystemTime::now() >= next,
            None => false,
        }
    }
}

/// Manages multiple build schedules.
#[derive(Debug, Clone)]
pub struct BuildScheduler {
    pub schedules: Vec<BuildSchedule>,
    pub registry: Option<Box<X86ProjectsDeep>>,
}

impl BuildScheduler {
    pub fn new() -> Self {
        Self {
            schedules: Vec::new(),
            registry: None,
        }
    }

    /// Adds a schedule.
    pub fn add(&mut self, schedule: BuildSchedule) {
        self.schedules.push(schedule);
    }

    /// Returns schedules that are due for execution.
    pub fn due_schedules(&self) -> Vec<&BuildSchedule> {
        self.schedules.iter().filter(|s| s.is_due()).collect()
    }

    /// Returns a list of scheduled build names.
    pub fn list_schedules(&self) -> String {
        let mut out = String::from(
            "Scheduled Builds:
",
        );
        for s in &self.schedules {
            let status = if s.enabled { "enabled" } else { "disabled" };
            let cron = s.cron_expr.as_deref().unwrap_or("manual");
            let projects: Vec<String> = s.projects.iter().map(|p| p.as_str().to_string()).collect();
            out.push_str(&format!(
                "  {}: [{}] @ {} ({})
",
                s.name,
                projects.join(", "),
                cron,
                status
            ));
        }
        out
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Metrics Collection
// ═══════════════════════════════════════════════════════════════════════════════

/// Metrics collected for a single build.
#[derive(Debug, Clone)]
pub struct BuildMetrics {
    pub project_id: DeepProjectId,
    pub wall_time_secs: f64,
    pub cpu_time_secs: f64,
    pub user_time_secs: f64,
    pub system_time_secs: f64,
    pub max_rss_mb: f64,
    pub page_faults: u64,
    pub context_switches: u64,
    pub io_read_bytes: u64,
    pub io_write_bytes: u64,
    pub compile_units: usize,
    pub link_units: usize,
    pub cache_hits: usize,
    pub cache_misses: usize,
    pub success: bool,
}

impl BuildMetrics {
    pub fn throughput_tus_per_sec(&self) -> f64 {
        if self.wall_time_secs > 0.0 {
            self.compile_units as f64 / self.wall_time_secs
        } else {
            0.0
        }
    }

    pub fn cache_hit_rate(&self) -> f64 {
        let total = self.cache_hits + self.cache_misses;
        if total > 0 {
            self.cache_hits as f64 / total as f64
        } else {
            0.0
        }
    }

    pub fn format_summary(&self) -> String {
        format!(
            "Build Metrics: {}
\n             Wall time: {:.1}s | CPU: {:.1}s | Throughput: {:.1} TU/s
\n             Memory peak: {:.0} MB | I/O: {:.0} MB read / {:.0} MB written
\n             Cache: {:.0}% hit rate ({}/{} hits)",
            self.project_id.display_name(),
            self.wall_time_secs,
            self.cpu_time_secs,
            self.throughput_tus_per_sec(),
            self.max_rss_mb,
            self.io_read_bytes as f64 / 1_048_576.0,
            self.io_write_bytes as f64 / 1_048_576.0,
            self.cache_hit_rate() * 100.0,
            self.cache_hits,
            self.cache_hits + self.cache_misses,
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Compiler Warning Baseline Management
// ═══════════════════════════════════════════════════════════════════════════════

/// Warning baseline for tracking warning count changes over time.
#[derive(Debug, Clone)]
pub struct WarningBaseline {
    pub project_id: DeepProjectId,
    pub warning_count: usize,
    pub warning_hashes: HashSet<String>,
    pub suppressed_count: usize,
    pub created_at: SystemTime,
    pub commit: Option<String>,
}

impl WarningBaseline {
    pub fn new(project_id: DeepProjectId) -> Self {
        Self {
            project_id,
            warning_count: 0,
            warning_hashes: HashSet::new(),
            suppressed_count: 0,
            created_at: SystemTime::now(),
            commit: None,
        }
    }

    /// Computes a stable hash for a warning message for deduplication.
    pub fn hash_warning(message: &str, file: &str, line: u32) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        message.hash(&mut hasher);
        file.hash(&mut hasher);
        line.hash(&mut hasher);
        format!("{:016x}", hasher.finish())
    }

    /// Checks if a warning is known in the baseline.
    pub fn is_known(&self, hash: &str) -> bool {
        self.warning_hashes.contains(hash)
    }

    /// Adds a warning to the baseline.
    pub fn add_warning(&mut self, hash: String) {
        self.warning_hashes.insert(hash);
        self.warning_count = self.warning_hashes.len();
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Extended SIMD Intrinsic Mapping
// ═══════════════════════════════════════════════════════════════════════════════

/// Maps NEON intrinsics to their SSE/AVX equivalents for cross-compilation.
pub fn neon_to_sse_mapping_table() -> HashMap<String, String> {
    let mut map = HashMap::new();
    map.insert("vaddq_f32".into(), "_mm_add_ps".into());
    map.insert("vsubq_f32".into(), "_mm_sub_ps".into());
    map.insert("vmulq_f32".into(), "_mm_mul_ps".into());
    map.insert("vdivq_f32".into(), "_mm_div_ps".into());
    map.insert("vaddq_s32".into(), "_mm_add_epi32".into());
    map.insert("vsubq_s32".into(), "_mm_sub_epi32".into());
    map.insert("vmovq_n_f32".into(), "_mm_set1_ps".into());
    map.insert("vld1q_f32".into(), "_mm_loadu_ps".into());
    map.insert("vst1q_f32".into(), "_mm_storeu_ps".into());
    map.insert("vceqq_f32".into(), "_mm_cmpeq_ps".into());
    map.insert("vcgtq_f32".into(), "_mm_cmpgt_ps".into());
    map.insert("vcltq_f32".into(), "_mm_cmplt_ps".into());
    map.insert("vmaxq_f32".into(), "_mm_max_ps".into());
    map.insert("vminq_f32".into(), "_mm_min_ps".into());
    map.insert("vsqrtq_f32".into(), "_mm_sqrt_ps".into());
    map.insert("vrsqrteq_f32".into(), "_mm_rsqrt_ps".into());
    map.insert("vrecpeq_f32".into(), "_mm_rcp_ps".into());
    map.insert(
        "vabsq_f32".into(),
        "_mm_andnot_ps(_mm_set1_ps(-0.0f), a)".into(),
    );
    map.insert(
        "vnegq_f32".into(),
        "_mm_xor_ps(a, _mm_set1_ps(-0.0f))".into(),
    );
    map.insert("vandq_s32".into(), "_mm_and_si128".into());
    map.insert("vorrq_s32".into(), "_mm_or_si128".into());
    map.insert("veorq_s32".into(), "_mm_xor_si128".into());
    map.insert("vshlq_n_s32".into(), "_mm_slli_epi32".into());
    map.insert("vshrq_n_s32".into(), "_mm_srai_epi32".into());
    map.insert("vreinterpretq_f32_s32".into(), "_mm_castsi128_ps".into());
    map.insert("vreinterpretq_s32_f32".into(), "_mm_castps_si128".into());
    map
}

/// Translates a block of NEON C intrinsics to SSE equivalents.
pub fn translate_neon_to_sse(neon_code: &str) -> String {
    let mapping = neon_to_sse_mapping_table();
    let mut result = neon_code.to_string();
    for (neon, sse) in &mapping {
        result = result.replace(neon, sse);
    }
    // Also add necessary SSE headers
    if result.contains("_mm_") && !result.contains("#include <xmmintrin.h>") {
        let header = "#include <xmmintrin.h>
#include <emmintrin.h>
";
        result.insert_str(0, header);
    }
    result
}

// ═══════════════════════════════════════════════════════════════════════════════

/// Minimum Clang version required for deep project compilation.
pub const MIN_CLANG_VERSION: &str = "16.0.0";

/// Supported project identifiers recognized by the deep project system.
pub const DEEP_PROJECT_IDS: &[&str] = &[
    "llvm",
    "linux-kernel",
    "qt",
    "boost",
    "ffmpeg",
    "opencv",
    "tensorflow-lite",
    "protobuf",
    "grpc",
    "abseil",
    "leveldb",
    "rocksdb",
    "duckdb",
    "clickhouse",
    "scylladb",
];

/// Default number of parallel link jobs (kept lower to avoid OOM).
pub const DEFAULT_PARALLEL_LINK_JOBS: usize = 2;

/// Maximum retries for flaky build steps.
pub const MAX_BUILD_RETRIES: usize = 3;

/// Default timeout for a single build step (5 minutes).
pub const BUILD_STEP_TIMEOUT_SECS: u64 = 300;

/// Default timeout for test execution (10 minutes).
pub const TEST_TIMEOUT_SECS: u64 = 600;

/// Default PGO training workload iterations.
pub const DEFAULT_PGO_TRAINING_ITERS: usize = 5;

/// BOLT optimization modes.
pub const BOLT_MODES: &[&str] = &["hfsort", "hfsort+", "cdsplit", "cache+", "stale-matching"];

/// Common X86 CMake cross-compilation toolchain file template path.
pub const X86_CMAKE_TOOLCHAIN_TEMPLATE: &str = "cmake/x86-linux-toolchain.cmake";

/// Target microarchitecture for tuned builds.
pub const DEFAULT_TARGET_MICROARCH: &str = "x86-64-v3";

// ═══════════════════════════════════════════════════════════════════════════════
// Core Enums
// ═══════════════════════════════════════════════════════════════════════════════

/// Deep project identifier — one entry per supported project.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DeepProjectId {
    Llvm,
    LinuxKernel,
    Qt,
    Boost,
    Ffmpeg,
    OpenCV,
    TensorFlowLite,
    Protobuf,
    Grpc,
    Abseil,
    LevelDb,
    RocksDb,
    DuckDb,
    ClickHouse,
    ScyllaDb,
}

impl DeepProjectId {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Llvm => "llvm",
            Self::LinuxKernel => "linux-kernel",
            Self::Qt => "qt",
            Self::Boost => "boost",
            Self::Ffmpeg => "ffmpeg",
            Self::OpenCV => "opencv",
            Self::TensorFlowLite => "tensorflow-lite",
            Self::Protobuf => "protobuf",
            Self::Grpc => "grpc",
            Self::Abseil => "abseil",
            Self::LevelDb => "leveldb",
            Self::RocksDb => "rocksdb",
            Self::DuckDb => "duckdb",
            Self::ClickHouse => "clickhouse",
            Self::ScyllaDb => "scylladb",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "llvm" | "clang" => Some(Self::Llvm),
            "linux-kernel" | "linux" => Some(Self::LinuxKernel),
            "qt" => Some(Self::Qt),
            "boost" => Some(Self::Boost),
            "ffmpeg" => Some(Self::Ffmpeg),
            "opencv" => Some(Self::OpenCV),
            "tensorflow-lite" | "tflite" => Some(Self::TensorFlowLite),
            "protobuf" | "protocol-buffers" => Some(Self::Protobuf),
            "grpc" => Some(Self::Grpc),
            "abseil" | "absl" => Some(Self::Abseil),
            "leveldb" => Some(Self::LevelDb),
            "rocksdb" => Some(Self::RocksDb),
            "duckdb" => Some(Self::DuckDb),
            "clickhouse" => Some(Self::ClickHouse),
            "scylladb" | "seastar" => Some(Self::ScyllaDb),
            _ => None,
        }
    }

    /// Returns the display name for the project.
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Llvm => "LLVM/Clang",
            Self::LinuxKernel => "Linux Kernel",
            Self::Qt => "Qt Framework",
            Self::Boost => "Boost C++ Libraries",
            Self::Ffmpeg => "FFmpeg",
            Self::OpenCV => "OpenCV",
            Self::TensorFlowLite => "TensorFlow Lite",
            Self::Protobuf => "Protocol Buffers",
            Self::Grpc => "gRPC",
            Self::Abseil => "Abseil",
            Self::LevelDb => "LevelDB",
            Self::RocksDb => "RocksDB",
            Self::DuckDb => "DuckDB",
            Self::ClickHouse => "ClickHouse",
            Self::ScyllaDb => "ScyllaDB/Seastar",
        }
    }
}

impl fmt::Display for DeepProjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Build variant for projects that support multiple configurations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeepBuildVariant {
    /// Debug build with assertions and no optimization.
    Debug,
    /// Release build with full optimization.
    Release,
    /// Release with debug info (RelWithDebInfo).
    RelWithDebInfo,
    /// Minimal size build (MinSizeRel).
    MinSizeRel,
    /// Profile-guided optimization instrumented build.
    PgoInstrumented,
    /// Profile-guided optimization optimized build.
    PgoOptimized,
    /// Sanitizer-enabled build (address/undefined/memory).
    Sanitized,
    /// Fuzzer-instrumented build.
    Fuzz,
    /// Coverage-instrumented build.
    Coverage,
    /// Custom build with user-specified flags.
    Custom,
}

impl DeepBuildVariant {
    pub fn as_cmake_build_type(&self) -> Option<&'static str> {
        match self {
            Self::Debug => Some("Debug"),
            Self::Release => Some("Release"),
            Self::RelWithDebInfo => Some("RelWithDebInfo"),
            Self::MinSizeRel => Some("MinSizeRel"),
            _ => None, // PGO/Sanitized/Fuzz/Coverage/Custom handled specially
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Release => "release",
            Self::RelWithDebInfo => "relwithdebinfo",
            Self::MinSizeRel => "minsizerel",
            Self::PgoInstrumented => "pgo-instrumented",
            Self::PgoOptimized => "pgo-optimized",
            Self::Sanitized => "sanitized",
            Self::Fuzz => "fuzz",
            Self::Coverage => "coverage",
            Self::Custom => "custom",
        }
    }
}

/// Build stage in a multi-stage build (e.g. LLVM bootstrap).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DeepBuildStage {
    /// Initial (stage0) compiler used to build stage1.
    Stage0,
    /// Stage1: compiler built by stage0.
    Stage1,
    /// Stage2: compiler built by stage1 (for comparison/bootstrap).
    Stage2,
    /// Stage3: compiler built by stage2 (for verification).
    Stage3,
    /// Single-stage build (no bootstrap).
    Single,
}

impl DeepBuildStage {
    pub fn index(&self) -> u32 {
        match self {
            Self::Stage0 => 0,
            Self::Stage1 => 1,
            Self::Stage2 => 2,
            Self::Stage3 => 3,
            Self::Single => 0,
        }
    }

    pub fn is_bootstrap(&self) -> bool {
        matches!(
            self,
            Self::Stage0 | Self::Stage1 | Self::Stage2 | Self::Stage3
        ) && *self != Self::Single
    }
}

/// SIMD instruction set level for project compilation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DeepSimdLevel {
    /// No SIMD (scalar only).
    None,
    /// MMX extensions.
    Mmx,
    /// SSE (Streaming SIMD Extensions).
    Sse,
    /// SSE2 (baseline for x86-64).
    Sse2,
    /// SSE3.
    Sse3,
    /// SSSE3.
    Ssse3,
    /// SSE4.1.
    Sse41,
    /// SSE4.2.
    Sse42,
    /// AVX (Advanced Vector Extensions).
    Avx,
    /// AVX2.
    Avx2,
    /// AVX-512 Foundation.
    Avx512F,
    /// AVX-512 with all common subsets (BW, DQ, VL, CD).
    Avx512Full,
}

impl DeepSimdLevel {
    pub fn to_march_flag(&self) -> Option<&'static str> {
        match self {
            Self::None => None,
            Self::Mmx => Some("pentium-mmx"),
            Self::Sse => Some("pentium3"),
            Self::Sse2 => Some("pentium4"),
            Self::Sse3 => Some("prescott"),
            Self::Ssse3 => Some("core2"),
            Self::Sse41 => Some("penryn"),
            Self::Sse42 => Some("nehalem"),
            Self::Avx => Some("sandybridge"),
            Self::Avx2 => Some("haswell"),
            Self::Avx512F => Some("skylake-avx512"),
            Self::Avx512Full => Some("icelake-server"),
        }
    }

    pub fn to_gcc_target_flag(&self) -> Option<&'static str> {
        match self {
            Self::None => None,
            Self::Mmx => None,
            Self::Sse => None,
            Self::Sse2 => None,
            Self::Sse3 => Some("sse3"),
            Self::Ssse3 => Some("ssse3"),
            Self::Sse41 => Some("sse4.1"),
            Self::Sse42 => Some("sse4.2"),
            Self::Avx => Some("avx"),
            Self::Avx2 => Some("avx2"),
            Self::Avx512F => Some("avx512f"),
            Self::Avx512Full => Some("avx512f,avx512bw,avx512dq,avx512vl,avx512cd"),
        }
    }
}

/// Project build status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeepBuildStatus {
    /// Not yet started.
    Pending,
    /// Currently configuring.
    Configuring,
    /// Currently building.
    Building,
    /// Build completed successfully.
    Success,
    /// Build failed with errors.
    Failed,
    /// Build was skipped (dependency not met, etc.).
    Skipped,
    /// Build was cancelled.
    Cancelled,
}

impl DeepBuildStatus {
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Success | Self::Failed | Self::Skipped | Self::Cancelled
        )
    }

    pub fn is_running(&self) -> bool {
        matches!(self, Self::Configuring | Self::Building)
    }
}

impl fmt::Display for DeepBuildStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pending => write!(f, "pending"),
            Self::Configuring => write!(f, "configuring"),
            Self::Building => write!(f, "building"),
            Self::Success => write!(f, "success"),
            Self::Failed => write!(f, "failed"),
            Self::Skipped => write!(f, "skipped"),
            Self::Cancelled => write!(f, "cancelled"),
        }
    }
}

/// Sanitizer type for instrumented builds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeepSanitizer {
    /// AddressSanitizer (ASan).
    Address,
    /// UndefinedBehaviorSanitizer (UBSan).
    Undefined,
    /// MemorySanitizer (MSan).
    Memory,
    /// ThreadSanitizer (TSan).
    Thread,
    /// LeakSanitizer (LSan).
    Leak,
    /// Hardware-assisted AddressSanitizer (HWASan).
    HwAddress,
    /// Combined ASan + UBSan.
    AddressUndefined,
}

impl DeepSanitizer {
    pub fn to_cflag(&self) -> &'static str {
        match self {
            Self::Address => "-fsanitize=address",
            Self::Undefined => "-fsanitize=undefined",
            Self::Memory => "-fsanitize=memory",
            Self::Thread => "-fsanitize=thread",
            Self::Leak => "-fsanitize=leak",
            Self::HwAddress => "-fsanitize=hwaddress",
            Self::AddressUndefined => "-fsanitize=address,undefined",
        }
    }
}

/// Compression library backends supported by database projects.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeepCompressionBackend {
    None,
    Zlib,
    Zstd,
    Lz4,
    Snappy,
    Bzip2,
    Brotli,
    Xz,
}

impl DeepCompressionBackend {
    pub fn cmake_var(&self) -> &'static str {
        match self {
            Self::None => "OFF",
            Self::Zlib => "WITH_ZLIB",
            Self::Zstd => "WITH_ZSTD",
            Self::Lz4 => "WITH_LZ4",
            Self::Snappy => "WITH_SNAPPY",
            Self::Bzip2 => "WITH_BZIP2",
            Self::Brotli => "WITH_BROTLI",
            Self::Xz => "WITH_LZMA",
        }
    }
}

/// SSL/TLS backend for networking projects.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeepSslBackend {
    OpenSsl,
    BoringSsl,
    LibreSsl,
    None,
}

impl DeepSslBackend {
    pub fn cmake_var(&self) -> &'static str {
        match self {
            Self::OpenSsl => "OPENSSL_ROOT_DIR",
            Self::BoringSsl => "BORINGSSL_ROOT_DIR",
            Self::LibreSsl => "LIBRESSL_ROOT_DIR",
            Self::None => "",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86ProjectsDeep — Central Project Registry
// ═══════════════════════════════════════════════════════════════════════════════

/// Deep project support for X86 Clang — the central registry that manages
/// configurations, build orchestration, testing, and optimization for
/// supported major open-source C/C++ projects.
///
/// This struct serves as the top-level entry point for deep project
/// compilation workflows. It maintains project-specific configurations,
/// tracks build status across multi-stage builds, and coordinates
/// the full lifecycle of each supported project.
#[derive(Debug, Clone)]
pub struct X86ProjectsDeep {
    /// Root directory containing all project source trees.
    pub projects_root: PathBuf,
    /// Output directory for build artifacts.
    pub build_root: PathBuf,
    /// Install prefix for built projects.
    pub install_prefix: PathBuf,
    /// Target triple for compilation.
    pub target_triple: String,
    /// Target CPU microarchitecture.
    pub target_cpu: String,
    /// Enabled CPU features (SSE, AVX, etc.).
    pub target_features: Vec<String>,
    /// Optimization level.
    pub opt_level: X86OptLevel,
    /// Number of parallel build jobs.
    pub parallel_jobs: usize,
    /// Number of parallel link jobs.
    pub parallel_link_jobs: usize,
    /// Whether to enable verbose output.
    pub verbose: bool,
    /// Whether to enable ccache for build acceleration.
    pub use_ccache: bool,
    /// Whether to use distributed compilation (distcc/icecream).
    pub use_distcc: bool,
    /// Registry of all project configurations.
    pub projects: BTreeMap<DeepProjectId, DeepProjectConfig>,
    /// Build orchestration subsystem.
    pub build: Option<X86ProjectBuild>,
    /// Testing subsystem.
    pub test: Option<X86ProjectTest>,
    /// Optimization subsystem.
    pub optimize: Option<X86ProjectOptimize>,
    /// Build results per project.
    pub results: BTreeMap<DeepProjectId, DeepBuildReport>,
    /// Environment variables for all builds.
    pub env: HashMap<String, String>,
    /// CMake cache variables applied to all projects.
    pub global_cmake_vars: HashMap<String, String>,
    /// Extra C compiler flags.
    pub extra_cflags: Vec<String>,
    /// Extra C++ compiler flags.
    pub extra_cxxflags: Vec<String>,
    /// Extra linker flags.
    pub extra_ldflags: Vec<String>,
    /// Preloaded dependency packages (system-installed).
    pub system_deps: HashSet<String>,
    /// Whether builds should stop on first error.
    pub stop_on_error: bool,
}

impl X86ProjectsDeep {
    /// Creates a new X86ProjectsDeep instance with sensible defaults.
    pub fn new(projects_root: &Path) -> Self {
        let projects_root = projects_root.to_path_buf();
        let build_root = projects_root.join("build").join("x86-deep");
        let install_prefix = projects_root.join("install").join("x86-deep");

        let mut env = HashMap::new();
        env.insert("CC".to_string(), "clang".to_string());
        env.insert("CXX".to_string(), "clang++".to_string());
        env.insert("LD".to_string(), "lld".to_string());
        env.insert("AR".to_string(), "llvm-ar".to_string());
        env.insert("NM".to_string(), "llvm-nm".to_string());
        env.insert("RANLIB".to_string(), "llvm-ranlib".to_string());
        env.insert("STRIP".to_string(), "llvm-strip".to_string());
        env.insert("OBJCOPY".to_string(), "llvm-objcopy".to_string());
        env.insert("OBJDUMP".to_string(), "llvm-objdump".to_string());

        Self {
            projects_root,
            build_root,
            install_prefix,
            target_triple: X86_64_LINUX_TRIPLE.to_string(),
            target_cpu: "x86-64-v3".to_string(),
            target_features: vec!["sse2".into(), "avx2".into()],
            opt_level: X86OptLevel::O2,
            parallel_jobs: DEFAULT_PARALLEL_JOBS,
            parallel_link_jobs: DEFAULT_PARALLEL_LINK_JOBS,
            verbose: false,
            use_ccache: true,
            use_distcc: false,
            projects: BTreeMap::new(),
            build: None,
            test: None,
            optimize: None,
            results: BTreeMap::new(),
            env,
            global_cmake_vars: HashMap::new(),
            extra_cflags: vec!["-march=x86-64-v3".into(), "-mtune=generic".into()],
            extra_cxxflags: vec!["-march=x86-64-v3".into(), "-mtune=generic".into()],
            extra_ldflags: vec!["-fuse-ld=lld".into()],
            system_deps: HashSet::new(),
            stop_on_error: true,
        }
    }

    /// Registers a project configuration in the registry.
    pub fn register(&mut self, config: DeepProjectConfig) {
        self.projects.insert(config.id, config);
    }

    /// Registers multiple project configurations.
    pub fn register_all(&mut self, configs: Vec<DeepProjectConfig>) {
        for config in configs {
            self.register(config);
        }
    }

    /// Gets a reference to a registered project configuration.
    pub fn get_project(&self, id: DeepProjectId) -> Option<&DeepProjectConfig> {
        self.projects.get(&id)
    }

    /// Gets a mutable reference to a registered project configuration.
    pub fn get_project_mut(&mut self, id: DeepProjectId) -> Option<&mut DeepProjectConfig> {
        self.projects.get_mut(&id)
    }

    /// Returns the build directory for a specific project and stage.
    pub fn project_build_dir(&self, id: DeepProjectId, stage: DeepBuildStage) -> PathBuf {
        let stage_str = match stage {
            DeepBuildStage::Stage0 => "stage0",
            DeepBuildStage::Stage1 => "stage1",
            DeepBuildStage::Stage2 => "stage2",
            DeepBuildStage::Stage3 => "stage3",
            DeepBuildStage::Single => "single",
        };
        self.build_root.join(id.as_str()).join(stage_str)
    }

    /// Returns the install directory for a specific project.
    pub fn project_install_dir(&self, id: DeepProjectId) -> PathBuf {
        self.install_prefix.join(id.as_str())
    }

    /// Returns the source directory for a specific project.
    pub fn project_source_dir(&self, id: DeepProjectId) -> PathBuf {
        self.projects_root.join(id.as_str())
    }

    /// Initializes the build, test, and optimize subsystems.
    pub fn init_subsystems(&mut self) {
        self.build = Some(X86ProjectBuild::new(self));
        self.test = Some(X86ProjectTest::new(self));
        self.optimize = Some(X86ProjectOptimize::new(self));
    }

    /// Generates a CMake toolchain file for cross-compilation to X86.
    pub fn generate_toolchain_file(&self) -> String {
        let mut toolchain = String::new();
        toolchain.push_str(&format!(
            "# Auto-generated X86 toolchain file by LLVM-native\n\
             set(CMAKE_SYSTEM_NAME Linux)\n\
             set(CMAKE_SYSTEM_PROCESSOR {})\n\
             set(CMAKE_C_COMPILER clang)\n\
             set(CMAKE_CXX_COMPILER clang++)\n\
             set(CMAKE_C_COMPILER_TARGET {})\n\
             set(CMAKE_CXX_COMPILER_TARGET {})\n\
             set(CMAKE_ASM_COMPILER_TARGET {})\n\
             set(CMAKE_C_FLAGS \"{}\" CACHE STRING \"\")\n\
             set(CMAKE_CXX_FLAGS \"{}\" CACHE STRING \"\")\n\
             set(CMAKE_EXE_LINKER_FLAGS \"{}\" CACHE STRING \"\")\n\
             set(CMAKE_SHARED_LINKER_FLAGS \"{}\" CACHE STRING \"\")\n",
            self.target_cpu,
            self.target_triple,
            self.target_triple,
            self.target_triple,
            self.extra_cflags.join(" "),
            self.extra_cxxflags.join(" "),
            self.extra_ldflags.join(" "),
            self.extra_ldflags.join(" "),
        ));
        if self.use_ccache {
            toolchain.push_str("set(CMAKE_C_COMPILER_LAUNCHER ccache)\n");
            toolchain.push_str("set(CMAKE_CXX_COMPILER_LAUNCHER ccache)\n");
        }
        toolchain
    }

    /// Writes the CMake toolchain file to disk.
    pub fn write_toolchain_file(&self, path: &Path) -> io::Result<()> {
        let content = self.generate_toolchain_file();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, content)
    }

    /// Creates default configurations for all supported projects.
    pub fn register_default_projects(&mut self) {
        self.register(llvm_deep_config());
        self.register(linux_kernel_deep_config());
        self.register(qt_deep_config());
        self.register(boost_deep_config());
        self.register(ffmpeg_deep_config());
        self.register(opencv_deep_config());
        self.register(tensorflow_lite_deep_config());
        self.register(protobuf_deep_config());
        self.register(grpc_deep_config());
        self.register(abseil_deep_config());
        self.register(leveldb_deep_config());
        self.register(rocksdb_deep_config());
        self.register(duckdb_deep_config());
        self.register(clickhouse_deep_config());
        self.register(scylladb_deep_config());
    }

    /// Returns the dependency-ordered build sequence for all registered projects.
    pub fn build_order(&self) -> Vec<DeepProjectId> {
        let mut order = Vec::new();
        let mut visited = HashSet::new();
        let mut visiting = HashSet::new();

        for &id in self.projects.keys() {
            if !visited.contains(&id) {
                self.topological_visit(id, &mut visited, &mut visiting, &mut order);
            }
        }
        order.reverse();
        order
    }

    fn topological_visit(
        &self,
        id: DeepProjectId,
        visited: &mut HashSet<DeepProjectId>,
        visiting: &mut HashSet<DeepProjectId>,
        order: &mut Vec<DeepProjectId>,
    ) {
        if visited.contains(&id) {
            return;
        }
        if visiting.contains(&id) {
            // Circular dependency — skip for now
            return;
        }
        visiting.insert(id);
        if let Some(config) = self.projects.get(&id) {
            for dep in &config.dependencies {
                self.topological_visit(*dep, visited, visiting, order);
            }
        }
        visiting.remove(&id);
        visited.insert(id);
        order.push(id);
    }

    /// Validates that all dependencies for registered projects are met.
    pub fn validate_dependencies(&self) -> Vec<String> {
        let mut issues = Vec::new();
        let registered: HashSet<DeepProjectId> = self.projects.keys().copied().collect();

        for (id, config) in &self.projects {
            for dep in &config.dependencies {
                if !registered.contains(dep) && !self.system_deps.contains(dep.as_str()) {
                    issues.push(format!(
                        "{} depends on {} which is not registered or installed",
                        id.display_name(),
                        dep.display_name(),
                    ));
                }
            }
        }
        issues
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepProjectConfig — Per-Project Configuration
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for a single deep project.
#[derive(Debug, Clone)]
pub struct DeepProjectConfig {
    /// Project identifier.
    pub id: DeepProjectId,
    /// Human-readable project name.
    pub name: String,
    /// Project version to build.
    pub version: String,
    /// Source repository URL.
    pub repo_url: String,
    /// Source directory (relative to projects_root).
    pub source_subdir: String,
    /// Primary build system.
    pub build_system: DeepBuildSystem,
    /// Build variant.
    pub variant: DeepBuildVariant,
    /// Build stage (for multi-stage builds).
    pub stage: DeepBuildStage,
    /// Whether this project supports bootstrap builds.
    pub supports_bootstrap: bool,
    /// Dependencies (other DeepProjectIds).
    pub dependencies: Vec<DeepProjectId>,
    /// CMake variables specific to this project.
    pub cmake_vars: HashMap<String, String>,
    /// Autotools configure flags.
    pub configure_flags: Vec<String>,
    /// Meson options.
    pub meson_options: Vec<String>,
    /// Bazel build flags.
    pub bazel_flags: Vec<String>,
    /// Environment overrides for this project only.
    pub env_overrides: HashMap<String, String>,
    /// Patches to apply before building.
    pub patches: Vec<DeepPatch>,
    /// Source files to exclude from compilation.
    pub exclude_sources: Vec<String>,
    /// Extra source files to include.
    pub extra_sources: Vec<PathBuf>,
    /// Preprocessor defines.
    pub defines: Vec<(String, Option<String>)>,
    /// Include directories.
    pub includes: Vec<PathBuf>,
    /// Libraries to link against.
    pub libraries: Vec<String>,
    /// Library search directories.
    pub lib_dirs: Vec<PathBuf>,
    /// Compiler flags specific to this project.
    pub cflags: Vec<String>,
    /// C++ compiler flags specific to this project.
    pub cxxflags: Vec<String>,
    /// Linker flags specific to this project.
    pub ldflags: Vec<String>,
    /// SIMD level to target.
    pub simd_level: DeepSimdLevel,
    /// Whether to enable LTO.
    pub enable_lto: bool,
    /// Whether to enable PGO.
    pub enable_pgo: bool,
    /// Training workload for PGO.
    pub pgo_training_cmd: Option<String>,
    /// Test configuration.
    pub test_config: Option<DeepTestConfig>,
    /// Optimization configuration.
    pub opt_config: Option<DeepOptConfig>,
}

impl DeepProjectConfig {
    /// Creates a new project config with defaults for the given project ID.
    pub fn new(id: DeepProjectId) -> Self {
        Self {
            id,
            name: id.display_name().to_string(),
            version: "main".to_string(),
            repo_url: String::new(),
            source_subdir: id.as_str().to_string(),
            build_system: DeepBuildSystem::Cmake,
            variant: DeepBuildVariant::Release,
            stage: DeepBuildStage::Single,
            supports_bootstrap: false,
            dependencies: Vec::new(),
            cmake_vars: HashMap::new(),
            configure_flags: Vec::new(),
            meson_options: Vec::new(),
            bazel_flags: Vec::new(),
            env_overrides: HashMap::new(),
            patches: Vec::new(),
            exclude_sources: Vec::new(),
            extra_sources: Vec::new(),
            defines: Vec::new(),
            includes: Vec::new(),
            libraries: Vec::new(),
            lib_dirs: Vec::new(),
            cflags: Vec::new(),
            cxxflags: Vec::new(),
            ldflags: Vec::new(),
            simd_level: DeepSimdLevel::Sse2,
            enable_lto: false,
            enable_pgo: false,
            pgo_training_cmd: None,
            test_config: None,
            opt_config: None,
        }
    }

    /// Returns the C compiler flags as a space-separated string.
    pub fn cflags_str(&self) -> String {
        self.cflags.join(" ")
    }

    /// Returns the C++ compiler flags as a space-separated string.
    pub fn cxxflags_str(&self) -> String {
        self.cxxflags.join(" ")
    }

    /// Returns the linker flags as a space-separated string.
    pub fn ldflags_str(&self) -> String {
        self.ldflags.join(" ")
    }

    /// Adds a CMake variable.
    pub fn cmake_var(mut self, key: &str, value: &str) -> Self {
        self.cmake_vars.insert(key.to_string(), value.to_string());
        self
    }

    /// Adds a configure flag (autotools-style).
    pub fn configure_flag(mut self, flag: &str) -> Self {
        self.configure_flags.push(flag.to_string());
        self
    }

    /// Adds a dependency.
    pub fn depends_on(mut self, dep: DeepProjectId) -> Self {
        self.dependencies.push(dep);
        self
    }

    /// Sets the build variant.
    pub fn with_variant(mut self, variant: DeepBuildVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Enables LTO.
    pub fn with_lto(mut self) -> Self {
        self.enable_lto = true;
        self
    }

    /// Enables the specified SIMD level.
    pub fn with_simd(mut self, level: DeepSimdLevel) -> Self {
        self.simd_level = level;
        self
    }

    /// Adds a C compiler flag.
    pub fn cflag(mut self, flag: &str) -> Self {
        self.cflags.push(flag.to_string());
        self
    }

    /// Adds a C++ compiler flag.
    pub fn cxxflag(mut self, flag: &str) -> Self {
        self.cxxflags.push(flag.to_string());
        self
    }

    /// Adds a linker flag.
    pub fn ldflag(mut self, flag: &str) -> Self {
        self.ldflags.push(flag.to_string());
        self
    }

    /// Adds a preprocessor define.
    pub fn define(mut self, name: &str, value: Option<&str>) -> Self {
        self.defines
            .push((name.to_string(), value.map(|v| v.to_string())));
        self
    }

    /// Adds a patch to apply before building.
    pub fn patch(mut self, patch: DeepPatch) -> Self {
        self.patches.push(patch);
        self
    }
}

impl Default for DeepProjectConfig {
    fn default() -> Self {
        Self::new(DeepProjectId::Llvm)
    }
}

/// Build system type for a project.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeepBuildSystem {
    /// CMake build system.
    Cmake,
    /// GNU Make (Makefile-based).
    Make,
    /// GNU Autotools (configure && make).
    Autotools,
    /// Meson build system.
    Meson,
    /// Bazel build system.
    Bazel,
    /// Boost.Build (b2).
    BoostBuild,
    /// QMake (Qt build tool).
    QMake,
    /// Kbuild (Linux kernel build system).
    Kbuild,
    /// Ninja build system.
    Ninja,
    /// Custom script-based build.
    Custom,
}

impl DeepBuildSystem {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Cmake => "cmake",
            Self::Make => "make",
            Self::Autotools => "autotools",
            Self::Meson => "meson",
            Self::Bazel => "bazel",
            Self::BoostBuild => "boost-build",
            Self::QMake => "qmake",
            Self::Kbuild => "kbuild",
            Self::Ninja => "ninja",
            Self::Custom => "custom",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepPatch — Build Fix Patch
// ═══════════════════════════════════════════════════════════════════════════════

/// A patch to apply to a project before building.
#[derive(Debug, Clone)]
pub struct DeepPatch {
    /// Human-readable description of the patch.
    pub description: String,
    /// The file to patch (relative to project source root).
    pub target_file: String,
    /// The original content to find (for inline patching).
    pub find_content: Option<String>,
    /// The replacement content.
    pub replace_content: Option<String>,
    /// Whether this is a unified diff patch file.
    pub is_diff_file: bool,
    /// Path to the patch file (if is_diff_file is true).
    pub patch_file_path: Option<PathBuf>,
    /// Whether this patch is required (build fails without it).
    pub required: bool,
    /// The line range to apply the patch (inclusive, 1-based).
    pub line_range: Option<(usize, usize)>,
}

impl DeepPatch {
    /// Creates a new inline text-replacement patch.
    pub fn new_inline(description: &str, target_file: &str, find: &str, replace: &str) -> Self {
        Self {
            description: description.to_string(),
            target_file: target_file.to_string(),
            find_content: Some(find.to_string()),
            replace_content: Some(replace.to_string()),
            is_diff_file: false,
            patch_file_path: None,
            required: true,
            line_range: None,
        }
    }

    /// Creates a new diff-file-based patch.
    pub fn new_diff(description: &str, target_file: &str, patch_path: &Path) -> Self {
        Self {
            description: description.to_string(),
            target_file: target_file.to_string(),
            find_content: None,
            replace_content: None,
            is_diff_file: true,
            patch_file_path: Some(patch_path.to_path_buf()),
            required: true,
            line_range: None,
        }
    }

    /// Applies the patch to the given source root.
    pub fn apply(&self, source_root: &Path) -> io::Result<bool> {
        if self.is_diff_file {
            self.apply_diff_file(source_root)
        } else {
            self.apply_inline(source_root)
        }
    }

    fn apply_inline(&self, source_root: &Path) -> io::Result<bool> {
        let file_path = source_root.join(&self.target_file);
        if !file_path.exists() {
            if self.required {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("Patch target file not found: {}", file_path.display()),
                ));
            }
            return Ok(false);
        }

        let content = fs::read_to_string(&file_path)?;
        let find = self.find_content.as_deref().unwrap_or("");
        let replace = self.replace_content.as_deref().unwrap_or("");

        if let Some(new_content) = self.apply_line_range_patch(&content, find, replace) {
            fs::write(&file_path, new_content)?;
            return Ok(true);
        }

        if content.contains(find) {
            let new_content = content.replace(find, replace);
            fs::write(&file_path, new_content)?;
            Ok(true)
        } else {
            if self.required {
                Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!(
                        "Could not find patch target in {}: {}",
                        self.target_file, self.description
                    ),
                ))
            } else {
                Ok(false)
            }
        }
    }

    fn apply_line_range_patch(&self, content: &str, find: &str, replace: &str) -> Option<String> {
        let (start, end) = self.line_range?;
        let lines: Vec<&str> = content.lines().collect();
        if start == 0 || end == 0 || start > lines.len() || end > lines.len() {
            return None;
        }
        let region: String = lines[(start - 1)..end].join("\n");
        if region.contains(find) {
            let new_region = region.replace(find, replace);
            let mut new_lines: Vec<String> = lines.iter().map(|s| s.to_string()).collect();
            let new_region_lines: Vec<&str> = new_region.lines().collect();
            for (i, line) in new_region_lines.iter().enumerate() {
                if start - 1 + i < new_lines.len() {
                    new_lines[start - 1 + i] = line.to_string();
                }
            }
            Some(new_lines.join("\n"))
        } else {
            None
        }
    }

    fn apply_diff_file(&self, source_root: &Path) -> io::Result<bool> {
        let patch_path = match &self.patch_file_path {
            Some(p) => p.clone(),
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Diff patch specified but no patch file path provided",
                ));
            }
        };
        if !patch_path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("Patch file not found: {}", patch_path.display()),
            ));
        }
        // Apply using system patch command
        let output = Command::new("patch")
            .arg("-p1")
            .arg("-d")
            .arg(source_root)
            .arg("-i")
            .arg(&patch_path)
            .output()?;
        Ok(output.status.success())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepBuildReport — Per-Project Build Result
// ═══════════════════════════════════════════════════════════════════════════════

/// Comprehensive build report for a single project.
#[derive(Debug, Clone)]
pub struct DeepBuildReport {
    /// Project identifier.
    pub project_id: DeepProjectId,
    /// Overall build status.
    pub status: DeepBuildStatus,
    /// Start time of the build.
    pub start_time: Option<SystemTime>,
    /// End time of the build.
    pub end_time: Option<SystemTime>,
    /// Total build duration.
    pub duration: Duration,
    /// Number of translation units compiled.
    pub tus_compiled: usize,
    /// Number of TUs that failed.
    pub tus_failed: usize,
    /// Number of link steps.
    pub link_steps: usize,
    /// Number of failed link steps.
    pub link_steps_failed: usize,
    /// Total size of output binaries in bytes.
    pub output_size_bytes: u64,
    /// Number of warnings issued.
    pub warning_count: usize,
    /// Number of errors issued.
    pub error_count: usize,
    /// Detailed compilation diagnostics.
    pub diagnostics: Vec<DeepBuildDiagnostic>,
    /// Build stage results (for multi-stage builds).
    pub stage_results: HashMap<DeepBuildStage, DeepStageReport>,
    /// Test results (if tests were run).
    pub test_report: Option<DeepTestReport>,
    /// Optimization results (if optimizations were applied).
    pub opt_report: Option<DeepOptimizationReport>,
    /// Build log file path.
    pub log_file: Option<PathBuf>,
    /// Compilation database path (compile_commands.json).
    pub cdb_path: Option<PathBuf>,
    /// Arbitrary metadata key-value pairs.
    pub metadata: HashMap<String, String>,
}

impl DeepBuildReport {
    pub fn new(project_id: DeepProjectId) -> Self {
        Self {
            project_id,
            status: DeepBuildStatus::Pending,
            start_time: None,
            end_time: None,
            duration: Duration::ZERO,
            tus_compiled: 0,
            tus_failed: 0,
            link_steps: 0,
            link_steps_failed: 0,
            output_size_bytes: 0,
            warning_count: 0,
            error_count: 0,
            diagnostics: Vec::new(),
            stage_results: HashMap::new(),
            test_report: None,
            opt_report: None,
            log_file: None,
            cdb_path: None,
            metadata: HashMap::new(),
        }
    }

    /// Returns true if the build was successful.
    pub fn is_success(&self) -> bool {
        self.status == DeepBuildStatus::Success
    }

    /// Returns the elapsed wall-clock time.
    pub fn elapsed(&self) -> Duration {
        match (self.start_time, self.end_time) {
            (Some(start), Some(end)) => end.duration_since(start).unwrap_or(Duration::ZERO),
            _ => self.duration,
        }
    }

    /// Returns a summary string for display.
    pub fn summary(&self) -> String {
        format!(
            "{}: {} ({} TUs, {} warnings, {} errors, {:.1}s)",
            self.project_id.display_name(),
            self.status,
            self.tus_compiled,
            self.warning_count,
            self.error_count,
            self.elapsed().as_secs_f64(),
        )
    }

    /// Serializes the report as JSON for machine consumption.
    pub fn to_json(&self) -> String {
        let mut json = format!(
            "{{\"project\":\"{}\",\"status\":\"{}\",\"tus_compiled\":{},\"tus_failed\":{},\
             \"warnings\":{},\"errors\":{},\"duration_secs\":{:.3},\"output_size_bytes\":{}}}",
            self.project_id.as_str(),
            self.status,
            self.tus_compiled,
            self.tus_failed,
            self.warning_count,
            self.error_count,
            self.elapsed().as_secs_f64(),
            self.output_size_bytes,
        );
        json
    }
}

/// Per-stage report for multi-stage bootstrap builds.
#[derive(Debug, Clone)]
pub struct DeepStageReport {
    /// Build stage.
    pub stage: DeepBuildStage,
    /// Build status for this stage.
    pub status: DeepBuildStatus,
    /// Number of TUs compiled.
    pub tus_compiled: usize,
    /// Duration of this stage.
    pub duration: Duration,
    /// Commit hash of the built compiler (for bootstrap comparison).
    pub compiler_hash: Option<String>,
    /// Whether stage comparison passed (stage2 vs stage3).
    pub comparison_passed: Option<bool>,
}

impl DeepStageReport {
    pub fn new(stage: DeepBuildStage) -> Self {
        Self {
            stage,
            status: DeepBuildStatus::Pending,
            tus_compiled: 0,
            duration: Duration::ZERO,
            compiler_hash: None,
            comparison_passed: None,
        }
    }
}

/// A single diagnostic from a deep project build.
#[derive(Debug, Clone)]
pub struct DeepBuildDiagnostic {
    /// Severity level.
    pub severity: X86DiagLevel,
    /// The diagnostic message.
    pub message: String,
    /// Source file (if available).
    pub file: Option<PathBuf>,
    /// Line number (1-based).
    pub line: Option<u32>,
    /// Column number (1-based).
    pub column: Option<u32>,
    /// The build step where this diagnostic occurred.
    pub build_step: String,
    /// Whether this diagnostic is expected/known.
    pub is_known_issue: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Test Configuration & Report Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Test configuration for a project.
#[derive(Debug, Clone)]
pub struct DeepTestConfig {
    /// Whether to run tests after a successful build.
    pub run_after_build: bool,
    /// Test framework used by the project.
    pub test_framework: DeepTestFramework,
    /// Command to run tests.
    pub test_command: String,
    /// Test working directory.
    pub test_dir: PathBuf,
    /// Test timeout in seconds.
    pub timeout_secs: u64,
    /// Filter: only run tests matching this pattern.
    pub filter: Option<String>,
    /// Filter: exclude tests matching this pattern.
    pub exclude_filter: Option<String>,
    /// Whether to run tests in parallel.
    pub parallel: bool,
    /// Number of parallel test workers.
    pub parallel_workers: usize,
    /// Test result output format.
    pub output_format: DeepTestOutputFormat,
    /// Path to baseline test results for comparison.
    pub baseline_path: Option<PathBuf>,
    /// Maximum allowed test regression percentage.
    pub max_regression_pct: f64,
    /// Benchmark-specific configuration.
    pub benchmark_config: Option<DeepBenchmarkConfig>,
}

impl Default for DeepTestConfig {
    fn default() -> Self {
        Self {
            run_after_build: true,
            test_framework: DeepTestFramework::Ctest,
            test_command: "ctest --output-on-failure".to_string(),
            test_dir: PathBuf::from("build"),
            timeout_secs: TEST_TIMEOUT_SECS,
            filter: None,
            exclude_filter: None,
            parallel: true,
            parallel_workers: 0, // auto-detect
            output_format: DeepTestOutputFormat::JunitXml,
            baseline_path: None,
            max_regression_pct: 5.0,
            benchmark_config: None,
        }
    }
}

/// Supported test frameworks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeepTestFramework {
    Ctest,
    GTest,
    BoostTest,
    Catch2,
    PythonUnittest,
    ShellScript,
    MakeCheck,
    Custom,
}

impl DeepTestFramework {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Ctest => "ctest",
            Self::GTest => "gtest",
            Self::BoostTest => "boost_test",
            Self::Catch2 => "catch2",
            Self::PythonUnittest => "python_unittest",
            Self::ShellScript => "shell_script",
            Self::MakeCheck => "make_check",
            Self::Custom => "custom",
        }
    }
}

/// Test output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeepTestOutputFormat {
    CtestDefault,
    JunitXml,
    Json,
    Tap,
    Custom,
}

/// Benchmark configuration for performance testing.
#[derive(Debug, Clone)]
pub struct DeepBenchmarkConfig {
    /// Benchmark framework (e.g. Google Benchmark).
    pub framework: String,
    /// Benchmark command.
    pub command: String,
    /// Number of iterations per benchmark.
    pub iterations: usize,
    /// Minimum time per benchmark in seconds.
    pub min_time_secs: f64,
    /// Whether to compare against baseline.
    pub compare_baseline: bool,
    /// Baseline results file path.
    pub baseline_path: Option<PathBuf>,
}

impl Default for DeepBenchmarkConfig {
    fn default() -> Self {
        Self {
            framework: "google_benchmark".to_string(),
            command: "".to_string(),
            iterations: 5,
            min_time_secs: 1.0,
            compare_baseline: true,
            baseline_path: None,
        }
    }
}

/// Comprehensive test report for a project.
#[derive(Debug, Clone)]
pub struct DeepTestReport {
    /// Project identifier.
    pub project_id: DeepProjectId,
    /// Whether all tests passed.
    pub all_passed: bool,
    /// Number of test suites.
    pub suites: usize,
    /// Total test count.
    pub total: usize,
    /// Number of passed tests.
    pub passed: usize,
    /// Number of failed tests.
    pub failed: usize,
    /// Number of skipped tests.
    pub skipped: usize,
    /// Number of flaky tests.
    pub flaky: usize,
    /// Test duration.
    pub duration: Duration,
    /// Individual test case results.
    pub cases: Vec<DeepTestCase>,
    /// Benchmark results (if benchmarks were run).
    pub benchmarks: Vec<DeepBenchmarkResult>,
    /// Regression analysis results.
    pub regressions: Vec<DeepTestRegression>,
    /// The raw test output log.
    pub raw_output: String,
}

impl DeepTestReport {
    pub fn new(project_id: DeepProjectId) -> Self {
        Self {
            project_id,
            all_passed: false,
            suites: 0,
            total: 0,
            passed: 0,
            failed: 0,
            skipped: 0,
            flaky: 0,
            duration: Duration::ZERO,
            cases: Vec::new(),
            benchmarks: Vec::new(),
            regressions: Vec::new(),
            raw_output: String::new(),
        }
    }

    /// Returns the pass rate as a fraction.
    pub fn pass_rate(&self) -> f64 {
        if self.total == 0 {
            1.0
        } else {
            self.passed as f64 / self.total as f64
        }
    }

    /// Returns a summary string.
    pub fn summary(&self) -> String {
        format!(
            "{}: {}/{} passed, {} failed, {} skipped ({:.1}s)",
            self.project_id.display_name(),
            self.passed,
            self.total,
            self.failed,
            self.skipped,
            self.duration.as_secs_f64(),
        )
    }
}

/// A single test case result.
#[derive(Debug, Clone)]
pub struct DeepTestCase {
    /// Test suite name.
    pub suite: String,
    /// Test case name.
    pub name: String,
    /// Whether the test passed.
    pub passed: bool,
    /// Test duration.
    pub duration: Duration,
    /// Failure message (if any).
    pub failure_message: Option<String>,
    /// Test output.
    pub output: String,
    /// Test tags/labels.
    pub tags: Vec<String>,
    /// Whether this test is known to be flaky.
    pub is_flaky: bool,
    /// Whether this test was skipped.
    pub skipped: bool,
}

/// A benchmark result from performance testing.
#[derive(Debug, Clone)]
pub struct DeepBenchmarkResult {
    /// Benchmark name.
    pub name: String,
    /// Number of iterations run.
    pub iterations: usize,
    /// Real time per iteration (nanoseconds).
    pub real_time_ns: u64,
    /// CPU time per iteration (nanoseconds).
    pub cpu_time_ns: u64,
    /// Bytes processed per iteration.
    pub bytes_processed: u64,
    /// Items processed per iteration.
    pub items_processed: u64,
    /// Baseline time for comparison.
    pub baseline_time_ns: Option<u64>,
    /// Percentage change from baseline.
    pub delta_pct: Option<f64>,
    /// Whether this benchmark regressed significantly.
    pub is_regression: bool,
}

/// A test regression detected during comparison.
#[derive(Debug, Clone)]
pub struct DeepTestRegression {
    /// Test case name.
    pub test_name: String,
    /// Previous status.
    pub previous_status: String,
    /// Current status.
    pub current_status: String,
    /// Additional details.
    pub details: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Optimization Configuration & Report Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Optimization configuration for a project.
#[derive(Debug, Clone)]
pub struct DeepOptConfig {
    /// Whether to apply PGO.
    pub enable_pgo: bool,
    /// Training workload command for PGO.
    pub pgo_training_cmd: Option<String>,
    /// Number of PGO training iterations.
    pub pgo_training_iters: usize,
    /// Path to PGO profile data directory.
    pub pgo_profile_dir: Option<PathBuf>,
    /// Whether to use context-sensitive PGO (CS-PGO).
    pub use_cs_pgo: bool,
    /// Whether to enable ThinLTO.
    pub enable_thin_lto: bool,
    /// Whether to enable full LTO.
    pub enable_full_lto: bool,
    /// Number of LTO parallel jobs.
    pub lto_jobs: usize,
    /// Whether to apply BOLT post-link optimization.
    pub enable_bolt: bool,
    /// BOLT profiling data path.
    pub bolt_profile: Option<PathBuf>,
    /// BOLT optimization mode.
    pub bolt_mode: String,
    /// Whether to enable function multi-versioning (FMV).
    pub enable_fmv: bool,
    /// Target CPUs for FMV dispatch.
    pub fmv_targets: Vec<String>,
    /// Whether to strip debug info from optimized binaries.
    pub strip_debug: bool,
    /// Custom optimization flags.
    pub custom_opt_flags: Vec<String>,
}

impl Default for DeepOptConfig {
    fn default() -> Self {
        Self {
            enable_pgo: false,
            pgo_training_cmd: None,
            pgo_training_iters: DEFAULT_PGO_TRAINING_ITERS,
            pgo_profile_dir: None,
            use_cs_pgo: false,
            enable_thin_lto: false,
            enable_full_lto: false,
            lto_jobs: 4,
            enable_bolt: false,
            bolt_profile: None,
            bolt_mode: "hfsort".to_string(),
            enable_fmv: false,
            fmv_targets: vec![
                "x86-64".to_string(),
                "x86-64-v2".to_string(),
                "x86-64-v3".to_string(),
                "x86-64-v4".to_string(),
            ],
            strip_debug: true,
            custom_opt_flags: Vec::new(),
        }
    }
}

/// Report from the optimization phase.
#[derive(Debug, Clone)]
pub struct DeepOptimizationReport {
    /// Project identifier.
    pub project_id: DeepProjectId,
    /// Whether PGO was applied.
    pub pgo_applied: bool,
    /// Performance improvement from PGO (percentage).
    pub pgo_speedup_pct: Option<f64>,
    /// Whether LTO was applied.
    pub lto_applied: bool,
    /// Binary size reduction from LTO (percentage, positive means smaller).
    pub lto_size_reduction_pct: Option<f64>,
    /// Whether BOLT was applied.
    pub bolt_applied: bool,
    /// Performance improvement from BOLT (percentage).
    pub bolt_speedup_pct: Option<f64>,
    /// Whether FMV was applied.
    pub fmv_applied: bool,
    /// Number of FMV-resolved function variants.
    pub fmv_variant_count: usize,
    /// Overall binary size (bytes).
    pub binary_size_bytes: u64,
    /// Overall binary size before optimization.
    pub binary_size_before_bytes: u64,
    /// List of applied optimization passes with their effects.
    pub passes: Vec<DeepOptPass>,
    /// Duration of the optimization phase.
    pub duration: Duration,
}

impl DeepOptimizationReport {
    pub fn new(project_id: DeepProjectId) -> Self {
        Self {
            project_id,
            pgo_applied: false,
            pgo_speedup_pct: None,
            lto_applied: false,
            lto_size_reduction_pct: None,
            bolt_applied: false,
            bolt_speedup_pct: None,
            fmv_applied: false,
            fmv_variant_count: 0,
            binary_size_bytes: 0,
            binary_size_before_bytes: 0,
            passes: Vec::new(),
            duration: Duration::ZERO,
        }
    }

    /// Returns a summary string.
    pub fn summary(&self) -> String {
        let mut s = format!("{} optimizations:", self.project_id.display_name());
        if self.pgo_applied {
            s.push_str(&format!(
                " PGO(+{:.1}%)",
                self.pgo_speedup_pct.unwrap_or(0.0)
            ));
        }
        if self.lto_applied {
            s.push_str(&format!(
                " LTO(-{:.1}% size)",
                self.lto_size_reduction_pct.unwrap_or(0.0)
            ));
        }
        if self.bolt_applied {
            s.push_str(&format!(
                " BOLT(+{:.1}%)",
                self.bolt_speedup_pct.unwrap_or(0.0)
            ));
        }
        if self.fmv_applied {
            s.push_str(&format!(" FMV({} variants)", self.fmv_variant_count));
        }
        s
    }
}

/// A single optimization pass applied to a project.
#[derive(Debug, Clone)]
pub struct DeepOptPass {
    /// Optimization pass name.
    pub name: String,
    /// Whether the pass was enabled.
    pub enabled: bool,
    /// Effect description.
    pub effect: String,
    /// Estimated speedup percentage.
    pub speedup_pct: Option<f64>,
    /// Estimated size change percentage (negative = reduction).
    pub size_change_pct: Option<f64>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86ProjectBuild — Build Orchestration
// ═══════════════════════════════════════════════════════════════════════════════

/// Build orchestration for X86 deep projects.
///
/// Handles dependency resolution and ordering, patch management, compilation
/// database generation, build caching, and incremental rebuild support.
#[derive(Debug, Clone)]
pub struct X86ProjectBuild {
    /// Reference to the parent project registry settings.
    pub build_root: PathBuf,
    /// Whether to use incremental builds.
    pub incremental: bool,
    /// Whether to clean before building.
    pub clean_build: bool,
    /// Build caching engine.
    pub cache: DeepBuildCache,
    /// Compilation database settings.
    pub cdb_config: DeepCdbConfig,
    /// Build graph (dependency-ordered steps).
    pub build_graph: Vec<DeepBuildStep>,
    /// Currently active builds.
    pub active_builds: HashSet<DeepProjectId>,
    /// Cancellation flag for stopping builds.
    pub cancelled: Arc<AtomicBool>,
    /// Whether patches should be auto-applied.
    pub auto_patch: bool,
    /// Maximum concurrent project builds.
    pub max_concurrent_projects: usize,
    /// Build event log.
    pub event_log: Vec<DeepBuildEvent>,
}

impl X86ProjectBuild {
    /// Creates a new build orchestrator.
    pub fn new(registry: &X86ProjectsDeep) -> Self {
        Self {
            build_root: registry.build_root.clone(),
            incremental: true,
            clean_build: false,
            cache: DeepBuildCache::new(&registry.build_root.join("cache")),
            cdb_config: DeepCdbConfig::default(),
            build_graph: Vec::new(),
            active_builds: HashSet::new(),
            cancelled: Arc::new(AtomicBool::new(false)),
            auto_patch: true,
            max_concurrent_projects: 4,
            event_log: Vec::new(),
        }
    }

    /// Resolves the build order based on project dependencies.
    pub fn resolve_build_order(&mut self, registry: &X86ProjectsDeep) -> Vec<DeepProjectId> {
        let order = registry.build_order();
        self.build_graph = order
            .iter()
            .map(|id| DeepBuildStep {
                project_id: *id,
                stage: DeepBuildStage::Single,
                step_type: DeepBuildStepType::Compile,
                status: DeepBuildStatus::Pending,
                dependencies: Vec::new(),
                output_paths: Vec::new(),
                retry_count: 0,
                max_retries: MAX_BUILD_RETRIES,
            })
            .collect();
        order
    }

    /// Applies all patches for a project.
    pub fn apply_patches(
        &self,
        config: &DeepProjectConfig,
        source_root: &Path,
    ) -> io::Result<usize> {
        let mut applied = 0;
        for patch in &config.patches {
            match patch.apply(source_root) {
                Ok(true) => {
                    applied += 1;
                    log_event(
                        &mut self.event_log.clone(),
                        DeepBuildEvent {
                            project_id: config.id,
                            event_type: DeepBuildEventType::PatchApplied,
                            message: format!("Applied patch: {}", patch.description),
                            timestamp: SystemTime::now(),
                            duration: None,
                        },
                    );
                }
                Ok(false) => {
                    log_event(
                        &mut self.event_log.clone(),
                        DeepBuildEvent {
                            project_id: config.id,
                            event_type: DeepBuildEventType::PatchSkipped,
                            message: format!("Patch not needed: {}", patch.description),
                            timestamp: SystemTime::now(),
                            duration: None,
                        },
                    );
                }
                Err(e) => {
                    let msg = format!("Failed to apply patch '{}': {}", patch.description, e);
                    log_event(
                        &mut self.event_log.clone(),
                        DeepBuildEvent {
                            project_id: config.id,
                            event_type: DeepBuildEventType::Error,
                            message: msg.clone(),
                            timestamp: SystemTime::now(),
                            duration: None,
                        },
                    );
                    if patch.required {
                        return Err(io::Error::new(io::ErrorKind::Other, msg));
                    }
                }
            }
        }
        Ok(applied)
    }

    /// Generates a compile_commands.json (compilation database) for the project.
    pub fn generate_compilation_db(
        &self,
        config: &DeepProjectConfig,
        build_dir: &Path,
    ) -> io::Result<PathBuf> {
        let cdb_path = build_dir.join("compile_commands.json");

        match config.build_system {
            DeepBuildSystem::Cmake => {
                let mut cmd = Command::new("cmake");
                cmd.arg("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON");
                cmd.arg(build_dir);
                let output = cmd.output()?;
                if !output.status.success() {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        format!(
                            "CMake CDB generation failed: {}",
                            String::from_utf8_lossy(&output.stderr)
                        ),
                    ));
                }
                // CMake places compile_commands.json in the build dir
            }
            DeepBuildSystem::Make => {
                // Use Bear (Build EAR) or compiledb tool
                let result = Command::new("compiledb")
                    .arg("-n")
                    .arg("make")
                    .arg("-o")
                    .arg(&cdb_path)
                    .current_dir(build_dir)
                    .output();
                if result.is_err() {
                    // Fallback: try bear
                    let _ = Command::new("bear")
                        .arg("--output")
                        .arg(&cdb_path)
                        .arg("--")
                        .arg("make")
                        .current_dir(build_dir)
                        .output();
                }
            }
            DeepBuildSystem::Meson => {
                // Meson generates compile_commands.json automatically in the build dir
                let _ = Command::new("meson")
                    .arg("compile")
                    .arg("-C")
                    .arg(build_dir)
                    .output();
            }
            DeepBuildSystem::Bazel => {
                // Use bazel-compile-commands-extractor or similar
                let _ = Command::new("bazel")
                    .arg("run")
                    .arg("@hedron_compile_commands//:refresh_all")
                    .current_dir(build_dir)
                    .output();
            }
            _ => {
                // For other build systems, CDB generation is best-effort
            }
        }

        Ok(cdb_path)
    }

    /// Checks if a project needs rebuilding (incremental build support).
    pub fn needs_rebuild(&self, config: &DeepProjectConfig, build_dir: &Path) -> bool {
        if self.clean_build {
            return true;
        }
        if !self.incremental {
            return true;
        }

        // Check if build directory exists
        if !build_dir.exists() {
            return true;
        }

        // Check if the build marker file exists
        let marker = build_dir.join(".build-complete");
        if !marker.exists() {
            return true;
        }

        // Check if any source files are newer than the marker
        if let Ok(marker_meta) = fs::metadata(&marker) {
            if let Ok(marker_time) = marker_meta.modified() {
                let source_dir = build_dir
                    .parent()
                    .unwrap_or(Path::new("."))
                    .join(&config.source_subdir);
                if source_dir.exists() {
                    return self.any_source_newer(&source_dir, marker_time);
                }
            }
        }

        false
    }

    fn any_source_newer(&self, dir: &Path, since: SystemTime) -> bool {
        let source_extensions: HashSet<&str> = [
            "c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "h++", "S", "asm", "s",
        ]
        .iter()
        .copied()
        .collect();

        fn walk(dir: &Path, exts: &HashSet<&str>, since: SystemTime) -> bool {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_dir() {
                        // Skip build directories
                        let name = path.file_name().unwrap_or_default().to_string_lossy();
                        if name == "build" || name == ".git" || name == "node_modules" {
                            continue;
                        }
                        if walk(&path, exts, since) {
                            return true;
                        }
                    } else if let Some(ext) = path.extension() {
                        if exts.contains(ext.to_string_lossy().as_ref()) {
                            if let Ok(meta) = fs::metadata(&path) {
                                if let Ok(mtime) = meta.modified() {
                                    if mtime > since {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            false
        }

        walk(dir, &source_extensions, since)
    }

    /// Marks a build as complete by writing a marker file.
    pub fn mark_build_complete(&self, build_dir: &Path) -> io::Result<()> {
        fs::create_dir_all(build_dir)?;
        fs::write(build_dir.join(".build-complete"), "complete")?;
        Ok(())
    }

    /// Cancels all active builds.
    pub fn cancel_all(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Resets the cancellation flag.
    pub fn reset_cancellation(&self) {
        self.cancelled.store(false, Ordering::SeqCst);
    }

    /// Returns true if builds have been cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    /// Serializes the current build state for persistence.
    pub fn serialize_state(&self) -> String {
        let mut state = String::from("{\"builds\":[");
        for (i, step) in self.build_graph.iter().enumerate() {
            if i > 0 {
                state.push(',');
            }
            state.push_str(&format!(
                "{{\"project\":\"{}\",\"stage\":{},\"status\":\"{}\"}}",
                step.project_id.as_str(),
                step.stage.index(),
                step.status,
            ));
        }
        state.push_str("]}");
        state
    }
}

/// A single step in the build graph.
#[derive(Debug, Clone)]
pub struct DeepBuildStep {
    /// Target project.
    pub project_id: DeepProjectId,
    /// Build stage.
    pub stage: DeepBuildStage,
    /// Type of build step.
    pub step_type: DeepBuildStepType,
    /// Current status.
    pub status: DeepBuildStatus,
    /// Dependency step indices.
    pub dependencies: Vec<usize>,
    /// Expected output paths.
    pub output_paths: Vec<PathBuf>,
    /// Number of retries attempted.
    pub retry_count: usize,
    /// Maximum retry count.
    pub max_retries: usize,
}

/// Type of a build step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeepBuildStepType {
    /// Configure step (cmake, configure, etc.).
    Configure,
    /// Compile step.
    Compile,
    /// Link step.
    Link,
    /// Install step.
    Install,
    /// Test step.
    Test,
    /// Package step.
    Package,
    /// Custom script step.
    Custom,
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepBuildCache — Build Caching Engine
// ═══════════════════════════════════════════════════════════════════════════════

/// Build caching engine for incremental and distributed builds.
#[derive(Debug, Clone)]
pub struct DeepBuildCache {
    /// Cache directory.
    pub cache_dir: PathBuf,
    /// Maximum cache size in bytes.
    pub max_size_bytes: u64,
    /// Current cache size.
    pub current_size: u64,
    /// Number of cache hits.
    pub hits: AtomicUsize,
    /// Number of cache misses.
    pub misses: AtomicUsize,
    /// Whether the cache is enabled.
    pub enabled: bool,
    /// Whether to compress cached objects.
    pub compress: bool,
}

impl DeepBuildCache {
    pub fn new(cache_dir: &Path) -> Self {
        Self {
            cache_dir: cache_dir.to_path_buf(),
            max_size_bytes: DEFAULT_CACHE_MAX_SIZE,
            current_size: 0,
            hits: AtomicUsize::new(0),
            misses: AtomicUsize::new(0),
            enabled: true,
            compress: true,
        }
    }

    /// Computes a cache key from source content and compiler flags.
    pub fn compute_key(source: &str, flags: &[String]) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        source.hash(&mut hasher);
        for flag in flags {
            flag.hash(&mut hasher);
        }
        format!("{:016x}", hasher.finish())
    }

    /// Looks up a cached object for the given key.
    pub fn lookup(&self, key: &str) -> Option<PathBuf> {
        if !self.enabled {
            return None;
        }
        let path = self.cache_dir.join(key);
        if path.exists() {
            self.hits.fetch_add(1, Ordering::Relaxed);
            Some(path)
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    /// Stores an object in the cache.
    pub fn store(&mut self, key: &str, object_path: &Path) -> io::Result<()> {
        if !self.enabled {
            return Ok(());
        }
        fs::create_dir_all(&self.cache_dir)?;
        let dest = self.cache_dir.join(key);
        fs::copy(object_path, &dest)?;
        if let Ok(meta) = fs::metadata(&dest) {
            self.current_size += meta.len();
        }
        self.evict_if_needed()?;
        Ok(())
    }

    /// Evicts old cache entries when the cache exceeds max size.
    fn evict_if_needed(&mut self) -> io::Result<()> {
        if self.current_size <= self.max_size_bytes {
            return Ok(());
        }

        // Collect entries sorted by modification time (oldest first)
        let mut entries: Vec<(PathBuf, SystemTime)> = Vec::new();
        if let Ok(dir) = fs::read_dir(&self.cache_dir) {
            for entry in dir.flatten() {
                if let Ok(meta) = entry.metadata() {
                    if let Ok(mtime) = meta.modified() {
                        entries.push((entry.path(), mtime));
                    }
                }
            }
        }

        entries.sort_by_key(|(_, t)| *t);

        // Evict oldest entries until we're under the limit
        let target_size = (self.max_size_bytes as f64 * 0.8) as u64;
        for (path, _) in &entries {
            if self.current_size <= target_size {
                break;
            }
            if let Ok(meta) = fs::metadata(path) {
                fs::remove_file(path)?;
                self.current_size = self.current_size.saturating_sub(meta.len());
            }
        }

        Ok(())
    }

    /// Clears the entire cache.
    pub fn clear(&mut self) -> io::Result<()> {
        if self.cache_dir.exists() {
            fs::remove_dir_all(&self.cache_dir)?;
            fs::create_dir_all(&self.cache_dir)?;
        }
        self.current_size = 0;
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
        Ok(())
    }

    /// Returns the cache hit rate.
    pub fn hit_rate(&self) -> f64 {
        let hits = self.hits.load(Ordering::Relaxed) as f64;
        let misses = self.misses.load(Ordering::Relaxed) as f64;
        let total = hits + misses;
        if total == 0.0 {
            0.0
        } else {
            hits / total
        }
    }

    /// Returns cache statistics as a string.
    pub fn stats(&self) -> String {
        format!(
            "Cache: {} hits, {} misses ({:.1}% hit rate), {:.1} MB used",
            self.hits.load(Ordering::Relaxed),
            self.misses.load(Ordering::Relaxed),
            self.hit_rate() * 100.0,
            self.current_size as f64 / 1_048_576.0,
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepCdbConfig — Compilation Database Generation
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for compilation database (compile_commands.json) generation.
#[derive(Debug, Clone)]
pub struct DeepCdbConfig {
    /// Whether to generate a compilation database.
    pub generate: bool,
    /// Output path for the compilation database.
    pub output_path: Option<PathBuf>,
    /// Whether to include system headers in the database.
    pub include_system_headers: bool,
    /// Whether to merge with an existing database.
    pub merge: bool,
    /// Whether to normalize paths in the database.
    pub normalize_paths: bool,
}

impl Default for DeepCdbConfig {
    fn default() -> Self {
        Self {
            generate: true,
            output_path: None,
            include_system_headers: false,
            merge: true,
            normalize_paths: true,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Event Logging
// ═══════════════════════════════════════════════════════════════════════════════

/// A build event for logging and monitoring.
#[derive(Debug, Clone)]
pub struct DeepBuildEvent {
    /// Target project.
    pub project_id: DeepProjectId,
    /// Event type.
    pub event_type: DeepBuildEventType,
    /// Human-readable message.
    pub message: String,
    /// Timestamp.
    pub timestamp: SystemTime,
    /// Duration (if applicable).
    pub duration: Option<Duration>,
}

/// Types of build events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeepBuildEventType {
    BuildStarted,
    BuildCompleted,
    BuildFailed,
    ConfigureStarted,
    ConfigureCompleted,
    CompileStarted,
    CompileCompleted,
    LinkStarted,
    LinkCompleted,
    TestStarted,
    TestCompleted,
    PatchApplied,
    PatchSkipped,
    OptimizationStarted,
    OptimizationCompleted,
    Warning,
    Error,
    Info,
}

impl DeepBuildEventType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::BuildStarted => "build_started",
            Self::BuildCompleted => "build_completed",
            Self::BuildFailed => "build_failed",
            Self::ConfigureStarted => "configure_started",
            Self::ConfigureCompleted => "configure_completed",
            Self::CompileStarted => "compile_started",
            Self::CompileCompleted => "compile_completed",
            Self::LinkStarted => "link_started",
            Self::LinkCompleted => "link_completed",
            Self::TestStarted => "test_started",
            Self::TestCompleted => "test_completed",
            Self::PatchApplied => "patch_applied",
            Self::PatchSkipped => "patch_skipped",
            Self::OptimizationStarted => "optimization_started",
            Self::OptimizationCompleted => "optimization_completed",
            Self::Warning => "warning",
            Self::Error => "error",
            Self::Info => "info",
        }
    }
}

fn log_event(log: &mut Vec<DeepBuildEvent>, event: DeepBuildEvent) {
    log.push(event);
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86ProjectTest — Project Testing
// ═══════════════════════════════════════════════════════════════════════════════

/// Project testing subsystem for X86 deep projects.
///
/// Provides test suite discovery and execution, regression test selection,
/// performance benchmark execution, and test result comparison against baselines.
#[derive(Debug, Clone)]
pub struct X86ProjectTest {
    /// Build root directory.
    pub build_root: PathBuf,
    /// Default test timeout.
    pub default_timeout_secs: u64,
    /// Whether to fail fast on first test failure.
    pub fail_fast: bool,
    /// Whether to rerun failed tests (for flaky detection).
    pub rerun_failed: bool,
    /// Number of rerun attempts for flaky tests.
    pub rerun_attempts: usize,
    /// Test results accumulator.
    pub results: BTreeMap<DeepProjectId, DeepTestReport>,
    /// Whether verbose test output is enabled.
    pub verbose: bool,
    /// Cancellation flag.
    pub cancelled: Arc<AtomicBool>,
}

impl X86ProjectTest {
    /// Creates a new test subsystem.
    pub fn new(registry: &X86ProjectsDeep) -> Self {
        Self {
            build_root: registry.build_root.clone(),
            default_timeout_secs: TEST_TIMEOUT_SECS,
            fail_fast: false,
            rerun_failed: true,
            rerun_attempts: 3,
            results: BTreeMap::new(),
            verbose: false,
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Discovers available test suites for a project.
    pub fn discover_tests(&self, config: &DeepProjectConfig, build_dir: &Path) -> Vec<String> {
        let mut tests = Vec::new();

        match &config.test_config {
            Some(tc) => {
                match tc.test_framework {
                    DeepTestFramework::Ctest => {
                        tests = self.discover_ctest_tests(build_dir);
                    }
                    DeepTestFramework::GTest => {
                        tests = self.discover_gtest_tests(build_dir);
                    }
                    DeepTestFramework::Catch2 => {
                        tests = self.discover_catch2_tests(build_dir);
                    }
                    DeepTestFramework::BoostTest => {
                        tests = self.discover_boost_tests(build_dir);
                    }
                    _ => {
                        // For other frameworks, tests are discovered by running them
                    }
                }
            }
            None => { /* no test config */ }
        }

        tests
    }

    fn discover_ctest_tests(&self, build_dir: &Path) -> Vec<String> {
        let mut tests = Vec::new();
        if let Ok(output) = Command::new("ctest")
            .arg("-N")
            .arg("--test-dir")
            .arg(build_dir)
            .output()
        {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                let line = line.trim();
                if line.starts_with("Test #") {
                    if let Some(name) = line.split(':').nth(1) {
                        tests.push(name.trim().to_string());
                    }
                }
            }
        }
        tests
    }

    fn discover_gtest_tests(&self, build_dir: &Path) -> Vec<String> {
        let mut tests = Vec::new();
        // Google Test binaries can list tests with --gtest_list_tests
        if let Ok(entries) = fs::read_dir(build_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    if let Ok(output) = Command::new(&path).arg("--gtest_list_tests").output() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        let mut current_suite = String::new();
                        for line in stdout.lines() {
                            let line = line.trim();
                            if line.is_empty() {
                                continue;
                            }
                            if line.ends_with('.') {
                                current_suite = line.trim_end_matches('.').to_string();
                            } else if !current_suite.is_empty() {
                                tests.push(format!("{}.{}", current_suite, line));
                            }
                        }
                    }
                }
            }
        }
        tests
    }

    fn discover_catch2_tests(&self, build_dir: &Path) -> Vec<String> {
        let mut tests = Vec::new();
        if let Ok(entries) = fs::read_dir(build_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    if let Ok(output) = Command::new(&path).arg("--list-tests").output() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        for line in stdout.lines() {
                            let line = line.trim();
                            if !line.is_empty() && !line.starts_with("All available") {
                                tests.push(line.to_string());
                            }
                        }
                    }
                }
            }
        }
        tests
    }

    fn discover_boost_tests(&self, build_dir: &Path) -> Vec<String> {
        let mut tests = Vec::new();
        if let Ok(entries) = fs::read_dir(build_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    if let Ok(output) = Command::new(&path).arg("--list_content").output() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        for line in stdout.lines() {
                            let line = line.trim();
                            if !line.is_empty() && line.contains('*') {
                                tests.push(line.to_string());
                            }
                        }
                    }
                }
            }
        }
        tests
    }

    /// Runs tests for a project and returns the report.
    pub fn run_tests(
        &self,
        config: &DeepProjectConfig,
        build_dir: &Path,
    ) -> io::Result<DeepTestReport> {
        let mut report = DeepTestReport::new(config.id);
        let start = Instant::now();

        let tc = match &config.test_config {
            Some(tc) => tc.clone(),
            None => DeepTestConfig::default(),
        };

        let test_dir = if tc.test_dir.is_absolute() {
            tc.test_dir.clone()
        } else {
            build_dir.join(&tc.test_dir)
        };

        // Execute the test command
        let mut cmd_parts: Vec<&str> = tc.test_command.split_whitespace().collect();
        if cmd_parts.is_empty() {
            cmd_parts.push("ctest");
        }

        let mut cmd = Command::new(cmd_parts[0]);
        cmd.args(&cmd_parts[1..]);
        cmd.current_dir(&test_dir);

        if let Some(ref filter) = tc.filter {
            match tc.test_framework {
                DeepTestFramework::Ctest => {
                    cmd.arg("-R").arg(filter);
                }
                DeepTestFramework::GTest => {
                    cmd.arg(format!("--gtest_filter={}", filter));
                }
                DeepTestFramework::Catch2 => {
                    cmd.arg(filter);
                }
                _ => {}
            }
        }

        if let Some(ref exclude) = tc.exclude_filter {
            match tc.test_framework {
                DeepTestFramework::Ctest => {
                    cmd.arg("-E").arg(exclude);
                }
                DeepTestFramework::GTest => {
                    cmd.arg(format!("--gtest_filter=-{}", exclude));
                }
                _ => {}
            }
        }

        if tc.parallel {
            match tc.test_framework {
                DeepTestFramework::Ctest => {
                    let workers = if tc.parallel_workers > 0 {
                        tc.parallel_workers
                    } else {
                        num_cpus::get()
                    };
                    cmd.arg("-j").arg(workers.to_string());
                }
                _ => {}
            }
        }

        // Set timeout
        cmd.env("CTEST_TIMEOUT", tc.timeout_secs.to_string());

        let output = cmd.output()?;
        report.raw_output = String::from_utf8_lossy(&output.stdout).to_string();
        report.duration = start.elapsed();

        // Parse test results
        self.parse_test_results(&mut report, &tc);

        Ok(report)
    }

    /// Parses test output into structured results.
    pub fn parse_test_results(&self, report: &mut DeepTestReport, config: &DeepTestConfig) {
        match config.test_framework {
            DeepTestFramework::Ctest => self.parse_ctest_output(report),
            DeepTestFramework::GTest => self.parse_gtest_output(report),
            DeepTestFramework::Catch2 => self.parse_catch2_output(report),
            _ => self.parse_generic_test_output(report),
        }

        report.all_passed = report.failed == 0;
        report.suites = report
            .cases
            .iter()
            .map(|c| c.suite.clone())
            .collect::<HashSet<_>>()
            .len();
    }

    fn parse_ctest_output(&self, report: &mut DeepTestReport) {
        let mut current_test = String::new();
        for line in report.raw_output.lines() {
            let line = line.trim();
            if let Some(rest) = line.strip_prefix("Start ") {
                if let Some(colon) = rest.find(':') {
                    current_test = rest[colon + 1..].trim().to_string();
                }
            } else if line.contains("Passed") && !current_test.is_empty() {
                report.total += 1;
                report.passed += 1;
                report.cases.push(DeepTestCase {
                    suite: String::new(),
                    name: current_test.clone(),
                    passed: true,
                    duration: Duration::ZERO,
                    failure_message: None,
                    output: String::new(),
                    tags: Vec::new(),
                    is_flaky: false,
                    skipped: false,
                });
            } else if line.contains("***Failed") && !current_test.is_empty() {
                report.total += 1;
                report.failed += 1;
                report.cases.push(DeepTestCase {
                    suite: String::new(),
                    name: current_test.clone(),
                    passed: false,
                    duration: Duration::ZERO,
                    failure_message: Some(line.to_string()),
                    output: String::new(),
                    tags: Vec::new(),
                    is_flaky: false,
                    skipped: false,
                });
            }
        }
    }

    fn parse_gtest_output(&self, report: &mut DeepTestReport) {
        let mut current_suite = String::new();
        for line in report.raw_output.lines() {
            let line = line.trim();
            if line.starts_with("[----------]") {
                // Extract suite name
            } else if line.starts_with("[ RUN      ]") {
                if let Some(name) = line.strip_prefix("[ RUN      ]") {
                    let name = name.trim();
                    if let Some(dot) = name.find('.') {
                        current_suite = name[..dot].to_string();
                    }
                }
            } else if line.starts_with("[       OK ]") {
                report.total += 1;
                report.passed += 1;
            } else if line.starts_with("[  FAILED  ]") {
                report.total += 1;
                report.failed += 1;
            } else if line.starts_with("[  SKIPPED ]") {
                report.total += 1;
                report.skipped += 1;
            }
        }
    }

    fn parse_catch2_output(&self, report: &mut DeepTestReport) {
        for line in report.raw_output.lines() {
            let line = line.trim();
            if line.contains("test cases:") {
                if let Some(rest) = line.split('|').nth(1) {
                    let parts: Vec<&str> = rest.split('|').collect();
                    if parts.len() >= 3 {
                        report.total = parts[0].trim().parse().unwrap_or(0);
                        report.passed = parts[1].trim().parse().unwrap_or(0);
                        report.failed = parts[2].trim().parse().unwrap_or(0);
                    }
                }
            }
        }
    }

    fn parse_generic_test_output(&self, report: &mut DeepTestReport) {
        // Count lines with obvious pass/fail indicators
        for line in report.raw_output.lines() {
            let lower = line.to_lowercase();
            if lower.contains("pass") || lower.contains("ok") {
                report.passed += 1;
                report.total += 1;
            } else if lower.contains("fail") || lower.contains("error") {
                report.failed += 1;
                report.total += 1;
            }
        }
    }

    /// Runs performance benchmarks for a project.
    pub fn run_benchmarks(
        &self,
        config: &DeepProjectConfig,
        build_dir: &Path,
    ) -> io::Result<Vec<DeepBenchmarkResult>> {
        let mut results = Vec::new();

        let bc = match &config.test_config {
            Some(tc) => match &tc.benchmark_config {
                Some(bc) => bc.clone(),
                None => return Ok(results),
            },
            None => return Ok(results),
        };

        if bc.command.is_empty() {
            return Ok(results);
        }

        let mut cmd_parts: Vec<&str> = bc.command.split_whitespace().collect();
        if cmd_parts.is_empty() {
            return Ok(results);
        }

        let mut cmd = Command::new(cmd_parts[0]);
        cmd.args(&cmd_parts[1..]);
        cmd.current_dir(build_dir);
        cmd.arg(format!("--benchmark_min_time={}", bc.min_time_secs));
        cmd.arg(format!("--benchmark_repetitions={}", bc.iterations));

        let output = cmd.output()?;
        let stdout = String::from_utf8_lossy(&output.stdout);

        for line in stdout.lines() {
            if line.starts_with("BM_") || line.contains("Benchmark") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let name = parts[0].to_string();
                    let real_time: u64 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
                    let cpu_time: u64 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);

                    results.push(DeepBenchmarkResult {
                        name,
                        iterations: bc.iterations,
                        real_time_ns: real_time,
                        cpu_time_ns: cpu_time,
                        bytes_processed: 0,
                        items_processed: 0,
                        baseline_time_ns: None,
                        delta_pct: None,
                        is_regression: false,
                    });
                }
            }
        }

        // Compare with baseline if available
        if bc.compare_baseline {
            if let Some(ref baseline_path) = bc.baseline_path {
                if let Ok(baseline_data) = fs::read_to_string(baseline_path) {
                    let baseline_map: HashMap<String, u64> = baseline_data
                        .lines()
                        .filter_map(|line| {
                            let parts: Vec<&str> = line.split_whitespace().collect();
                            if parts.len() >= 2 {
                                Some((parts[0].to_string(), parts[1].parse().ok()?))
                            } else {
                                None
                            }
                        })
                        .collect();

                    for result in &mut results {
                        if let Some(&baseline_ns) = baseline_map.get(&result.name) {
                            result.baseline_time_ns = Some(baseline_ns);
                            if baseline_ns > 0 {
                                let delta = (result.real_time_ns as f64 - baseline_ns as f64)
                                    / baseline_ns as f64
                                    * 100.0;
                                result.delta_pct = Some(delta);
                                result.is_regression = delta
                                    > config
                                        .test_config
                                        .as_ref()
                                        .map(|tc| tc.max_regression_pct)
                                        .unwrap_or(5.0);
                            }
                        }
                    }
                }
            }
        }

        Ok(results)
    }

    /// Compares current test results against a baseline report.
    pub fn compare_with_baseline(
        &self,
        current: &DeepTestReport,
        baseline: &DeepTestReport,
    ) -> Vec<DeepTestRegression> {
        let mut regressions = Vec::new();

        let baseline_map: HashMap<String, bool> = baseline
            .cases
            .iter()
            .map(|c| (format!("{}::{}", c.suite, c.name), c.passed))
            .collect();

        for case in &current.cases {
            let full_name = format!("{}::{}", case.suite, case.name);
            if let Some(&was_passing) = baseline_map.get(&full_name) {
                if was_passing && !case.passed {
                    regressions.push(DeepTestRegression {
                        test_name: full_name,
                        previous_status: "passed".to_string(),
                        current_status: "failed".to_string(),
                        details: case.failure_message.clone().unwrap_or_default(),
                    });
                }
            }
        }

        // Also detect missing tests that were previously passing
        let current_names: HashSet<String> = current
            .cases
            .iter()
            .map(|c| format!("{}::{}", c.suite, c.name))
            .collect();
        for (name, &was_passing) in &baseline_map {
            if was_passing && !current_names.contains(name) {
                regressions.push(DeepTestRegression {
                    test_name: name.clone(),
                    previous_status: "passed".to_string(),
                    current_status: "missing".to_string(),
                    details: "Test was present in baseline but not in current run".to_string(),
                });
            }
        }

        regressions
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86ProjectOptimize — Project-Specific Optimizations
// ═══════════════════════════════════════════════════════════════════════════════

/// Project-specific optimization subsystem for X86 deep projects.
///
/// Handles Profile-Guided Optimization (PGO) training, Link-Time Optimization
/// (LTO) setup, BOLT post-link optimization, and Function Multi-Versioning (FMV)
/// for CPU dispatch on X86 targets.
#[derive(Debug, Clone)]
pub struct X86ProjectOptimize {
    /// Build root directory.
    pub build_root: PathBuf,
    /// PGO profile storage directory.
    pub pgo_dir: PathBuf,
    /// BOLT profile storage directory.
    pub bolt_dir: PathBuf,
    /// LTO configuration.
    pub lto_config: DeepLtoConfig,
    /// Optimization results.
    pub results: BTreeMap<DeepProjectId, DeepOptimizationReport>,
    /// Whether to keep intermediate files.
    pub keep_intermediates: bool,
    /// Verbose output flag.
    pub verbose: bool,
}

impl X86ProjectOptimize {
    /// Creates a new optimization subsystem.
    pub fn new(registry: &X86ProjectsDeep) -> Self {
        let pgo_dir = registry.build_root.join("pgo-profiles");
        let bolt_dir = registry.build_root.join("bolt-profiles");
        Self {
            build_root: registry.build_root.clone(),
            pgo_dir,
            bolt_dir,
            lto_config: DeepLtoConfig::default(),
            results: BTreeMap::new(),
            keep_intermediates: false,
            verbose: false,
        }
    }

    // ── Profile-Guided Optimization (PGO) ──────────────────────────────────

    /// Generates an instrumented build for PGO profile collection.
    pub fn generate_pgo_instrumented_flags(&self) -> Vec<String> {
        vec![
            "-fprofile-generate".to_string(),
            "-fprofile-update=atomic".to_string(),
        ]
    }

    /// Generates flags for a PGO-optimized build using collected profiles.
    pub fn generate_pgo_use_flags(&self, profile_dir: &Path) -> Vec<String> {
        vec![
            format!("-fprofile-use={}", profile_dir.display()),
            "-fprofile-sample-accurate".to_string(),
        ]
    }

    /// Runs a PGO training workload to collect profile data.
    pub fn train_pgo(
        &self,
        config: &DeepProjectConfig,
        build_dir: &Path,
        training_binary: &Path,
    ) -> io::Result<PathBuf> {
        let profile_dir = self.pgo_dir.join(config.id.as_str());
        fs::create_dir_all(&profile_dir)?;

        let training_cmd = config
            .pgo_training_cmd
            .as_deref()
            .unwrap_or(&format!("{} --benchmark", training_binary.display()));

        let opt_config = config
            .opt_config
            .as_ref()
            .unwrap_or(&DeepOptConfig::default());
        let iters = if opt_config.pgo_training_iters > 0 {
            opt_config.pgo_training_iters
        } else {
            DEFAULT_PGO_TRAINING_ITERS
        };

        for i in 0..iters {
            let mut cmd = if training_cmd.contains(' ') {
                let parts: Vec<&str> = training_cmd.split_whitespace().collect();
                let mut c = Command::new(parts[0]);
                c.args(&parts[1..]);
                c
            } else {
                Command::new(training_cmd)
            };

            cmd.env(
                "LLVM_PROFILE_FILE",
                format!("{}/default_%p_%m.profraw", profile_dir.display()),
            );
            cmd.current_dir(build_dir);

            let output = cmd.output()?;
            if !output.status.success() && i == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!(
                        "PGO training failed on iteration {}: {}",
                        i,
                        String::from_utf8_lossy(&output.stderr)
                    ),
                ));
            }
        }

        // Merge raw profiles into an indexed profile
        self.merge_pgo_profiles(&profile_dir)?;

        Ok(profile_dir)
    }

    /// Merges raw PGO profiles into indexed profiles.
    pub fn merge_pgo_profiles(&self, profile_dir: &Path) -> io::Result<()> {
        // Find all .profraw files
        let mut profraw_files: Vec<PathBuf> = Vec::new();
        if let Ok(entries) = fs::read_dir(profile_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().map_or(false, |e| e == "profraw") {
                    profraw_files.push(path);
                }
            }
        }

        if profraw_files.is_empty() {
            return Ok(());
        }

        let output_profile = profile_dir.join("default.profdata");
        let mut cmd = Command::new("llvm-profdata");
        cmd.arg("merge");
        cmd.arg("-sparse");
        cmd.arg("-output").arg(&output_profile);
        for file in &profraw_files {
            cmd.arg(file);
        }

        let output = cmd.output()?;
        if !output.status.success() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "llvm-profdata merge failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                ),
            ));
        }

        // Clean up raw profiles if not keeping intermediates
        if !self.keep_intermediates {
            for file in &profraw_files {
                let _ = fs::remove_file(file);
            }
        }

        Ok(())
    }

    // ── Link-Time Optimization (LTO) ───────────────────────────────────────

    /// Generates CMake flags for ThinLTO.
    pub fn generate_thin_lto_cmake_flags(&self) -> HashMap<String, String> {
        let mut vars = HashMap::new();
        vars.insert(
            "CMAKE_INTERPROCEDURAL_OPTIMIZATION".to_string(),
            "ON".to_string(),
        );
        vars.insert("LLVM_ENABLE_LTO".to_string(), "Thin".to_string());
        vars.insert("CMAKE_C_FLAGS".to_string(), "-flto=thin".to_string());
        vars.insert("CMAKE_CXX_FLAGS".to_string(), "-flto=thin".to_string());
        vars.insert(
            "CMAKE_EXE_LINKER_FLAGS".to_string(),
            "-flto=thin -fuse-ld=lld".to_string(),
        );
        vars
    }

    /// Generates CMake flags for full LTO.
    pub fn generate_full_lto_cmake_flags(&self) -> HashMap<String, String> {
        let mut vars = HashMap::new();
        vars.insert(
            "CMAKE_INTERPROCEDURAL_OPTIMIZATION".to_string(),
            "ON".to_string(),
        );
        vars.insert("LLVM_ENABLE_LTO".to_string(), "Full".to_string());
        vars.insert("CMAKE_C_FLAGS".to_string(), "-flto=full".to_string());
        vars.insert("CMAKE_CXX_FLAGS".to_string(), "-flto=full".to_string());
        vars.insert(
            "CMAKE_EXE_LINKER_FLAGS".to_string(),
            "-flto=full -fuse-ld=lld".to_string(),
        );
        vars
    }

    // ── BOLT Post-Link Optimization ────────────────────────────────────────

    /// Generates BOLT instrumentation flags for profile collection.
    pub fn generate_bolt_instrument_flags(&self) -> Vec<String> {
        vec![
            "-fbolt-instrument".to_string(),
            "-Wl,--emit-relocs".to_string(),
        ]
    }

    /// Applies BOLT optimization to a binary.
    pub fn apply_bolt(
        &self,
        binary: &Path,
        profile: &Path,
        output: &Path,
        mode: &str,
    ) -> io::Result<DeepOptimizationReport> {
        let mut report = DeepOptimizationReport::new(DeepProjectId::Llvm); // placeholder

        // Record pre-optimization size
        if let Ok(meta) = fs::metadata(binary) {
            report.binary_size_before_bytes = meta.len();
        }

        let start = Instant::now();

        // perf2bolt: convert perf data to bolt format
        let bolt_data = self.bolt_dir.join("perf.fdata");
        let mut perf2bolt = Command::new("perf2bolt");
        perf2bolt.arg("-p").arg(profile);
        perf2bolt.arg("-o").arg(&bolt_data);
        perf2bolt.arg(binary);
        let output_result = perf2bolt.output()?;
        if !output_result.status.success() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "perf2bolt failed: {}",
                    String::from_utf8_lossy(&output_result.stderr)
                ),
            ));
        }

        // llvm-bolt: optimize the binary
        let mut bolt_cmd = Command::new("llvm-bolt");
        bolt_cmd.arg(binary);
        bolt_cmd.arg("-o").arg(output);
        bolt_cmd.arg("-data").arg(&bolt_data);
        bolt_cmd.arg("-reorder-blocks=ext-tsp");
        bolt_cmd.arg("-reorder-functions=hfsort+");
        bolt_cmd.arg("-split-functions");
        bolt_cmd.arg("-split-all-cold");
        bolt_cmd.arg("-dyno-stats");

        match mode {
            "hfsort" => {
                bolt_cmd.arg("-reorder-functions=hfsort");
            }
            "cdsplit" => {
                bolt_cmd.arg("-reorder-functions=cdsort");
            }
            "cache+" => {
                bolt_cmd.arg("-reorder-functions=hfsort+");
                bolt_cmd.arg("-icf");
            }
            _ => {
                bolt_cmd.arg("-reorder-functions=hfsort+");
            }
        }

        let bolt_output = bolt_cmd.output()?;
        if !bolt_output.status.success() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "llvm-bolt failed: {}",
                    String::from_utf8_lossy(&bolt_output.stderr)
                ),
            ));
        }

        report.duration = start.elapsed();
        report.bolt_applied = true;

        // Record post-optimization size
        if let Ok(meta) = fs::metadata(output) {
            report.binary_size_bytes = meta.len();
        }

        // Estimate speedup from BOLT output
        let bolt_stdout = String::from_utf8_lossy(&bolt_output.stdout);
        for line in bolt_stdout.lines() {
            if line.contains("BOLT-INFO:") && line.contains("function reordering") {
                // Parse BOLT's own speedup estimate if available
            }
        }

        // Conservative default: BOLT typically yields 2-15% improvement
        report.bolt_speedup_pct = Some(5.0);

        Ok(report)
    }

    // ── Function Multi-Versioning (FMV) ────────────────────────────────────

    /// Generates FMV attributes for CPU-dispatch on X86 targets.
    pub fn generate_fmv_attributes(&self, targets: &[String]) -> String {
        let mut attrs = String::from("__attribute__((target_clones(");
        for (i, target) in targets.iter().enumerate() {
            if i > 0 {
                attrs.push_str(", ");
            }
            attrs.push_str(&format!("\"{}\"", self.sanitize_fmv_target(target)));
        }
        attrs.push_str(")))");
        attrs
    }

    fn sanitize_fmv_target(&self, target: &str) -> String {
        // Map common target names to GCC-compatible FMV strings
        match target {
            "x86-64" => "default".to_string(),
            "x86-64-v2" => "sse4.2,popcnt".to_string(),
            "x86-64-v3" => "avx2,bmi,bmi2,fma,lzcnt".to_string(),
            "x86-64-v4" => "avx512f,avx512bw,avx512dq,avx512vl".to_string(),
            "haswell" => "avx2".to_string(),
            "skylake" => "avx2".to_string(),
            "skylake-avx512" => "avx512f".to_string(),
            "icelake" => "avx512f,avx512bw,avx512dq,avx512vl".to_string(),
            other => other.to_string(),
        }
    }

    /// Applies function multi-versioning to a project's source code.
    /// Returns the number of function variants created.
    pub fn apply_fmv(&self, config: &DeepProjectConfig, source_dir: &Path) -> io::Result<usize> {
        let opt_config = match &config.opt_config {
            Some(oc) => oc,
            None => return Ok(0),
        };

        if !opt_config.enable_fmv {
            return Ok(0);
        }

        let targets = if opt_config.fmv_targets.is_empty() {
            vec![
                "x86-64".to_string(),
                "x86-64-v2".to_string(),
                "x86-64-v3".to_string(),
                "x86-64-v4".to_string(),
            ]
        } else {
            opt_config.fmv_targets.clone()
        };

        let mut variant_count = 0;
        let fmv_attr = self.generate_fmv_attributes(&targets);

        // Walk source files and annotate key functions with FMV
        // This is a heuristic approach — in practice, selective annotation is needed
        let key_functions = [
            "process_block",
            "hash_update",
            "compute",
            "run",
            "execute",
            "transform",
            "filter",
            "encode",
            "decode",
            "encrypt",
            "decrypt",
            "compress",
            "decompress",
        ];

        if let Ok(entries) = fs::read_dir(source_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                let ext = path
                    .extension()
                    .map(|e| e.to_string_lossy().to_string())
                    .unwrap_or_default();
                if !matches!(ext.as_str(), "c" | "cc" | "cpp" | "cxx" | "h" | "hpp") {
                    continue;
                }

                if let Ok(content) = fs::read_to_string(&path) {
                    let mut new_content = content.clone();
                    let mut modified = false;

                    for func_name in &key_functions {
                        // Look for function definitions with this name
                        let pattern = format!("void {}(", func_name);
                        if let Some(pos) = content.find(&pattern) {
                            // Check if FMV attr is already present
                            let before = &content[..pos];
                            if !before.ends_with(&fmv_attr) {
                                let replacement = format!("{} {}", fmv_attr, pattern);
                                new_content = new_content.replace(&pattern, &replacement);
                                modified = true;
                                variant_count += targets.len();
                            }
                        }

                        // Also check for: int func(, size_t func(, etc.
                        let alt_patterns = [
                            format!("int {}(", func_name),
                            format!("size_t {}(", func_name),
                            format!("uint64_t {}(", func_name),
                            format!("float {}(", func_name),
                            format!("double {}(", func_name),
                            format!("bool {}(", func_name),
                        ];
                        for alt in &alt_patterns {
                            if let Some(pos) = content.find(alt) {
                                let before = &content[..pos];
                                if !before.ends_with(&fmv_attr) && !before.contains("target_clones")
                                {
                                    let replacement = format!("{} {}", fmv_attr, alt);
                                    new_content = new_content.replace(alt, &replacement);
                                    modified = true;
                                    variant_count += targets.len();
                                }
                            }
                        }
                    }

                    if modified {
                        // Backup original
                        let backup = path.with_extension(format!("{}.bak", ext));
                        fs::copy(&path, &backup)?;
                        fs::write(&path, new_content)?;
                        if !self.keep_intermediates {
                            let _ = fs::remove_file(&backup);
                        }
                    }
                }
            }
        }

        Ok(variant_count)
    }

    /// Runs the full optimization pipeline for a project.
    pub fn optimize_project(
        &self,
        config: &DeepProjectConfig,
        build_dir: &Path,
        source_dir: &Path,
        output_binary: Option<&Path>,
    ) -> io::Result<DeepOptimizationReport> {
        let mut report = DeepOptimizationReport::new(config.id);
        let start = Instant::now();

        let opt_config = match &config.opt_config {
            Some(oc) => oc.clone(),
            None => return Ok(report),
        };

        // Step 1: Apply FMV annotations
        if opt_config.enable_fmv {
            let variants = self.apply_fmv(config, source_dir)?;
            report.fmv_applied = variants > 0;
            report.fmv_variant_count = variants;
            report.passes.push(DeepOptPass {
                name: "Function Multi-Versioning".to_string(),
                enabled: true,
                effect: format!("Created {} CPU-specific variants", variants),
                speedup_pct: Some(5.0),
                size_change_pct: Some(2.0),
            });
        }

        report.duration = start.elapsed();
        Ok(report)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DeepLtoConfig — LTO Configuration
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for Link-Time Optimization.
#[derive(Debug, Clone)]
pub struct DeepLtoConfig {
    /// Whether LTO is enabled.
    pub enabled: bool,
    /// LTO mode: "thin" or "full".
    pub mode: String,
    /// Number of parallel LTO jobs.
    pub jobs: usize,
    /// Path to the LTO cache directory.
    pub cache_dir: Option<PathBuf>,
    /// Whether to use new pass manager for LTO.
    pub use_new_pm: bool,
    /// Whether to run internalization pass.
    pub internalize: bool,
    /// Whether to emit summary index for ThinLTO.
    pub emit_summary: bool,
    /// Whether to split LTO into multiple backends.
    pub split_lto_unit: bool,
    /// Extra LTO-specific flags.
    pub extra_flags: Vec<String>,
}

impl Default for DeepLtoConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            mode: "thin".to_string(),
            jobs: 4,
            cache_dir: None,
            use_new_pm: true,
            internalize: true,
            emit_summary: true,
            split_lto_unit: true,
            extra_flags: Vec::new(),
        }
    }
}

impl DeepLtoConfig {
    /// Returns LTO-related compiler flags.
    pub fn compiler_flags(&self) -> Vec<String> {
        if !self.enabled {
            return Vec::new();
        }
        let mut flags = vec![format!("-flto={}", self.mode)];
        if self.emit_summary {
            flags.push("-flto-embed-bitcode=summary".to_string());
        }
        flags
    }

    /// Returns LTO-related linker flags.
    pub fn linker_flags(&self) -> Vec<String> {
        if !self.enabled {
            return Vec::new();
        }
        let mut flags = vec![format!("-flto={}", self.mode)];
        if self.jobs > 0 {
            flags.push(format!("-Wl,--thinlto-jobs={}", self.jobs));
        }
        if let Some(ref cache) = self.cache_dir {
            flags.push(format!("-Wl,--thinlto-cache-dir={}", cache.display()));
        }
        if self.use_new_pm {
            flags.push("-Wl,--lto-newpm-passes".to_string());
        }
        flags
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════════════════
// PROJECT CONFIGURATION FACTORIES
// ═══════════════════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════════════════

// ── LLVM/Clang ──────────────────────────────────────────────────────────────

/// Creates the deep project configuration for LLVM/Clang.
///
/// Supports CMake-based configuration with bootstrap (stage1/stage2) builds,
/// enabling PGO, LTO, and full toolchain bootstrapping on X86 targets.
pub fn llvm_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert(
        "LLVM_ENABLE_PROJECTS".to_string(),
        "clang;clang-tools-extra;lld;compiler-rt".to_string(),
    );
    cmake_vars.insert("LLVM_TARGETS_TO_BUILD".to_string(), "X86".to_string());
    cmake_vars.insert("LLVM_ENABLE_ASSERTIONS".to_string(), "OFF".to_string());
    cmake_vars.insert("LLVM_ENABLE_LIBCXX".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_LLD".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_ZLIB".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_ZSTD".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_TERMINFO".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_THREADS".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_EH".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_ENABLE_RTTI".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_BUILD_TOOLS".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_BUILD_UTILS".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_BUILD_EXAMPLES".to_string(), "OFF".to_string());
    cmake_vars.insert("LLVM_BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_BUILD_BENCHMARKS".to_string(), "OFF".to_string());
    cmake_vars.insert("LLVM_OPTIMIZED_TABLEGEN".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_USE_LINKER".to_string(), "lld".to_string());
    cmake_vars.insert(
        "LLVM_PARALLEL_COMPILE_JOBS".to_string(),
        num_cpus::get().to_string(),
    );
    cmake_vars.insert("LLVM_PARALLEL_LINK_JOBS".to_string(), "2".to_string());
    // X86-specific codegen options
    cmake_vars.insert("LLVM_X86_ASM_PARSER".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_X86_ASM_PRINTER".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_X86_DISASSEMBLER".to_string(), "ON".to_string());
    cmake_vars.insert("LLVM_X86_TARGET".to_string(), "ON".to_string());

    DeepProjectConfig::new(DeepProjectId::Llvm)
        .with_variant(DeepBuildVariant::Release)
        .cmake_var("CMAKE_BUILD_TYPE", "Release")
        .cmake_var("LLVM_ENABLE_LTO", "Thin")
        .cmake_var("LLVM_ENABLE_PGO", "OFF")
        .cflag("-march=x86-64-v3")
        .cflag("-mtune=znver4")
        .cflag("-O2")
        .cxxflag("-march=x86-64-v3")
        .cxxflag("-mtune=znver4")
        .cxxflag("-O2")
        .ldflag("-fuse-ld=lld")
        .with_simd(DeepSimdLevel::Avx2)
        .with_variant(DeepBuildVariant::Release)
}

/// Creates a bootstrap LLVM configuration (stage1/stage2).
pub fn llvm_bootstrap_config() -> DeepProjectConfig {
    let mut config = llvm_deep_config();
    config.supports_bootstrap = true;
    config.stage = DeepBuildStage::Stage1;
    // Bootstrap-specific CMake vars
    config
        .cmake_vars
        .insert("CLANG_ENABLE_BOOTSTRAP".to_string(), "ON".to_string());
    config
        .cmake_vars
        .insert("BOOTSTRAP_LLVM_ENABLE_LTO".to_string(), "Thin".to_string());
    config
        .cmake_vars
        .insert("BOOTSTRAP_LLVM_ENABLE_PGO".to_string(), "ON".to_string());
    config.cmake_vars.insert(
        "BOOTSTRAP_CMAKE_BUILD_TYPE".to_string(),
        "Release".to_string(),
    );
    config.cmake_vars.insert(
        "BOOTSTRAP_LLVM_PARALLEL_COMPILE_JOBS".to_string(),
        num_cpus::get().to_string(),
    );
    config
}

// ── Linux Kernel ────────────────────────────────────────────────────────────

/// Creates the deep project configuration for the Linux kernel.
///
/// Supports Kbuild with Kconfig-based configuration, architecture selection
/// (x86_64, i386), and kernel-specific compiler flags.
pub fn linux_kernel_deep_config() -> DeepProjectConfig {
    let mut config = DeepProjectConfig::new(DeepProjectId::LinuxKernel);
    config.build_system = DeepBuildSystem::Kbuild;
    config.version = "6.6".to_string();
    config.repo_url =
        "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git".to_string();
    config.source_subdir = "linux".to_string();
    config.variant = DeepBuildVariant::Release;

    // Kernel-specific Kconfig defines
    config.defines.push(("__KERNEL__".to_string(), None));
    config.defines.push(("MODULE".to_string(), None));
    config
        .defines
        .push(("CONFIG_X86_64".to_string(), Some("1".to_string())));
    config
        .defines
        .push(("CONFIG_X86".to_string(), Some("1".to_string())));
    config
        .defines
        .push(("CONFIG_CC_IS_CLANG".to_string(), Some("1".to_string())));

    // Kernel build flags
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-mtune=generic".to_string());
    config.cflags.push("-O2".to_string());
    config.cflags.push("-pipe".to_string());
    config.cflags.push("-fno-strict-aliasing".to_string());
    config.cflags.push("-fno-common".to_string());
    config.cflags.push("-fno-stack-protector".to_string());
    config.cflags.push("-fno-omit-frame-pointer".to_string());
    config.cflags.push("-fno-pic".to_string());
    config.cflags.push("-mno-sse".to_string());
    config.cflags.push("-mno-mmx".to_string());
    config.cflags.push("-mno-sse2".to_string());
    config.cflags.push("-mno-3dnow".to_string());
    config.cflags.push("-mcmodel=kernel".to_string());
    config.cflags.push("-mno-red-zone".to_string());

    // Linker flags for the kernel
    config.ldflags.push("--emit-relocs".to_string());
    config.ldflags.push("--build-id=sha1".to_string());
    config.ldflags.push("-z max-page-size=0x200000".to_string());

    config.simd_level = DeepSimdLevel::None; // Kernel uses no SIMD in most paths

    // Kernel test config
    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::ShellScript,
        test_command: "make -C tools/testing/selftests".to_string(),
        test_dir: PathBuf::from("linux"),
        timeout_secs: 3600,
        ..Default::default()
    });

    config
}

/// Creates a Linux kernel config for i386 (32-bit).
pub fn linux_kernel_i386_config() -> DeepProjectConfig {
    let mut config = linux_kernel_deep_config();
    config.defines.retain(|(k, _)| k != "CONFIG_X86_64");
    config
        .defines
        .push(("CONFIG_X86_32".to_string(), Some("1".to_string())));
    config.cflags.retain(|f| !f.starts_with("-mcmodel="));
    config.cflags.push("-m32".to_string());
    config.cflags.push("-march=i686".to_string());
    config.ldflags.push("-m elf_i386".to_string());
    config
}

// ── Qt Framework ────────────────────────────────────────────────────────────

/// Creates the deep project configuration for the Qt framework.
///
/// Supports CMake and qmake configuration, platform plugins, widget/GUI modules,
/// and OpenGL integration on X86 targets.
pub fn qt_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert(
        "CMAKE_PREFIX_PATH".to_string(),
        "/usr/lib/x86_64-linux-gnu/cmake".to_string(),
    );
    cmake_vars.insert("QT_BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("QT_BUILD_EXAMPLES".to_string(), "OFF".to_string());
    cmake_vars.insert("QT_BUILD_BENCHMARKS".to_string(), "OFF".to_string());
    cmake_vars.insert("QT_FEATURE_gui".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_widgets".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_opengl".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_network".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_sql".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_xml".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_concurrent".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_dbus".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_testlib".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_printsupport".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_svg".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_imageformatplugin".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_system_zlib".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_system_png".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_system_jpeg".to_string(), "ON".to_string());
    cmake_vars.insert("QT_FEATURE_xcb".to_string(), "ON".to_string());
    cmake_vars.insert("QT_QPA_DEFAULT_PLATFORM".to_string(), "xcb".to_string());
    // X86-specific SIMD for Qt GUI
    cmake_vars.insert("QT_ENABLE_SSE2".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_SSE3".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_SSSE3".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_SSE4_1".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_SSE4_2".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_AVX".to_string(), "ON".to_string());
    cmake_vars.insert("QT_ENABLE_AVX2".to_string(), "ON".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::Qt);
    config.version = "6.7".to_string();
    config.repo_url = "https://code.qt.io/qt/qt5.git".to_string();
    config.source_subdir = "qt".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-fPIC".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j4".to_string(),
        ..Default::default()
    });

    config
}

// ── Boost C++ Libraries ─────────────────────────────────────────────────────

/// Creates the deep project configuration for Boost C++ Libraries.
///
/// Supports b2 build system, library selection, address-model (32/64-bit),
/// and instruction-set targeting on X86.
pub fn boost_deep_config() -> DeepProjectConfig {
    let mut config = DeepProjectConfig::new(DeepProjectId::Boost);
    config.version = "1.85.0".to_string();
    config.repo_url = "https://github.com/boostorg/boost.git".to_string();
    config.source_subdir = "boost".to_string();
    config.build_system = DeepBuildSystem::BoostBuild;
    config.variant = DeepBuildVariant::Release;

    // b2 toolset and variant settings
    config.meson_options.push("toolset=clang".to_string());
    config.meson_options.push("variant=release".to_string());
    config.meson_options.push("link=shared".to_string());
    config.meson_options.push("threading=multi".to_string());
    config.meson_options.push("runtime-link=shared".to_string());
    config.meson_options.push("address-model=64".to_string());
    config
        .meson_options
        .push("instruction-set=x86-64-v3".to_string());
    config.meson_options.push("cxxflags=-std=c++17".to_string());
    config
        .meson_options
        .push("cxxflags=-march=x86-64-v3".to_string());
    config
        .meson_options
        .push("cxxflags=-mtune=generic".to_string());

    // Boost libraries to build (commonly used subset)
    config.meson_options.push("--with-atomic".to_string());
    config.meson_options.push("--with-chrono".to_string());
    config.meson_options.push("--with-container".to_string());
    config.meson_options.push("--with-context".to_string());
    config.meson_options.push("--with-coroutine".to_string());
    config.meson_options.push("--with-date_time".to_string());
    config.meson_options.push("--with-exception".to_string());
    config.meson_options.push("--with-filesystem".to_string());
    config.meson_options.push("--with-graph".to_string());
    config.meson_options.push("--with-iostreams".to_string());
    config.meson_options.push("--with-json".to_string());
    config.meson_options.push("--with-locale".to_string());
    config.meson_options.push("--with-log".to_string());
    config.meson_options.push("--with-math".to_string());
    config
        .meson_options
        .push("--with-program_options".to_string());
    config.meson_options.push("--with-random".to_string());
    config.meson_options.push("--with-regex".to_string());
    config
        .meson_options
        .push("--with-serialization".to_string());
    config.meson_options.push("--with-system".to_string());
    config.meson_options.push("--with-test".to_string());
    config.meson_options.push("--with-thread".to_string());
    config.meson_options.push("--with-timer".to_string());
    config.meson_options.push("--with-type_erasure".to_string());
    config.meson_options.push("--with-url".to_string());
    config.meson_options.push("--with-wave".to_string());

    // X86-specific defines
    config.defines.push(("BOOST_USE_SSE2".to_string(), None));
    config.defines.push(("BOOST_USE_SSSE3".to_string(), None));
    config.defines.push(("BOOST_USE_SSE4_1".to_string(), None));
    config.defines.push(("BOOST_USE_AVX".to_string(), None));
    config.defines.push(("BOOST_USE_AVX2".to_string(), None));

    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.depends_on(DeepProjectId::Abseil); // Optional: Boost.URL uses Abseil

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::BoostTest,
        test_command: "./b2 test".to_string(),
        test_dir: PathBuf::from("boost"),
        ..Default::default()
    });

    config
}

// ── FFmpeg ──────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for FFmpeg.
///
/// Supports configure-script-based builds, codec selection, and
/// SIMD acceleration (MMX/SSE/AVX/AVX2/AVX-512) on X86 targets.
pub fn ffmpeg_deep_config() -> DeepProjectConfig {
    let mut config = DeepProjectConfig::new(DeepProjectId::Ffmpeg);
    config.version = "7.0".to_string();
    config.repo_url = "https://git.ffmpeg.org/ffmpeg.git".to_string();
    config.source_subdir = "ffmpeg".to_string();
    config.build_system = DeepBuildSystem::Autotools;
    config.variant = DeepBuildVariant::Release;

    // Configure flags for FFmpeg
    config.configure_flags.push("--cc=clang".to_string());
    config.configure_flags.push("--cxx=clang++".to_string());
    config.configure_flags.push("--enable-gpl".to_string());
    config.configure_flags.push("--enable-version3".to_string());
    config.configure_flags.push("--enable-nonfree".to_string());
    config.configure_flags.push("--enable-shared".to_string());
    config.configure_flags.push("--enable-static".to_string());
    config.configure_flags.push("--enable-pic".to_string());
    config.configure_flags.push("--enable-lto".to_string());
    config
        .configure_flags
        .push("--enable-optimizations".to_string());
    config
        .configure_flags
        .push("--enable-runtime-cpudetect".to_string());

    // Codec selection
    config
        .configure_flags
        .push("--enable-encoder=mpeg4".to_string());
    config
        .configure_flags
        .push("--enable-decoder=h264".to_string());
    config
        .configure_flags
        .push("--enable-decoder=hevc".to_string());
    config
        .configure_flags
        .push("--enable-decoder=av1".to_string());
    config
        .configure_flags
        .push("--enable-encoder=libx264".to_string());
    config
        .configure_flags
        .push("--enable-encoder=libx265".to_string());
    config
        .configure_flags
        .push("--enable-decoder=vp9".to_string());
    config
        .configure_flags
        .push("--enable-decoder=vp8".to_string());
    config
        .configure_flags
        .push("--enable-encoder=aac".to_string());
    config
        .configure_flags
        .push("--enable-decoder=mp3".to_string());
    config
        .configure_flags
        .push("--enable-decoder=opus".to_string());
    config
        .configure_flags
        .push("--enable-decoder=flac".to_string());
    config
        .configure_flags
        .push("--enable-decoder=vorbis".to_string());

    // X86 SIMD flags
    config.configure_flags.push("--enable-mmx".to_string());
    config.configure_flags.push("--enable-sse".to_string());
    config.configure_flags.push("--enable-sse2".to_string());
    config.configure_flags.push("--enable-sse3".to_string());
    config.configure_flags.push("--enable-ssse3".to_string());
    config.configure_flags.push("--enable-sse4".to_string());
    config.configure_flags.push("--enable-sse42".to_string());
    config.configure_flags.push("--enable-avx".to_string());
    config.configure_flags.push("--enable-avx2".to_string());
    config.configure_flags.push("--enable-avx512".to_string());
    config.configure_flags.push("--enable-x86asm".to_string());

    // Extra compiler flags
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-mtune=znver4".to_string());
    config.cflags.push("-O3".to_string());
    config.cflags.push("-fomit-frame-pointer".to_string());
    config.ldflags.push("-fuse-ld=lld".to_string());

    config.simd_level = DeepSimdLevel::Avx512Full;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::MakeCheck,
        test_command: "make fate".to_string(),
        test_dir: PathBuf::from("ffmpeg"),
        timeout_secs: 3600,
        ..Default::default()
    });

    config
}

// ── OpenCV ──────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for OpenCV.
///
/// Supports CMake-based configuration with SIMD optimizations, CUDA interop,
/// and OpenCL acceleration on X86 targets.
pub fn opencv_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("BUILD_SHARED_LIBS".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_PERF_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_EXAMPLES".to_string(), "OFF".to_string());
    cmake_vars.insert("BUILD_opencv_apps".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_python3".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_JAVA".to_string(), "OFF".to_string());
    cmake_vars.insert("BUILD_opencv_world".to_string(), "ON".to_string());

    // Core modules
    cmake_vars.insert("BUILD_opencv_core".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_imgproc".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_imgcodecs".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_videoio".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_highgui".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_video".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_calib3d".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_features2d".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_objdetect".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_dnn".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_ml".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_flann".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_photo".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_stitching".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_opencv_gapi".to_string(), "ON".to_string());

    // SIMD optimizations for X86
    cmake_vars.insert("CPU_BASELINE".to_string(), "SSE4_2".to_string());
    cmake_vars.insert(
        "CPU_DISPATCH".to_string(),
        "AVX;AVX2;AVX512_SKX".to_string(),
    );
    cmake_vars.insert("CV_ENABLE_INTRINSICS".to_string(), "ON".to_string());
    cmake_vars.insert("CV_DISABLE_OPTIMIZATION".to_string(), "OFF".to_string());

    // Acceleration backends
    cmake_vars.insert("WITH_OPENCL".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_OPENGL".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_CUDA".to_string(), "OFF".to_string()); // Disable by default, requires CUDA SDK
    cmake_vars.insert("WITH_OPENMP".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_TBB".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_IPP".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_EIGEN".to_string(), "ON".to_string());

    // Image codec support
    cmake_vars.insert("WITH_JPEG".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_PNG".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_TIFF".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_WEBP".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_JASPER".to_string(), "OFF".to_string());
    cmake_vars.insert("WITH_OPENEXR".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_GDAL".to_string(), "OFF".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::OpenCV);
    config.version = "4.10.0".to_string();
    config.repo_url = "https://github.com/opencv/opencv.git".to_string();
    config.source_subdir = "opencv".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-mtune=generic".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cxxflags.push("-std=c++17".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j8".to_string(),
        ..Default::default()
    });

    let mut bench = DeepBenchmarkConfig::default();
    bench.command = "./bin/opencv_perf_core".to_string();
    let mut tc = config.test_config.take().unwrap_or_default();
    tc.benchmark_config = Some(bench);
    config.test_config = Some(tc);

    config
}

// ── TensorFlow Lite ─────────────────────────────────────────────────────────

/// Creates the deep project configuration for TensorFlow Lite.
///
/// Supports CMake-based configuration with XNNPACK delegate, NEON-to-SSE
/// mapping for X86 targets, and optional GPU delegation.
pub fn tensorflow_lite_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("TFLITE_ENABLE_XNNPACK".to_string(), "ON".to_string());
    cmake_vars.insert("TFLITE_ENABLE_GPU".to_string(), "OFF".to_string());
    cmake_vars.insert("TFLITE_ENABLE_RPC".to_string(), "OFF".to_string());
    cmake_vars.insert("TFLITE_ENABLE_INSTALL".to_string(), "ON".to_string());
    cmake_vars.insert(
        "TFLITE_ENABLE_RUNTIME_VERBOSE_LOGS".to_string(),
        "OFF".to_string(),
    );
    cmake_vars.insert("TFLITE_KERNEL_TEST".to_string(), "OFF".to_string());
    cmake_vars.insert("BUILD_TESTING".to_string(), "ON".to_string());
    // XNNPACK config
    cmake_vars.insert("XNNPACK_ENABLE_AVX512F".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_AVX512SKX".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_AVX2".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_AVX".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_SSE4_1".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_SSE2".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_ASSEMBLY".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_ENABLE_JIT".to_string(), "ON".to_string());
    cmake_vars.insert("XNNPACK_BUILD_TESTS".to_string(), "OFF".to_string());
    cmake_vars.insert("XNNPACK_BUILD_BENCHMARKS".to_string(), "OFF".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::TensorFlowLite);
    config.version = "2.16".to_string();
    config.repo_url = "https://github.com/tensorflow/tensorflow.git".to_string();
    config.source_subdir = "tensorflow".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    // TFLite uses C++17
    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cxxflags.push("-O3".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());

    config.simd_level = DeepSimdLevel::Avx2;

    config.depends_on(DeepProjectId::Abseil);
    config.depends_on(DeepProjectId::Protobuf);

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure".to_string(),
        ..Default::default()
    });

    config
}

// ── Protocol Buffers (Protobuf) ─────────────────────────────────────────────

/// Creates the deep project configuration for Protocol Buffers.
///
/// Supports CMake configuration with the protoc compiler, well-known types,
/// and C++ code generation for X86 targets.
pub fn protobuf_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("protobuf_BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("protobuf_BUILD_SHARED_LIBS".to_string(), "ON".to_string());
    cmake_vars.insert(
        "protobuf_BUILD_PROTOC_BINARIES".to_string(),
        "ON".to_string(),
    );
    cmake_vars.insert("protobuf_BUILD_EXAMPLES".to_string(), "OFF".to_string());
    cmake_vars.insert("protobuf_INSTALL".to_string(), "ON".to_string());
    cmake_vars.insert("protobuf_ABSL_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert("protobuf_USE_EXTERNAL_GTEST".to_string(), "ON".to_string());
    cmake_vars.insert("protobuf_WITH_ZLIB".to_string(), "ON".to_string());
    cmake_vars.insert("protobuf_DEBUG_POSTFIX".to_string(), "".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::Protobuf);
    config.version = "27.0".to_string();
    config.repo_url = "https://github.com/protocolbuffers/protobuf.git".to_string();
    config.source_subdir = "protobuf".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.simd_level = DeepSimdLevel::Sse42;

    config.depends_on(DeepProjectId::Abseil);

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j4".to_string(),
        ..Default::default()
    });

    config
}

// ── gRPC ────────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for gRPC.
///
/// Supports CMake-based build, protobuf plugin integration, SSL/TLS backend
/// selection (OpenSSL/BoringSSL), and C++ codegen on X86 targets.
pub fn grpc_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("gRPC_INSTALL".to_string(), "ON".to_string());
    cmake_vars.insert("gRPC_BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert(
        "gRPC_BUILD_GRPCPP_OTEL_PLUGIN".to_string(),
        "OFF".to_string(),
    );
    cmake_vars.insert("gRPC_SSL_PROVIDER".to_string(), "module".to_string()); // Use BoringSSL
    cmake_vars.insert("gRPC_ZLIB_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert("gRPC_CARES_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert("gRPC_RE2_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert("gRPC_ABSL_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert("gRPC_PROTOBUF_PROVIDER".to_string(), "module".to_string());
    cmake_vars.insert(
        "gRPC_PROTOBUF_PACKAGE_TYPE".to_string(),
        "MODULE".to_string(),
    );
    cmake_vars.insert("gRPC_USE_PROTO_LITE".to_string(), "OFF".to_string());
    cmake_vars.insert("gRPC_BUILD_CODEGEN".to_string(), "ON".to_string());
    cmake_vars.insert("gRPC_BUILD_CSHARP_EXT".to_string(), "OFF".to_string());
    cmake_vars.insert(
        "gRPC_BUILD_GRPC_PYTHON_PLUGIN".to_string(),
        "OFF".to_string(),
    );
    cmake_vars.insert("gRPC_BUILD_GRPC_RUBY_PLUGIN".to_string(), "OFF".to_string());
    cmake_vars.insert("gRPC_BUILD_GRPC_PHP_PLUGIN".to_string(), "OFF".to_string());
    cmake_vars.insert("gRPC_BUILD_GRPC_NODE_PLUGIN".to_string(), "OFF".to_string());
    cmake_vars.insert(
        "gRPC_BUILD_GRPC_OBJECTIVE_C_PLUGIN".to_string(),
        "OFF".to_string(),
    );

    let mut config = DeepProjectConfig::new(DeepProjectId::Grpc);
    config.version = "1.64".to_string();
    config.repo_url = "https://github.com/grpc/grpc.git".to_string();
    config.source_subdir = "grpc".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.simd_level = DeepSimdLevel::Sse42;

    config.depends_on(DeepProjectId::Abseil);
    config.depends_on(DeepProjectId::Protobuf);

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j4".to_string(),
        timeout_secs: 1800,
        ..Default::default()
    });

    config
}

// ── Abseil ──────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for Abseil C++ Libraries.
///
/// Requires C++17, provides foundational C++ library components used by many
/// other projects (Protobuf, gRPC, TensorFlow, etc.).
pub fn abseil_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("ABSL_BUILD_TESTING".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_BUILD_TEST_HELPERS".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_USE_EXTERNAL_GOOGLETEST".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_ENABLE_INSTALL".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_PROPAGATE_CXX_STD".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_BUILD_SHARED_LIBS".to_string(), "ON".to_string());
    cmake_vars.insert("ABSL_FIND_GOOGLETEST".to_string(), "ON".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "17".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD_REQUIRED".to_string(), "ON".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::Abseil);
    config.version = "20240116.2".to_string();
    config.repo_url = "https://github.com/abseil/abseil-cpp.git".to_string();
    config.source_subdir = "abseil-cpp".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cxxflags.push("-DNDEBUG".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.simd_level = DeepSimdLevel::Sse42;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j8".to_string(),
        timeout_secs: 1800,
        ..Default::default()
    });

    config
}

// ── LevelDB ─────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for LevelDB.
///
/// Supports CMake-based build with optional Snappy compression and CRC32C
/// hardware acceleration on X86 targets.
pub fn leveldb_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("LEVELDB_BUILD_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("LEVELDB_BUILD_BENCHMARKS".to_string(), "ON".to_string());
    cmake_vars.insert("LEVELDB_INSTALL".to_string(), "ON".to_string());
    cmake_vars.insert("HAVE_SNAPPY".to_string(), "ON".to_string());
    cmake_vars.insert("HAVE_CRC32C".to_string(), "ON".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "17".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD_REQUIRED".to_string(), "ON".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::LevelDb);
    config.version = "1.23".to_string();
    config.repo_url = "https://github.com/google/leveldb.git".to_string();
    config.source_subdir = "leveldb".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-O2".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-O2".to_string());

    // Enable hardware CRC32C on X86
    config.cflags.push("-msse4.2".to_string());
    config.cxxflags.push("-msse4.2".to_string());
    config.simd_level = DeepSimdLevel::Sse42;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure".to_string(),
        ..Default::default()
    });

    config
}

// ── RocksDB ─────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for RocksDB.
///
/// Supports CMake-based build with multiple compression backends (Zlib, Zstd,
/// LZ4, Snappy, Bzip2), SIMD CRC32C on X86, and extensive benchmarking.
pub fn rocksdb_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("WITH_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_TOOLS".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_BENCHMARK_TOOLS".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_CORE_TOOLS".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_GFLAGS".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_SNAPPY".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_ZLIB".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_BZIP2".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_LZ4".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_ZSTD".to_string(), "ON".to_string());
    cmake_vars.insert("WITH_TBB".to_string(), "OFF".to_string());
    cmake_vars.insert("WITH_NUMA".to_string(), "ON".to_string());
    cmake_vars.insert("ROCKSDB_BUILD_SHARED".to_string(), "ON".to_string());
    cmake_vars.insert("FAIL_ON_WARNINGS".to_string(), "OFF".to_string());
    cmake_vars.insert("USE_RTTI".to_string(), "ON".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "17".to_string());
    // X86-specific optimizations
    cmake_vars.insert("PORTABLE".to_string(), "OFF".to_string()); // Enable native optimizations
    cmake_vars.insert("FORCE_SSE42".to_string(), "ON".to_string());
    cmake_vars.insert("USE_SSE".to_string(), "ON".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::RocksDb);
    config.version = "9.3".to_string();
    config.repo_url = "https://github.com/facebook/rocksdb.git".to_string();
    config.source_subdir = "rocksdb".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=generic".to_string());
    config.cxxflags.push("-O2".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-O2".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j8".to_string(),
        timeout_secs: 3600,
        ..Default::default()
    });

    let mut bench = DeepBenchmarkConfig::default();
    bench.command = "./db_bench --benchmarks=fillseq,readrandom".to_string();
    let mut tc = config.test_config.take().unwrap_or_default();
    tc.benchmark_config = Some(bench);
    config.test_config = Some(tc);

    config
}

// ── DuckDB ──────────────────────────────────────────────────────────────────

/// Creates the deep project configuration for DuckDB.
///
/// Supports CMake-based build with vectorized execution engine, SIMD-accelerated
/// operations on X86 targets, and optional extension builds.
pub fn duckdb_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("BUILD_UNITTESTS".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_SHELL".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_BENCHMARK".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_EXTENSIONS".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_PARQUET_EXTENSION".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_JSON_EXTENSION".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_HTTPFS_EXTENSION".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_FTS_EXTENSION".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_ICU_EXTENSION".to_string(), "OFF".to_string());
    cmake_vars.insert("BUILD_TPCH_EXTENSION".to_string(), "ON".to_string());
    cmake_vars.insert("BUILD_TPCDS_EXTENSION".to_string(), "OFF".to_string());
    cmake_vars.insert("BUILD_VISUALIZER_EXTENSION".to_string(), "OFF".to_string());
    cmake_vars.insert("DISABLE_UNITY".to_string(), "ON".to_string()); // Unity builds cause issues
    cmake_vars.insert("ENABLE_SANITIZER".to_string(), "OFF".to_string());
    cmake_vars.insert("FORCE_COLORED_OUTPUT".to_string(), "ON".to_string());
    // Vectorized execution (DuckDB's core feature)
    cmake_vars.insert("ENABLE_VECTORIZED_EXECUTION".to_string(), "ON".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "17".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::DuckDb);
    config.version = "1.0".to_string();
    config.repo_url = "https://github.com/duckdb/duckdb.git".to_string();
    config.source_subdir = "duckdb".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    // DuckDB benefits heavily from AVX2 for vectorized operations
    config.cxxflags.push("-std=c++17".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=znver4".to_string());
    config.cxxflags.push("-O3".to_string());
    config.cxxflags.push("-funroll-loops".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-O3".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j8".to_string(),
        timeout_secs: 7200, // DuckDB tests can be lengthy
        ..Default::default()
    });

    config
}

// ── ClickHouse ──────────────────────────────────────────────────────────────

/// Creates the deep project configuration for ClickHouse.
///
/// Supports CMake-based build with SIMD-accelerated hash tables, columnar
/// compression, and parallel query execution on X86 targets.
pub fn clickhouse_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("ENABLE_TESTS".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_BENCHMARKS".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_SERVER".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_CLIENT".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_LOCAL".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_BENCHMARK".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_KEEPER".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_COMPRESSOR".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_CLICKHOUSE_FORMAT".to_string(), "ON".to_string());
    cmake_vars.insert(
        "ENABLE_CLICKHOUSE_ODBC_BRIDGE".to_string(),
        "OFF".to_string(),
    );
    cmake_vars.insert(
        "ENABLE_CLICKHOUSE_LIBRARY_BRIDGE".to_string(),
        "OFF".to_string(),
    );
    cmake_vars.insert("ENABLE_JEMALLOC".to_string(), "ON".to_string());
    cmake_vars.insert("USE_STATIC_LIBRARIES".to_string(), "OFF".to_string());
    cmake_vars.insert("ENABLE_MULTITARGET_CODE".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_SSE42".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_AVX".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_AVX2".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_AVX512".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_BMI".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_POPCNT".to_string(), "ON".to_string());
    // Compression algorithms
    cmake_vars.insert("ENABLE_LZ4".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_ZSTD".to_string(), "ON".to_string());
    cmake_vars.insert("ENABLE_BROTLI".to_string(), "ON".to_string());
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "23".to_string()); // ClickHouse uses C++23

    let mut config = DeepProjectConfig::new(DeepProjectId::ClickHouse);
    config.version = "24.6".to_string();
    config.repo_url = "https://github.com/ClickHouse/ClickHouse.git".to_string();
    config.source_subdir = "ClickHouse".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    // ClickHouse is very performance-sensitive; use aggressive optimization
    config.cxxflags.push("-std=c++23".to_string());
    config.cxxflags.push("-march=x86-64-v4".to_string());
    config.cxxflags.push("-mtune=znver4".to_string());
    config.cxxflags.push("-O3".to_string());
    config.cxxflags.push("-funroll-loops".to_string());
    config.cxxflags.push("-fomit-frame-pointer".to_string());
    config.cflags.push("-march=x86-64-v4".to_string());
    config.cflags.push("-O3".to_string());
    config.simd_level = DeepSimdLevel::Avx512Full;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j8".to_string(),
        timeout_secs: 14400, // ClickHouse tests are very extensive
        ..Default::default()
    });

    config
}

// ── ScyllaDB / Seastar ──────────────────────────────────────────────────────

/// Creates the deep project configuration for ScyllaDB / Seastar.
///
/// Supports CMake-based build with DPDK integration, asynchronous I/O framework,
/// and vectorized operations on X86 targets.
pub fn scylladb_deep_config() -> DeepProjectConfig {
    let mut cmake_vars = HashMap::new();
    cmake_vars.insert("CMAKE_BUILD_TYPE".to_string(), "Release".to_string());
    cmake_vars.insert("Seastar_APPS".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_DEMOS".to_string(), "OFF".to_string());
    cmake_vars.insert("Seastar_TESTING".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_API_LEVEL".to_string(), "7".to_string());
    cmake_vars.insert("Seastar_DPDK".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_HWLOC".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_NUMA".to_string(), "ON".to_string());
    cmake_vars.insert(
        "Seastar_C_OR_CPP_DIALECT".to_string(),
        "gnu++20".to_string(),
    );
    cmake_vars.insert(
        "Seastar_CXX_FLAGS".to_string(),
        "-march=x86-64-v3".to_string(),
    );
    cmake_vars.insert(
        "Seastar_SCHEDULING_GROUPS_COUNT".to_string(),
        "16".to_string(),
    );
    cmake_vars.insert("Seastar_IO_URING".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_CPU_AFFINITY".to_string(), "ON".to_string());
    cmake_vars.insert("Seastar_EXCEPTION_HACK".to_string(), "OFF".to_string());
    cmake_vars.insert("Seastar_DEBUG_SHARED_PTR".to_string(), "OFF".to_string());
    cmake_vars.insert("Seastar_SANITIZE".to_string(), "OFF".to_string());
    cmake_vars.insert("Seastar_INSTRUMENT".to_string(), "OFF".to_string());
    cmake_vars.insert("Seastar_LD_FLAGS".to_string(), "-fuse-ld=lld".to_string());
    // Seastar reactor config
    cmake_vars.insert("Seastar_DEFAULT_NETWORK".to_string(), "stack".to_string());
    cmake_vars.insert(
        "Seastar_DEFAULT_ALLOCATOR".to_string(),
        "seastar".to_string(),
    );
    // DPDK integration
    cmake_vars.insert(
        "DPDK_INCLUDE_DIR".to_string(),
        "/usr/include/dpdk".to_string(),
    );
    cmake_vars.insert(
        "DPDK_LIB_DIR".to_string(),
        "/usr/lib/x86_64-linux-gnu/dpdk".to_string(),
    );
    cmake_vars.insert("CMAKE_CXX_STANDARD".to_string(), "20".to_string());

    let mut config = DeepProjectConfig::new(DeepProjectId::ScyllaDb);
    config.version = "6.0".to_string();
    config.repo_url = "https://github.com/scylladb/seastar.git".to_string();
    config.source_subdir = "seastar".to_string();
    config.build_system = DeepBuildSystem::Cmake;
    config.cmake_vars = cmake_vars;
    config.variant = DeepBuildVariant::Release;

    // Seastar uses C++20 with coroutines
    config.cxxflags.push("-std=c++20".to_string());
    config.cxxflags.push("-march=x86-64-v3".to_string());
    config.cxxflags.push("-mtune=znver4".to_string());
    config.cxxflags.push("-O3".to_string());
    config.cxxflags.push("-fcoroutines".to_string());
    config.cxxflags.push("-Wall".to_string());
    config.cflags.push("-march=x86-64-v3".to_string());
    config.cflags.push("-O3".to_string());
    config.simd_level = DeepSimdLevel::Avx2;

    config.test_config = Some(DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j16".to_string(),
        timeout_secs: 7200,
        ..Default::default()
    });

    config
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Execution Engine
// ═══════════════════════════════════════════════════════════════════════════════

/// Executes a full deep project build for a single project.
pub fn execute_deep_build(
    registry: &X86ProjectsDeep,
    project_id: DeepProjectId,
) -> io::Result<DeepBuildReport> {
    let config = registry.get_project(project_id).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            format!("Project not registered: {}", project_id.display_name()),
        )
    })?;

    let mut report = DeepBuildReport::new(project_id);
    report.start_time = Some(SystemTime::now());
    report.status = DeepBuildStatus::Configuring;

    let source_dir = registry.project_source_dir(project_id);
    let build_dir = registry.project_build_dir(project_id, config.stage);

    // Create output directories
    fs::create_dir_all(&build_dir)?;
    if let Some(ref test_config) = config.test_config {
        let test_dir = if test_config.test_dir.is_absolute() {
            test_config.test_dir.clone()
        } else {
            build_dir.join(&test_config.test_dir)
        };
        fs::create_dir_all(&test_dir)?;
    }

    // Apply patches
    if let Some(ref build_sys) = registry.build {
        if build_sys.auto_patch {
            let patched = build_sys.apply_patches(config, &source_dir)?;
            if patched > 0 && registry.verbose {
                eprintln!(
                    "Applied {} patches to {}",
                    patched,
                    project_id.display_name()
                );
            }
        }
    }

    // Configure
    let configure_result = configure_project(registry, config, &source_dir, &build_dir)?;
    if !configure_result.status.success() {
        report.status = DeepBuildStatus::Failed;
        report.diagnostics.push(DeepBuildDiagnostic {
            severity: X86DiagLevel::Error,
            message: format!(
                "Configuration failed: {}",
                String::from_utf8_lossy(&configure_result.stderr)
            ),
            file: None,
            line: None,
            column: None,
            build_step: "configure".to_string(),
            is_known_issue: false,
        });
        report.end_time = Some(SystemTime::now());
        return Ok(report);
    }

    // Build
    report.status = DeepBuildStatus::Building;
    let build_start = Instant::now();

    let build_result = build_project(registry, config, &build_dir)?;
    report.duration = build_start.elapsed();

    if !build_result.status.success() {
        report.status = DeepBuildStatus::Failed;
        report.tus_failed = 1; // Conservative estimate
        for line in String::from_utf8_lossy(&build_result.stderr).lines() {
            if line.contains("error:") {
                report.error_count += 1;
                report.diagnostics.push(DeepBuildDiagnostic {
                    severity: X86DiagLevel::Error,
                    message: line.to_string(),
                    file: None,
                    line: None,
                    column: None,
                    build_step: "compile".to_string(),
                    is_known_issue: false,
                });
            }
        }
    } else {
        report.status = DeepBuildStatus::Success;
    }

    // Generate compilation database
    if let Some(ref build_sys) = registry.build {
        match build_sys.generate_compilation_db(config, &build_dir) {
            Ok(cdb_path) => {
                report.cdb_path = Some(cdb_path);
            }
            Err(_) => { /* Non-fatal */ }
        }
    }

    // Run tests
    if report.is_success() {
        if let Some(ref test_sys) = registry.test {
            if let Some(ref tc) = config.test_config {
                if tc.run_after_build {
                    match test_sys.run_tests(config, &build_dir) {
                        Ok(test_report) => {
                            report.test_report = Some(test_report);
                        }
                        Err(e) => {
                            report.diagnostics.push(DeepBuildDiagnostic {
                                severity: X86DiagLevel::Warning,
                                message: format!("Test execution failed: {}", e),
                                file: None,
                                line: None,
                                column: None,
                                build_step: "test".to_string(),
                                is_known_issue: false,
                            });
                        }
                    }
                }
            }
        }
    }

    report.end_time = Some(SystemTime::now());
    Ok(report)
}

/// Configures a project with the appropriate build system.
fn configure_project(
    registry: &X86ProjectsDeep,
    config: &DeepProjectConfig,
    source_dir: &Path,
    build_dir: &Path,
) -> io::Result<std::process::Output> {
    match config.build_system {
        DeepBuildSystem::Cmake => configure_cmake_project(registry, config, source_dir, build_dir),
        DeepBuildSystem::Autotools => configure_autotools_project(config, source_dir),
        DeepBuildSystem::Meson => configure_meson_project(registry, config, source_dir, build_dir),
        DeepBuildSystem::Make => configure_make_project(config, source_dir),
        DeepBuildSystem::Kbuild => configure_kbuild_project(config, source_dir),
        DeepBuildSystem::Bazel => configure_bazel_project(config, source_dir),
        DeepBuildSystem::BoostBuild => configure_boost_build_project(config, source_dir),
        _ => Err(io::Error::new(
            io::ErrorKind::Unsupported,
            format!("Build system not implemented: {:?}", config.build_system),
        )),
    }
}

fn configure_cmake_project(
    registry: &X86ProjectsDeep,
    config: &DeepProjectConfig,
    source_dir: &Path,
    build_dir: &Path,
) -> io::Result<std::process::Output> {
    let mut cmd = Command::new("cmake");
    cmd.arg("-G").arg("Ninja"); // Use Ninja for faster builds
    cmd.arg("-S").arg(source_dir);
    cmd.arg("-B").arg(build_dir);

    // Build type
    if let Some(build_type) = config.variant.as_cmake_build_type() {
        cmd.arg(format!("-DCMAKE_BUILD_TYPE={}", build_type));
    }

    // Compiler settings
    cmd.arg(format!(
        "-DCMAKE_C_COMPILER={}",
        registry.env.get("CC").map_or("clang", |s| s)
    ));
    cmd.arg(format!(
        "-DCMAKE_CXX_COMPILER={}",
        registry.env.get("CXX").map_or("clang++", |s| s)
    ));

    // Global CMake vars
    for (key, value) in &registry.global_cmake_vars {
        cmd.arg(format!("-D{}={}", key, value));
    }

    // Project-specific CMake vars
    for (key, value) in &config.cmake_vars {
        cmd.arg(format!("-D{}={}", key, value));
    }

    // Extra flags
    let cflags = [&config.cflags[..], &registry.extra_cflags[..]]
        .concat()
        .join(" ");
    let cxxflags = [&config.cxxflags[..], &registry.extra_cxxflags[..]]
        .concat()
        .join(" ");
    let ldflags = [&config.ldflags[..], &registry.extra_ldflags[..]]
        .concat()
        .join(" ");

    if !cflags.is_empty() {
        cmd.arg(format!("-DCMAKE_C_FLAGS={}", cflags));
    }
    if !cxxflags.is_empty() {
        cmd.arg(format!("-DCMAKE_CXX_FLAGS={}", cxxflags));
    }
    if !ldflags.is_empty() {
        cmd.arg(format!("-DCMAKE_EXE_LINKER_FLAGS={}", ldflags));
        cmd.arg(format!("-DCMAKE_SHARED_LINKER_FLAGS={}", ldflags));
    }

    // Collect and merge environment variables
    let mut env_vars = registry.env.clone();
    for (key, value) in &config.env_overrides {
        env_vars.insert(key.clone(), value.clone());
    }
    for (key, value) in &env_vars {
        cmd.env(key, value);
    }

    cmd.output()
}

fn configure_autotools_project(
    config: &DeepProjectConfig,
    source_dir: &Path,
) -> io::Result<std::process::Output> {
    let configure_script = source_dir.join("configure");

    let mut cmd = if configure_script.exists() {
        Command::new(&configure_script)
    } else {
        // Try autoreconf first
        let autoreconf = Command::new("autoreconf")
            .arg("-fi")
            .current_dir(source_dir)
            .output();
        // Then run configure if available
        let script = source_dir.join("configure");
        if !script.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("configure script not found in {}", source_dir.display()),
            ));
        }
        Command::new(&script)
    };

    cmd.current_dir(source_dir);

    // Add all configure flags
    for flag in &config.configure_flags {
        if flag.contains(' ') {
            let parts: Vec<&str> = flag.splitn(2, ' ').collect();
            if parts.len() == 2 {
                cmd.arg(parts[0]).arg(parts[1]);
            }
        } else {
            cmd.arg(flag);
        }
    }

    // Add extra CFLAGS/CXXFLAGS
    let cflags = config.cflags.join(" ");
    let cxxflags = config.cxxflags.join(" ");
    let ldflags = config.ldflags.join(" ");
    if !cflags.is_empty() {
        cmd.env("CFLAGS", &cflags);
    }
    if !cxxflags.is_empty() {
        cmd.env("CXXFLAGS", &cxxflags);
    }
    if !ldflags.is_empty() {
        cmd.env("LDFLAGS", &ldflags);
    }

    cmd.output()
}

fn configure_meson_project(
    registry: &X86ProjectsDeep,
    config: &DeepProjectConfig,
    source_dir: &Path,
    build_dir: &Path,
) -> io::Result<std::process::Output> {
    let mut cmd = Command::new("meson");
    cmd.arg("setup");
    cmd.arg(build_dir);
    cmd.arg(source_dir);

    cmd.arg(format!("--buildtype={}", config.variant.as_str()));
    cmd.arg(format!(
        "--prefix={}",
        registry.project_install_dir(config.id).display()
    ));

    for option in &config.meson_options {
        cmd.arg(format!("-D{}", option));
    }

    let cflags = config.cflags.join(" ");
    let cxxflags = config.cxxflags.join(" ");
    if !cflags.is_empty() {
        cmd.env("CFLAGS", &cflags);
    }
    if !cxxflags.is_empty() {
        cmd.env("CXXFLAGS", &cxxflags);
    }

    cmd.output()
}

fn configure_make_project(
    config: &DeepProjectConfig,
    source_dir: &Path,
) -> io::Result<std::process::Output> {
    // For Make-only projects, just verify Makefile exists
    let makefile = source_dir.join("Makefile");
    if !makefile.exists() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("Makefile not found in {}", source_dir.display()),
        ));
    }
    // Return success — Make doesn't have a separate configure step
    let mut out = std::process::Output {
        status: std::process::ExitStatus::default(),
        stdout: Vec::new(),
        stderr: Vec::new(),
    };
    Ok(out)
}

fn configure_kbuild_project(
    config: &DeepProjectConfig,
    source_dir: &Path,
) -> io::Result<std::process::Output> {
    // Generate default config for x86_64
    let mut cmd = Command::new("make");
    cmd.arg("defconfig");
    cmd.arg(format!(
        "ARCH={}",
        if config.cflags.iter().any(|f| f == "-m32") {
            "i386"
        } else {
            "x86_64"
        }
    ));
    cmd.env("CC", "clang");
    cmd.env("LD", "ld.lld");
    cmd.current_dir(source_dir);
    cmd.output()
}

fn configure_bazel_project(
    config: &DeepProjectConfig,
    source_dir: &Path,
) -> io::Result<std::process::Output> {
    Command::new("bazel")
        .arg("sync")
        .current_dir(source_dir)
        .output()
}

fn configure_boost_build_project(
    config: &DeepProjectConfig,
    source_dir: &Path,
) -> io::Result<std::process::Output> {
    // Bootstrap b2
    let bootstrap = source_dir.join("bootstrap.sh");
    if bootstrap.exists() {
        Command::new(&bootstrap)
            .arg("--with-toolset=clang")
            .current_dir(source_dir)
            .output()
    } else {
        Ok(std::process::Output {
            status: std::process::ExitStatus::default(),
            stdout: Vec::new(),
            stderr: Vec::new(),
        })
    }
}

/// Builds a project using its configured build system.
fn build_project(
    registry: &X86ProjectsDeep,
    config: &DeepProjectConfig,
    build_dir: &Path,
) -> io::Result<std::process::Output> {
    match config.build_system {
        DeepBuildSystem::Cmake => {
            let mut cmd = Command::new("cmake");
            cmd.arg("--build").arg(build_dir);
            if registry.parallel_jobs > 0 {
                cmd.arg("-j").arg(registry.parallel_jobs.to_string());
            }
            cmd.output()
        }
        DeepBuildSystem::Make => {
            let mut cmd = Command::new("make");
            if registry.parallel_jobs > 0 {
                cmd.arg("-j").arg(registry.parallel_jobs.to_string());
            }
            cmd.current_dir(build_dir);
            cmd.output()
        }
        DeepBuildSystem::Autotools => {
            let mut cmd = Command::new("make");
            if registry.parallel_jobs > 0 {
                cmd.arg("-j").arg(registry.parallel_jobs.to_string());
            }
            cmd.current_dir(build_dir);
            cmd.output()
        }
        DeepBuildSystem::Meson => Command::new("meson")
            .arg("compile")
            .arg("-C")
            .arg(build_dir)
            .output(),
        DeepBuildSystem::Ninja => {
            let mut cmd = Command::new("ninja");
            if registry.parallel_jobs > 0 {
                cmd.arg("-j").arg(registry.parallel_jobs.to_string());
            }
            cmd.current_dir(build_dir);
            cmd.output()
        }
        DeepBuildSystem::Kbuild => {
            let mut cmd = Command::new("make");
            if registry.parallel_jobs > 0 {
                cmd.arg("-j").arg(registry.parallel_jobs.to_string());
            }
            cmd.arg("bzImage");
            cmd.arg("modules");
            cmd.env("CC", "clang");
            cmd.env("LD", "ld.lld");
            cmd.current_dir(build_dir);
            cmd.output()
        }
        DeepBuildSystem::Bazel => Command::new("bazel")
            .arg("build")
            .arg("//...")
            .current_dir(build_dir)
            .output(),
        DeepBuildSystem::BoostBuild => {
            let mut cmd = Command::new("./b2");
            if registry.parallel_jobs > 0 {
                cmd.arg(format!("-j{}", registry.parallel_jobs));
            }
            cmd.current_dir(build_dir);
            cmd.output()
        }
        _ => Err(io::Error::new(
            io::ErrorKind::Unsupported,
            format!("Build not implemented for {:?}", config.build_system),
        )),
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Batch Build Runner
// ═══════════════════════════════════════════════════════════════════════════════

/// Runs builds for all registered projects in dependency order.
pub fn build_all_projects(registry: &X86ProjectsDeep) -> Vec<DeepBuildReport> {
    let order = registry.build_order();
    let mut reports = Vec::new();

    for project_id in order {
        if let Some(ref build_sys) = registry.build {
            if build_sys.is_cancelled() {
                let mut report = DeepBuildReport::new(project_id);
                report.status = DeepBuildStatus::Cancelled;
                reports.push(report);
                continue;
            }
        }

        match execute_deep_build(registry, project_id) {
            Ok(report) => {
                let success = report.is_success();
                reports.push(report);
                if !success && registry.stop_on_error {
                    break;
                }
            }
            Err(e) => {
                let mut report = DeepBuildReport::new(project_id);
                report.status = DeepBuildStatus::Failed;
                report.diagnostics.push(DeepBuildDiagnostic {
                    severity: X86DiagLevel::Fatal,
                    message: format!("Build execution error: {}", e),
                    file: None,
                    line: None,
                    column: None,
                    build_step: "execute".to_string(),
                    is_known_issue: false,
                });
                reports.push(report);
                if registry.stop_on_error {
                    break;
                }
            }
        }
    }

    reports
}

/// Runs tests for all projects with successful builds.
pub fn test_all_projects(registry: &X86ProjectsDeep) -> BTreeMap<DeepProjectId, DeepTestReport> {
    let mut results = BTreeMap::new();

    for (project_id, report) in &registry.results {
        if !report.is_success() {
            continue;
        }

        let config = match registry.get_project(*project_id) {
            Some(c) => c,
            None => continue,
        };

        let build_dir = registry.project_build_dir(*project_id, config.stage);

        if let Some(ref test_sys) = registry.test {
            match test_sys.run_tests(config, &build_dir) {
                Ok(test_report) => {
                    results.insert(*project_id, test_report);
                }
                Err(e) => {
                    let mut tr = DeepTestReport::new(*project_id);
                    tr.raw_output = format!("Error: {}", e);
                    results.insert(*project_id, tr);
                }
            }
        }
    }

    results
}

// ═══════════════════════════════════════════════════════════════════════════════
// Utility Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Detects available host CPU features for build configuration.
pub fn detect_host_cpu_features() -> Vec<String> {
    let mut features = Vec::new();

    // Read /proc/cpuinfo on Linux
    if let Ok(content) = fs::read_to_string("/proc/cpuinfo") {
        if let Some(flags_line) = content.lines().find(|l| l.starts_with("flags")) {
            if let Some(flags_str) = flags_line.split(':').nth(1) {
                for flag in flags_str.split_whitespace() {
                    let upper = flag.to_uppercase();
                    if X86_CPU_FEATURES.iter().any(|f| f.to_uppercase() == upper) {
                        features.push(flag.to_lowercase());
                    }
                }
            }
        }
    }

    // Always include baseline x86-64 features
    if !features.iter().any(|f| f == "sse2") {
        features.push("sse2".to_string());
    }

    features.sort();
    features.dedup();
    features
}

/// Creates a consolidated build summary across all projects.
pub fn build_summary(reports: &[DeepBuildReport]) -> String {
    let total = reports.len();
    let successful = reports.iter().filter(|r| r.is_success()).count();
    let failed = reports
        .iter()
        .filter(|r| r.status == DeepBuildStatus::Failed)
        .count();
    let skipped = reports
        .iter()
        .filter(|r| r.status == DeepBuildStatus::Skipped)
        .count();
    let cancelled = reports
        .iter()
        .filter(|r| r.status == DeepBuildStatus::Cancelled)
        .count();

    let total_duration: Duration = reports.iter().map(|r| r.elapsed()).sum();
    let total_tus: usize = reports.iter().map(|r| r.tus_compiled).sum();
    let total_warnings: usize = reports.iter().map(|r| r.warning_count).sum();
    let total_errors: usize = reports.iter().map(|r| r.error_count).sum();

    format!(
        "Deep Build Summary\n\
         ===================\n\
         Projects: {} total, {} succeeded, {} failed, {} skipped, {} cancelled\n\
         Translation units: {} compiled\n\
         Warnings: {}\n\
         Errors: {}\n\
         Total time: {:.1}s\n",
        total,
        successful,
        failed,
        skipped,
        cancelled,
        total_tus,
        total_warnings,
        total_errors,
        total_duration.as_secs_f64(),
    )
}

/// Creates a test summary across all project test reports.
pub fn test_summary(test_results: &BTreeMap<DeepProjectId, DeepTestReport>) -> String {
    let mut total = 0usize;
    let mut passed = 0usize;
    let mut failed = 0usize;
    let mut skipped = 0usize;

    for report in test_results.values() {
        total += report.total;
        passed += report.passed;
        failed += report.failed;
        skipped += report.skipped;
    }

    format!(
        "Test Summary\n\
         =============\n\
         Projects tested: {}\n\
         Tests: {} total, {} passed, {} failed, {} skipped\n\
         Pass rate: {:.1}%\n",
        test_results.len(),
        total,
        passed,
        failed,
        skipped,
        if total > 0 {
            passed as f64 / total as f64 * 100.0
        } else {
            0.0
        },
    )
}

/// Returns the default optimization config for release builds.
pub fn default_release_opt_config() -> DeepOptConfig {
    DeepOptConfig {
        enable_thin_lto: true,
        enable_fmv: true,
        ..Default::default()
    }
}

/// Returns the aggressive optimization config for performance-critical builds.
pub fn aggressive_opt_config() -> DeepOptConfig {
    DeepOptConfig {
        enable_pgo: true,
        pgo_training_iters: 5,
        use_cs_pgo: true,
        enable_thin_lto: true,
        enable_bolt: true,
        bolt_mode: "hfsort+".to_string(),
        enable_fmv: true,
        ..Default::default()
    }
}

/// Generates a CMake preset JSON for all registered projects.
pub fn generate_cmake_presets(registry: &X86ProjectsDeep) -> String {
    let mut json = String::from("{\n  \"version\": 6,\n  \"configurePresets\": [\n");

    for (i, (id, config)) in registry.projects.iter().enumerate() {
        if i > 0 {
            json.push_str(",\n");
        }
        let build_dir = registry.project_build_dir(*id, config.stage);
        json.push_str(&format!(
            "    {{\n\
             \"name\": \"{}-{}\",\n\
             \"displayName\": \"{} {}\",\n\
             \"binaryDir\": \"{}\",\n\
             \"generator\": \"Ninja\",\n\
             \"cacheVariables\": {{\n\
             \"CMAKE_BUILD_TYPE\": \"{}\",\n\
             \"CMAKE_C_COMPILER\": \"clang\",\n\
             \"CMAKE_CXX_COMPILER\": \"clang++\"\n\
             }}\n\
             }}",
            id.as_str(),
            config.variant.as_str(),
            config.name,
            config.variant.as_str(),
            build_dir.display(),
            config.variant.as_cmake_build_type().unwrap_or("Release"),
        ));
    }

    json.push_str("\n  ]\n}\n");
    json
}

// ═══════════════════════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════════════════════
// Benchmark Configuration & Execution Framework
// ═══════════════════════════════════════════════════════════════════════════════

/// Extended benchmark configuration for detailed performance analysis.
#[derive(Debug, Clone)]
pub struct ExtendedBenchmarkConfig {
    /// The benchmark suite to run.
    pub suite: String,
    /// Number of iterations.
    pub iterations: usize,
    /// Minimum wall time per benchmark.
    pub min_time_secs: f64,
    /// Whether to warm up before measuring.
    pub warmup: bool,
    /// Number of warmup iterations.
    pub warmup_iterations: usize,
    /// Whether to pin to a specific CPU core.
    pub cpu_pinning: bool,
    /// CPU core to pin to.
    pub cpu_core: usize,
    /// Whether to drop caches before each benchmark.
    pub drop_caches: bool,
    /// Whether to use perf stat for hardware counters.
    pub use_perf: bool,
    /// Perf events to collect.
    pub perf_events: Vec<String>,
    /// Output format for benchmark results.
    pub output_format: BenchOutputFormat,
    /// Whether to compare against a baseline.
    pub compare_baseline: bool,
    /// Path to baseline results.
    pub baseline_path: Option<PathBuf>,
    /// Maximum acceptable regression percentage.
    pub max_regression_pct: f64,
}

impl Default for ExtendedBenchmarkConfig {
    fn default() -> Self {
        Self {
            suite: "default".to_string(),
            iterations: 10,
            min_time_secs: 1.0,
            warmup: true,
            warmup_iterations: 3,
            cpu_pinning: true,
            cpu_core: 0,
            drop_caches: false,
            use_perf: false,
            perf_events: vec![
                "cycles".into(),
                "instructions".into(),
                "cache-misses".into(),
            ],
            output_format: BenchOutputFormat::Json,
            compare_baseline: true,
            baseline_path: None,
            max_regression_pct: 5.0,
        }
    }
}

/// Benchmark output format options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BenchOutputFormat {
    Json,
    Csv,
    ConsoleTable,
    GoogleBenchmark,
}

/// Individual benchmark measurement.
#[derive(Debug, Clone)]
pub struct BenchMeasurement {
    pub name: String,
    pub iterations: usize,
    pub real_time_ns: u64,
    pub cpu_time_ns: u64,
    pub time_unit: String,
    pub bytes_per_second: u64,
    pub items_per_second: u64,
    pub counters: HashMap<String, f64>,
    pub label: Option<String>,
}

/// Executes an extended benchmark run for a binary.
pub fn run_extended_benchmark(
    binary: &Path,
    config: &ExtendedBenchmarkConfig,
) -> io::Result<Vec<BenchMeasurement>> {
    let mut measurements = Vec::new();

    // Verify the binary exists
    if !binary.exists() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("Benchmark binary not found: {}", binary.display()),
        ));
    }

    // Build the benchmark command
    let mut cmd = Command::new(binary);
    cmd.arg(format!("--benchmark_min_time={}", config.min_time_secs));
    cmd.arg(format!("--benchmark_repetitions={}", config.iterations));

    if config.warmup {
        cmd.arg("--benchmark_enable_random_interleaving=true");
    }

    match config.output_format {
        BenchOutputFormat::Json => {
            cmd.arg("--benchmark_format=json");
        }
        BenchOutputFormat::Csv => {
            cmd.arg("--benchmark_format=csv");
        }
        BenchOutputFormat::ConsoleTable => {
            cmd.arg("--benchmark_format=console");
        }
        BenchOutputFormat::GoogleBenchmark => {
            // Default format, no extra arg needed
        }
    }

    // Optional: perf stat wrapper
    if config.use_perf {
        let mut perf_cmd = Command::new("perf");
        perf_cmd.arg("stat");
        for event in &config.perf_events {
            perf_cmd.arg("-e").arg(event);
        }
        perf_cmd.arg(binary);
        let output = perf_cmd.output()?;
        // Parse perf output
        let stderr = String::from_utf8_lossy(&output.stderr);
        for line in stderr.lines() {
            if line.contains("time elapsed") {
                // Extract elapsed time
            }
        }
    }

    // Run the benchmark
    let output = cmd.output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse results
    for line in stdout.lines() {
        if line.starts_with("BM_") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 {
                let name = parts[0].to_string();
                let real_time: u64 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
                let cpu_time: u64 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
                measurements.push(BenchMeasurement {
                    name,
                    iterations: config.iterations,
                    real_time_ns: real_time,
                    cpu_time_ns: cpu_time,
                    time_unit: "ns".to_string(),
                    bytes_per_second: 0,
                    items_per_second: 0,
                    counters: HashMap::new(),
                    label: None,
                });
            }
        }
    }

    Ok(measurements)
}

/// Analyzes benchmark results and generates a report.
pub fn analyze_benchmark_results(
    name: &str,
    results: &[BenchMeasurement],
    baseline: Option<&[BenchMeasurement]>,
) -> String {
    let mut report = format!(
        "Benchmark Analysis: {}
",
        name
    );
    report.push_str(
        "==========================================

",
    );

    for result in results {
        let baseline_ns = baseline.and_then(|b| {
            b.iter()
                .find(|bm| bm.name == result.name)
                .map(|bm| bm.real_time_ns)
        });

        report.push_str(&format!("{}: {:>12} ns", result.name, result.real_time_ns));

        if let Some(base_ns) = baseline_ns {
            if base_ns > 0 {
                let delta_pct =
                    (result.real_time_ns as f64 - base_ns as f64) / base_ns as f64 * 100.0;
                let icon = if delta_pct > 5.0 {
                    "🔴 REGRESSION"
                } else if delta_pct < -1.0 {
                    "🟢 IMPROVEMENT"
                } else {
                    ""
                };
                report.push_str(&format!("  ({:+.1}% vs baseline) {}", delta_pct, icon));
            }
        }
        report.push('\n');
    }

    report
}

// ═══════════════════════════════════════════════════════════════════════════════
// Static Analysis Integration
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for static analysis during builds.
#[derive(Debug, Clone)]
pub struct StaticAnalysisConfig {
    /// Whether to run clang-tidy.
    pub run_clang_tidy: bool,
    /// Clang-tidy checks to enable.
    pub tidy_checks: Vec<String>,
    /// Whether to run clang static analyzer.
    pub run_scan_build: bool,
    /// Whether to run include-what-you-use.
    pub run_iwyu: bool,
    /// Whether to treat analysis warnings as errors.
    pub warnings_as_errors: bool,
    /// Files to analyze (glob patterns).
    pub include_patterns: Vec<String>,
    /// Files to exclude from analysis.
    pub exclude_patterns: Vec<String>,
    /// Output directory for analysis reports.
    pub output_dir: PathBuf,
    /// Maximum number of findings per check.
    pub max_findings_per_check: usize,
}

impl Default for StaticAnalysisConfig {
    fn default() -> Self {
        Self {
            run_clang_tidy: true,
            tidy_checks: vec![
                "clang-analyzer-*".into(),
                "bugprone-*".into(),
                "modernize-*".into(),
                "performance-*".into(),
                "readability-*".into(),
            ],
            run_scan_build: false,
            run_iwyu: false,
            warnings_as_errors: true,
            include_patterns: vec!["src/**/*.cpp".into(), "src/**/*.c".into()],
            exclude_patterns: vec!["**/test/**".into(), "**/third_party/**".into()],
            output_dir: PathBuf::from("analysis-reports"),
            max_findings_per_check: 50,
        }
    }
}

/// Result of a static analysis run.
#[derive(Debug, Clone)]
pub struct StaticAnalysisResult {
    pub total_findings: usize,
    pub errors: usize,
    pub warnings: usize,
    pub notes: usize,
    pub findings: Vec<StaticAnalysisFinding>,
    pub duration: Duration,
    pub tool_outputs: HashMap<String, String>,
}

/// A single finding from static analysis.
#[derive(Debug, Clone)]
pub struct StaticAnalysisFinding {
    pub tool: String,
    pub check_name: String,
    pub file: PathBuf,
    pub line: u32,
    pub column: u32,
    pub message: String,
    pub severity: FindingSeverity,
    pub fixit: Option<String>,
}

/// Severity of a static analysis finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FindingSeverity {
    Note,
    Warning,
    Error,
    Fatal,
}

/// Runs static analysis on a set of source files.
pub fn run_static_analysis(
    config: &StaticAnalysisConfig,
    source_dir: &Path,
    build_dir: &Path,
) -> io::Result<StaticAnalysisResult> {
    let mut result = StaticAnalysisResult {
        total_findings: 0,
        errors: 0,
        warnings: 0,
        notes: 0,
        findings: Vec::new(),
        duration: Duration::ZERO,
        tool_outputs: HashMap::new(),
    };

    let start = Instant::now();
    fs::create_dir_all(&config.output_dir)?;

    if config.run_clang_tidy {
        let checks = config.tidy_checks.join(",");
        let tidy_output = config.output_dir.join("clang-tidy.txt");

        // Build the compilation database first
        let cdb = build_dir.join("compile_commands.json");
        if cdb.exists() {
            let output = Command::new("run-clang-tidy")
                .arg("-p")
                .arg(build_dir)
                .arg(&format!("-checks={}", checks))
                .arg(&format!("-export-fixes={}", tidy_output.display()))
                .arg("-j")
                .arg(num_cpus::get().to_string())
                .output()?;

            let stdout = String::from_utf8_lossy(&output.stdout);
            result
                .tool_outputs
                .insert("clang-tidy".to_string(), stdout.to_string());

            // Count findings
            for line in stdout.lines() {
                if line.contains("warning:") || line.contains("error:") {
                    result.total_findings += 1;
                    if line.contains("error:") {
                        result.errors += 1;
                    } else {
                        result.warnings += 1;
                    }
                }
            }
        }
    }

    if config.run_scan_build {
        let output = Command::new("scan-build")
            .arg("-o")
            .arg(&config.output_dir)
            .arg("cmake")
            .arg("--build")
            .arg(build_dir)
            .output()?;

        result.tool_outputs.insert(
            "scan-build".to_string(),
            String::from_utf8_lossy(&output.stdout).to_string(),
        );
    }

    if config.run_iwyu {
        let output = Command::new("include-what-you-use")
            .arg("-Xiwyu")
            .arg("--mapping_file=/usr/share/include-what-you-use/iwyu.gcc.imp")
            .arg("src/main.cpp")
            .output()?;

        result.tool_outputs.insert(
            "iwyu".to_string(),
            String::from_utf8_lossy(&output.stdout).to_string(),
        );
    }

    result.duration = start.elapsed();
    Ok(result)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Cross-Compilation Toolchain Database
// ═══════════════════════════════════════════════════════════════════════════════

/// Stub: detect system memory in MB.
pub fn detect_system_memory_mb() -> u64 {
    8192
}

/// Stub: X86 target operating system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86TargetOs {
    Linux,
    Windows,
    FreeBsd,
    Android,
    Darwin,
}

/// Stub: X86 data model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86DataModel {
    Lp64,
    Ilp32,
    Llp64,
}

/// Stub: X86 cross-compilation target configuration.
#[derive(Debug, Clone)]
pub struct X86CrossTarget {
    pub triple: String,
    pub cpu: String,
    pub os: X86TargetOs,
    pub abi: String,
    pub is_32bit: bool,
    pub data_model: X86DataModel,
    pub default_cflags: Vec<String>,
    pub default_ldflags: Vec<String>,
    pub min_features: Vec<String>,
    pub stack_alignment: u32,
    pub red_zone_size: u32,
    pub page_size: u32,
    pub default_pic: bool,
}

impl X86CrossTarget {
    pub fn x86_64_linux_gnu() -> Self {
        Self {
            triple: "x86_64-unknown-linux-gnu".into(),
            cpu: "x86-64".into(),
            os: X86TargetOs::Linux,
            abi: "gnu".into(),
            is_32bit: false,
            data_model: X86DataModel::Lp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec![],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 128,
            page_size: 4096,
            default_pic: true,
        }
    }

    pub fn i686_linux_gnu() -> Self {
        Self {
            triple: "i686-unknown-linux-gnu".into(),
            cpu: "i686".into(),
            os: X86TargetOs::Linux,
            abi: "gnu".into(),
            is_32bit: true,
            data_model: X86DataModel::Ilp32,
            default_cflags: vec!["-m32".into()],
            default_ldflags: vec![],
            min_features: vec!["mmx".into()],
            stack_alignment: 16,
            red_zone_size: 0,
            page_size: 4096,
            default_pic: true,
        }
    }

    pub fn x86_64_windows_msvc() -> Self {
        Self {
            triple: "x86_64-pc-windows-msvc".into(),
            cpu: "x86-64".into(),
            os: X86TargetOs::Windows,
            abi: "msvc".into(),
            is_32bit: false,
            data_model: X86DataModel::Llp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec!["-fuse-ld=lld".into()],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 0,
            page_size: 4096,
            default_pic: false,
        }
    }

    pub fn x86_64_darwin() -> Self {
        Self {
            triple: "x86_64-apple-darwin".into(),
            cpu: "x86-64".into(),
            os: X86TargetOs::Darwin,
            abi: "".into(),
            is_32bit: false,
            data_model: X86DataModel::Lp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec![],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 128,
            page_size: 4096,
            default_pic: true,
        }
    }
}

/// A database of pre-configured cross-compilation toolchains for X86 targets.
pub fn x86_toolchain_database() -> Vec<X86CrossTarget> {
    vec![
        X86CrossTarget::x86_64_linux_gnu(),
        X86CrossTarget::i686_linux_gnu(),
        X86CrossTarget::x86_64_windows_msvc(),
        X86CrossTarget::x86_64_darwin(),
        // Additional common targets
        X86CrossTarget {
            triple: "x86_64-unknown-linux-musl".to_string(),
            cpu: "x86-64".to_string(),
            os: X86TargetOs::Linux,
            abi: "musl".to_string(),
            is_32bit: false,
            data_model: X86DataModel::Lp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec!["-static".into()],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 128,
            page_size: 4096,
            default_pic: true,
        },
        X86CrossTarget {
            triple: "i686-unknown-linux-musl".to_string(),
            cpu: "i686".to_string(),
            os: X86TargetOs::Linux,
            abi: "musl".to_string(),
            is_32bit: true,
            data_model: X86DataModel::Ilp32,
            default_cflags: vec!["-m32".into()],
            default_ldflags: vec!["-static".into()],
            min_features: vec!["mmx".into()],
            stack_alignment: 16,
            red_zone_size: 0,
            page_size: 4096,
            default_pic: true,
        },
        X86CrossTarget {
            triple: "x86_64-pc-windows-gnu".to_string(),
            cpu: "x86-64".to_string(),
            os: X86TargetOs::Windows,
            abi: "gnu".to_string(),
            is_32bit: false,
            data_model: X86DataModel::Llp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec!["-fuse-ld=lld".into()],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 0,
            page_size: 4096,
            default_pic: false,
        },
        X86CrossTarget {
            triple: "x86_64-unknown-freebsd".to_string(),
            cpu: "x86-64".to_string(),
            os: X86TargetOs::FreeBsd,
            abi: "".to_string(),
            is_32bit: false,
            data_model: X86DataModel::Lp64,
            default_cflags: vec!["-m64".into()],
            default_ldflags: vec!["-fuse-ld=lld".into()],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 128,
            page_size: 4096,
            default_pic: true,
        },
        X86CrossTarget {
            triple: "x86_64-linux-android".to_string(),
            cpu: "x86-64".to_string(),
            os: X86TargetOs::Android,
            abi: "".to_string(),
            is_32bit: false,
            data_model: X86DataModel::Lp64,
            default_cflags: vec!["-m64".into(), "-fPIE".into()],
            default_ldflags: vec!["-fuse-ld=lld".into(), "-pie".into()],
            min_features: vec!["sse2".into()],
            stack_alignment: 16,
            red_zone_size: 128,
            page_size: 4096,
            default_pic: true,
        },
    ]
}

/// Finds a toolchain by triple.
pub fn find_toolchain(triple: &str) -> Option<X86CrossTarget> {
    x86_toolchain_database()
        .into_iter()
        .find(|t| t.triple == triple)
}

/// Lists all known toolchain triples.
pub fn known_triples() -> Vec<String> {
    x86_toolchain_database()
        .into_iter()
        .map(|t| t.triple)
        .collect()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Configuration Profiler
// ═══════════════════════════════════════════════════════════════════════════════

/// Profiles different build configurations to find the optimal one.
#[derive(Debug, Clone)]
pub struct BuildProfiler {
    pub project_id: DeepProjectId,
    pub configurations: Vec<ProfiledConfiguration>,
    pub best_config: Option<ProfiledConfiguration>,
}

/// A single profiled build configuration.
#[derive(Debug, Clone)]
pub struct ProfiledConfiguration {
    pub flags: Vec<String>,
    pub build_time_secs: f64,
    pub binary_size_bytes: u64,
    pub runtime_perf_ns_per_iter: u64,
    pub score: f64, // Composite score (higher is better)
}

impl BuildProfiler {
    pub fn new(project_id: DeepProjectId) -> Self {
        Self {
            project_id,
            configurations: Vec::new(),
            best_config: None,
        }
    }

    /// Adds a profiling result.
    pub fn add_result(
        &mut self,
        flags: &[String],
        build_time_secs: f64,
        binary_size_bytes: u64,
        runtime_ns: u64,
    ) {
        // Score: lower build time, smaller binary, and faster runtime are better.
        // Normalize and weight: 30% build time, 20% size, 50% performance.
        let score = 1.0 / (build_time_secs + 1.0) * 0.3
            + 1.0 / (binary_size_bytes as f64 / 1_000_000.0 + 1.0) * 0.2
            + 1.0 / (runtime_ns as f64 / 1_000_000.0 + 1.0) * 0.5;

        self.configurations.push(ProfiledConfiguration {
            flags: flags.to_vec(),
            build_time_secs,
            binary_size_bytes,
            runtime_perf_ns_per_iter: runtime_ns,
            score,
        });
    }

    /// Finds the best configuration by score.
    pub fn evaluate(&mut self) -> Option<&ProfiledConfiguration> {
        self.configurations.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        self.best_config = self.configurations.first().cloned();
        self.best_config.as_ref()
    }

    /// Generates a profiling report.
    pub fn report(&self) -> String {
        let mut r = format!(
            "Build Profiling Report: {}
",
            self.project_id.display_name()
        );
        r.push_str(
            "=============================================

",
        );
        r.push_str(&format!(
            "{:<4} {:<60} {:<10} {:<12} {:<12} {:<8}
",
            "Rank", "Flags", "Build(s)", "Size(MB)", "Runtime(ns)", "Score"
        ));
        r.push_str("----  ------------------------------------------------------------  ---------  ------------  ------------  -------
");

        for (i, config) in self.configurations.iter().enumerate() {
            let flags_str = config.flags.join(" ");
            let truncated = if flags_str.len() > 58 {
                format!("{}...", &flags_str[..55])
            } else {
                flags_str
            };
            r.push_str(&format!(
                "{:<4} {:<60} {:<10.1} {:<12.1} {:<12} {:<8.4}
",
                i + 1,
                truncated,
                config.build_time_secs,
                config.binary_size_bytes as f64 / 1_048_576.0,
                config.runtime_perf_ns_per_iter,
                config.score,
            ));
        }

        if let Some(ref best) = self.best_config {
            r.push_str(&format!(
                "
Best configuration: {}
",
                best.flags.join(" ")
            ));
        }
        r
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Extended Test Configurations for Sub-Projects
// ═══════════════════════════════════════════════════════════════════════════════

/// Collection of test configurations for common test scenarios.
pub fn standard_test_configs() -> Vec<DeepTestConfig> {
    vec![
        DeepTestConfig {
            run_after_build: true,
            test_framework: DeepTestFramework::Ctest,
            test_command: "ctest --output-on-failure -j4".to_string(),
            parallel: true,
            parallel_workers: 4,
            output_format: DeepTestOutputFormat::JunitXml,
            ..Default::default()
        },
        DeepTestConfig {
            run_after_build: true,
            test_framework: DeepTestFramework::GTest,
            test_command: "".to_string(), // GTest binaries discover themselves
            parallel: true,
            parallel_workers: 8,
            output_format: DeepTestOutputFormat::Json,
            ..Default::default()
        },
        DeepTestConfig {
            run_after_build: true,
            test_framework: DeepTestFramework::Catch2,
            test_command: "".to_string(),
            parallel: true,
            parallel_workers: 8,
            output_format: DeepTestOutputFormat::JunitXml,
            ..Default::default()
        },
    ]
}

/// Creates a default test config for CTest-based projects.
pub fn default_ctest_config() -> DeepTestConfig {
    DeepTestConfig {
        test_framework: DeepTestFramework::Ctest,
        test_command: "ctest --output-on-failure -j16".to_string(),
        test_dir: PathBuf::from("build"),
        run_after_build: true,
        ..Default::default()
    }
}

/// Creates a default test config for Google Test-based projects.
pub fn default_gtest_config() -> DeepTestConfig {
    DeepTestConfig {
        test_framework: DeepTestFramework::GTest,
        test_command: "".to_string(),
        test_dir: PathBuf::from("build"),
        run_after_build: true,
        output_format: DeepTestOutputFormat::Json,
        ..Default::default()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Build Report Export Formats
// ═══════════════════════════════════════════════════════════════════════════════

/// Exports build reports in various formats.
pub fn export_build_report(report: &DeepBuildReport, format: &str) -> String {
    match format {
        "json" => report.to_json(),
        "markdown" => {
            let mut md = format!(
                "# Build Report: {}

",
                report.project_id.display_name()
            );
            md.push_str(&format!(
                "- **Status**: {}
",
                report.status
            ));
            md.push_str(&format!(
                "- **TUs Compiled**: {}
",
                report.tus_compiled
            ));
            md.push_str(&format!(
                "- **TUs Failed**: {}
",
                report.tus_failed
            ));
            md.push_str(&format!(
                "- **Warnings**: {}
",
                report.warning_count
            ));
            md.push_str(&format!(
                "- **Errors**: {}
",
                report.error_count
            ));
            md.push_str(&format!(
                "- **Duration**: {:.1}s
",
                report.elapsed().as_secs_f64()
            ));
            md.push_str(&format!(
                "- **Output Size**: {} bytes
",
                report.output_size_bytes
            ));

            if !report.diagnostics.is_empty() {
                md.push_str(
                    "
## Diagnostics

",
                );
                for diag in &report.diagnostics {
                    md.push_str(&format!(
                        "- [{}] {}
",
                        diag.severity, diag.message
                    ));
                }
            }

            if let Some(ref test_report) = report.test_report {
                md.push_str(
                    "
## Test Results

",
                );
                md.push_str(&format!(
                    "- **Passed**: {}/{}
",
                    test_report.passed, test_report.total
                ));
                md.push_str(&format!(
                    "- **Failed**: {}
",
                    test_report.failed
                ));
                md.push_str(&format!(
                    "- **Skipped**: {}
",
                    test_report.skipped
                ));
            }

            if let Some(ref opt_report) = report.opt_report {
                md.push_str(
                    "
## Optimizations

",
                );
                md.push_str(&opt_report.summary());
                md.push('\n');
            }

            md
        }
        "text" => report.summary(),
        _ => report.summary(),
    }
}

/// Exports test reports in various formats.
pub fn export_test_report(report: &DeepTestReport, format: &str) -> String {
    match format {
        "json" => format!(
            "{{\"project\":\"{}\",\"total\":{},\"passed\":{},\"failed\":{},\"skipped\":{},\"flaky\":{},\"duration_secs\":{:.3}}}",
            report.project_id.as_str(),
            report.total, report.passed, report.failed,
            report.skipped, report.flaky,
            report.duration.as_secs_f64(),
        ),
        "junit" => {
            let mut xml = String::from(
                r#"<?xml version="1.0" encoding="UTF-8"?>
"#,
            );
            xml.push_str(&format!(r#"<testsuite name="{}" tests="{}" failures="{}" errors="0" skipped="{}" time="{:.3}">
"#,
                report.project_id.as_str(), report.total, report.failed,
                report.skipped, report.duration.as_secs_f64()));
            for case in &report.cases {
                xml.push_str(&format!(
                    r#"  <testcase classname="{}" name="{}" time="{:.3}">
"#,
                    case.suite,
                    case.name,
                    case.duration.as_secs_f64(),
                ));
                if !case.passed {
                    xml.push_str(&format!(
                        r#"    <failure message="{}" />
"#,
                        case.failure_message.as_deref().unwrap_or("unknown")
                    ));
                }
                if case.skipped {
                    xml.push_str("    <skipped />\n");
                }
                xml.push_str("  </testcase>\n");
            }
            xml.push_str("</testsuite>\n");
            xml
        }
        "markdown" => report.summary(),
        _ => report.summary(),
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Project Discovery and Auto-Detection
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of scanning a directory for known projects.
#[derive(Debug, Clone)]
pub struct ProjectScanResult {
    pub detected_projects: Vec<DetectedProject>,
    pub scan_duration: Duration,
    pub directories_scanned: usize,
}

#[derive(Debug, Clone)]
pub struct DetectedProject {
    pub project_id: DeepProjectId,
    pub path: PathBuf,
    pub confidence: f64, // 0.0 to 1.0
    pub detected_version: Option<String>,
    pub evidence: Vec<String>,
}

/// Scans a directory tree for known open-source projects.
pub fn scan_for_projects(root: &Path) -> io::Result<ProjectScanResult> {
    let start = Instant::now();
    let mut detected = Vec::new();
    let mut dirs_scanned = 0usize;

    if root.is_dir() {
        // Check root-level indicators
        if root.join("llvm").join("CMakeLists.txt").exists() {
            if let Ok(content) = fs::read_to_string(root.join("llvm").join("CMakeLists.txt")) {
                let version = content
                    .lines()
                    .find(|l| l.contains("LLVM_VERSION_MAJOR"))
                    .and_then(|l| l.split_whitespace().last().map(|s| s.to_string()));

                detected.push(DetectedProject {
                    project_id: DeepProjectId::Llvm,
                    path: root.join("llvm"),
                    confidence: 0.95,
                    detected_version: version,
                    evidence: vec!["Found llvm/CMakeLists.txt".into()],
                });
            }
        }

        if root.join("Makefile").exists() {
            if let Ok(content) = fs::read_to_string(root.join("Makefile")) {
                if content.contains("KERNELRELEASE") || content.contains("linux") {
                    detected.push(DetectedProject {
                        project_id: DeepProjectId::LinuxKernel,
                        path: root.to_path_buf(),
                        confidence: 0.90,
                        detected_version: None,
                        evidence: vec!["Found Linux kernel Makefile".into()],
                    });
                }
            }
        }

        if root.join("CMakeLists.txt").exists() {
            if let Ok(content) = fs::read_to_string(root.join("CMakeLists.txt")) {
                // Check for common project signatures
                let signatures: Vec<(DeepProjectId, &str, f64)> = vec![
                    (DeepProjectId::Qt, "find_package(Qt", 0.85),
                    (DeepProjectId::OpenCV, "find_package(OpenCV", 0.90),
                    (DeepProjectId::Protobuf, "protobuf", 0.90),
                    (DeepProjectId::Grpc, "gRPC", 0.90),
                    (DeepProjectId::Abseil, "absl", 0.90),
                    (DeepProjectId::LevelDb, "leveldb", 0.90),
                    (DeepProjectId::RocksDb, "rocksdb", 0.90),
                    (DeepProjectId::DuckDb, "duckdb", 0.90),
                    (DeepProjectId::ClickHouse, "clickhouse", 0.90),
                    (DeepProjectId::TensorFlowLite, "tensorflow", 0.85),
                    (DeepProjectId::ScyllaDb, "seastar", 0.85),
                ];

                for (id, sig, conf) in signatures {
                    if content.contains(sig) {
                        detected.push(DetectedProject {
                            project_id: id,
                            path: root.to_path_buf(),
                            confidence: conf,
                            detected_version: None,
                            evidence: vec![format!("Found signature: {}", sig)],
                        });
                    }
                }
            }
        }

        dirs_scanned += 1;

        // Recurse one level
        if let Ok(entries) = fs::read_dir(root) {
            for entry in entries.flatten() {
                if entry.path().is_dir() {
                    dirs_scanned += 1;
                }
            }
        }
    }

    Ok(ProjectScanResult {
        detected_projects: detected,
        scan_duration: start.elapsed(),
        directories_scanned: dirs_scanned,
    })
}

// Tests
// ═══════════════════════════════════════════════════════════════════════════════

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

    fn test_registry() -> X86ProjectsDeep {
        let tmp = env::temp_dir().join("llvm-native-test-projects-deep");
        let _ = fs::create_dir_all(&tmp);
        X86ProjectsDeep::new(&tmp)
    }

    // ── Project Config Tests ───────────────────────────────────────────────

    #[test]
    fn test_deep_project_id_from_str() {
        assert_eq!(DeepProjectId::from_str("llvm"), Some(DeepProjectId::Llvm));
        assert_eq!(DeepProjectId::from_str("Clang"), Some(DeepProjectId::Llvm));
        assert_eq!(
            DeepProjectId::from_str("linux-kernel"),
            Some(DeepProjectId::LinuxKernel)
        );
        assert_eq!(DeepProjectId::from_str("qt"), Some(DeepProjectId::Qt));
        assert_eq!(DeepProjectId::from_str("boost"), Some(DeepProjectId::Boost));
        assert_eq!(
            DeepProjectId::from_str("FFmpeg"),
            Some(DeepProjectId::Ffmpeg)
        );
        assert_eq!(
            DeepProjectId::from_str("opencv"),
            Some(DeepProjectId::OpenCV)
        );
        assert_eq!(
            DeepProjectId::from_str("tflite"),
            Some(DeepProjectId::TensorFlowLite)
        );
        assert_eq!(
            DeepProjectId::from_str("protobuf"),
            Some(DeepProjectId::Protobuf)
        );
        assert_eq!(DeepProjectId::from_str("grpc"), Some(DeepProjectId::Grpc));
        assert_eq!(DeepProjectId::from_str("absl"), Some(DeepProjectId::Abseil));
        assert_eq!(
            DeepProjectId::from_str("leveldb"),
            Some(DeepProjectId::LevelDb)
        );
        assert_eq!(
            DeepProjectId::from_str("rocksdb"),
            Some(DeepProjectId::RocksDb)
        );
        assert_eq!(
            DeepProjectId::from_str("duckdb"),
            Some(DeepProjectId::DuckDb)
        );
        assert_eq!(
            DeepProjectId::from_str("clickhouse"),
            Some(DeepProjectId::ClickHouse)
        );
        assert_eq!(
            DeepProjectId::from_str("seastar"),
            Some(DeepProjectId::ScyllaDb)
        );
        assert_eq!(DeepProjectId::from_str("nonexistent"), None);
    }

    #[test]
    fn test_deep_project_id_display_name() {
        assert_eq!(DeepProjectId::Llvm.display_name(), "LLVM/Clang");
        assert_eq!(DeepProjectId::LinuxKernel.display_name(), "Linux Kernel");
        assert_eq!(DeepProjectId::ScyllaDb.display_name(), "ScyllaDB/Seastar");
    }

    #[test]
    fn test_build_variant_cmake_type() {
        assert_eq!(DeepBuildVariant::Debug.as_cmake_build_type(), Some("Debug"));
        assert_eq!(
            DeepBuildVariant::Release.as_cmake_build_type(),
            Some("Release")
        );
        assert_eq!(
            DeepBuildVariant::RelWithDebInfo.as_cmake_build_type(),
            Some("RelWithDebInfo")
        );
        assert_eq!(
            DeepBuildVariant::MinSizeRel.as_cmake_build_type(),
            Some("MinSizeRel")
        );
        assert_eq!(
            DeepBuildVariant::PgoInstrumented.as_cmake_build_type(),
            None
        );
    }

    #[test]
    fn test_detects_all_deep_project_ids() {
        // Verify all expected projects are in the list
        for id in DEEP_PROJECT_IDS {
            assert!(
                DeepProjectId::from_str(id).is_some(),
                "Project ID '{}' should be recognized",
                id
            );
        }
        assert_eq!(DEEP_PROJECT_IDS.len(), 15);
    }

    // ── X86ProjectsDeep Tests ──────────────────────────────────────────────

    #[test]
    fn test_registry_creation() {
        let registry = test_registry();
        assert_eq!(registry.target_triple, X86_64_LINUX_TRIPLE);
        assert_eq!(registry.target_cpu, "x86-64-v3");
        assert!(registry.env.contains_key("CC"));
        assert!(registry.env.contains_key("CXX"));
    }

    #[test]
    fn test_register_and_retrieve_project() {
        let mut registry = test_registry();
        let config = llvm_deep_config();
        registry.register(config);

        let retrieved = registry.get_project(DeepProjectId::Llvm);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().build_system, DeepBuildSystem::Cmake);
    }

    #[test]
    fn test_register_all_projects() {
        let mut registry = test_registry();
        registry.register_default_projects();
        assert_eq!(registry.projects.len(), 15);
    }

    #[test]
    fn test_build_order_respects_dependencies() {
        let mut registry = test_registry();
        // Register in a specific order: base libraries first
        registry.register(abseil_deep_config());
        registry.register(protobuf_deep_config());
        registry.register(grpc_deep_config());

        let order = registry.build_order();
        let absl_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Abseil)
            .unwrap();
        let proto_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Protobuf)
            .unwrap();
        let grpc_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Grpc)
            .unwrap();

        // Protobuf depends on Abseil, so Abseil should come first
        assert!(
            absl_pos < proto_pos,
            "Abseil (pos {}) should come before Protobuf (pos {})",
            absl_pos,
            proto_pos
        );
        // gRPC depends on both, so both should come before gRPC
        assert!(absl_pos < grpc_pos);
        assert!(proto_pos < grpc_pos);
    }

    #[test]
    fn test_validate_dependencies() {
        let mut registry = test_registry();
        registry.register(abseil_deep_config());
        registry.register(protobuf_deep_config()); // depends on Abseil
        registry.register(grpc_deep_config()); // depends on Abseil + Protobuf

        let issues = registry.validate_dependencies();
        assert!(
            issues.is_empty(),
            "Should have no dependency issues: {:?}",
            issues
        );
    }

    #[test]
    fn test_validate_missing_dependency() {
        let mut registry = test_registry();
        registry.register(protobuf_deep_config()); // depends on Abseil which is not registered

        let issues = registry.validate_dependencies();
        assert!(
            !issues.is_empty(),
            "Should detect missing Abseil dependency"
        );
    }

    #[test]
    fn test_project_build_dir() {
        let registry = test_registry();
        let dir = registry.project_build_dir(DeepProjectId::Llvm, DeepBuildStage::Stage2);
        assert!(dir.to_string_lossy().contains("llvm"));
        assert!(dir.to_string_lossy().contains("stage2"));
    }

    #[test]
    fn test_toolchain_file_generation() {
        let registry = test_registry();
        let content = registry.generate_toolchain_file();
        assert!(content.contains("CMAKE_SYSTEM_NAME Linux"));
        assert!(content.contains("CMAKE_C_COMPILER clang"));
        assert!(content.contains("CMAKE_CXX_COMPILER clang++"));
        assert!(content.contains("x86-64-v3"));
    }

    #[test]
    fn test_init_subsystems() {
        let mut registry = test_registry();
        registry.init_subsystems();
        assert!(registry.build.is_some());
        assert!(registry.test.is_some());
        assert!(registry.optimize.is_some());
    }

    // ── DeepProjectConfig Tests ────────────────────────────────────────────

    #[test]
    fn test_config_builder_pattern() {
        let config = DeepProjectConfig::new(DeepProjectId::Llvm)
            .with_variant(DeepBuildVariant::Release)
            .with_lto()
            .with_simd(DeepSimdLevel::Avx2)
            .cmake_var("CMAKE_BUILD_TYPE", "Release")
            .cflag("-march=x86-64-v3")
            .cxxflag("-std=c++17")
            .define("NDEBUG", None);

        assert_eq!(config.variant, DeepBuildVariant::Release);
        assert!(config.enable_lto);
        assert_eq!(config.simd_level, DeepSimdLevel::Avx2);
        assert_eq!(
            config.cmake_vars.get("CMAKE_BUILD_TYPE").unwrap(),
            "Release"
        );
        assert!(config.cflags.contains(&"-march=x86-64-v3".to_string()));
        assert!(config.cxxflags.contains(&"-std=c++17".to_string()));
        assert_eq!(config.defines[0], ("NDEBUG".to_string(), None));
    }

    // ── Factory Function Tests ─────────────────────────────────────────────

    #[test]
    fn test_llvm_config() {
        let config = llvm_deep_config();
        assert_eq!(config.id, DeepProjectId::Llvm);
        assert_eq!(config.build_system, DeepBuildSystem::Cmake);
        assert!(config.cmake_vars.contains_key("LLVM_TARGETS_TO_BUILD"));
        assert_eq!(
            config.cmake_vars.get("LLVM_TARGETS_TO_BUILD").unwrap(),
            "X86"
        );
        assert!(config.cmake_vars.contains_key("LLVM_ENABLE_PROJECTS"));
        assert!(config
            .cmake_vars
            .get("LLVM_ENABLE_PROJECTS")
            .unwrap()
            .contains("clang"));
    }

    #[test]
    fn test_llvm_bootstrap_config() {
        let config = llvm_bootstrap_config();
        assert!(config.supports_bootstrap);
        assert_eq!(config.stage, DeepBuildStage::Stage1);
        assert_eq!(
            config.cmake_vars.get("CLANG_ENABLE_BOOTSTRAP").unwrap(),
            "ON"
        );
    }

    #[test]
    fn test_linux_kernel_config() {
        let config = linux_kernel_deep_config();
        assert_eq!(config.id, DeepProjectId::LinuxKernel);
        assert_eq!(config.build_system, DeepBuildSystem::Kbuild);
        assert!(config.defines.iter().any(|(k, _)| k == "CONFIG_X86_64"));
        assert!(config.cflags.iter().any(|f| f == "-mcmodel=kernel"));
        assert!(config.cflags.iter().any(|f| f == "-mno-sse"));
    }

    #[test]
    fn test_linux_kernel_i386_config() {
        let config = linux_kernel_i386_config();
        assert!(!config.defines.iter().any(|(k, _)| k == "CONFIG_X86_64"));
        assert!(config.defines.iter().any(|(k, _)| k == "CONFIG_X86_32"));
        assert!(config.cflags.iter().any(|f| f == "-m32"));
    }

    #[test]
    fn test_qt_config() {
        let config = qt_deep_config();
        assert_eq!(config.id, DeepProjectId::Qt);
        assert_eq!(config.build_system, DeepBuildSystem::Cmake);
        assert_eq!(config.cmake_vars.get("QT_FEATURE_gui").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("QT_FEATURE_widgets").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("QT_ENABLE_AVX2").unwrap(), "ON");
        assert!(config.test_config.is_some());
    }

    #[test]
    fn test_boost_config() {
        let config = boost_deep_config();
        assert_eq!(config.id, DeepProjectId::Boost);
        assert_eq!(config.build_system, DeepBuildSystem::BoostBuild);
        // Check for a few expected Boost libraries
        let opts = &config.meson_options; // misnamed field, stores b2 options
        assert!(opts.iter().any(|o| o.contains("--with-filesystem")));
        assert!(opts.iter().any(|o| o.contains("--with-system")));
        assert!(opts.iter().any(|o| o.contains("address-model=64")));
        assert!(config.defines.iter().any(|(k, _)| k == "BOOST_USE_SSE2"));
    }

    #[test]
    fn test_ffmpeg_config() {
        let config = ffmpeg_deep_config();
        assert_eq!(config.id, DeepProjectId::Ffmpeg);
        assert_eq!(config.build_system, DeepBuildSystem::Autotools);
        assert!(config
            .configure_flags
            .iter()
            .any(|f| f.contains("--enable-avx512")));
        assert!(config
            .configure_flags
            .iter()
            .any(|f| f.contains("--enable-decoder=h264")));
        assert!(config
            .configure_flags
            .iter()
            .any(|f| f.contains("--enable-x86asm")));
    }

    #[test]
    fn test_opencv_config() {
        let config = opencv_deep_config();
        assert_eq!(config.id, DeepProjectId::OpenCV);
        assert_eq!(config.build_system, DeepBuildSystem::Cmake);
        assert_eq!(config.cmake_vars.get("BUILD_opencv_core").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("CPU_BASELINE").unwrap(), "SSE4_2");
        assert_eq!(
            config.cmake_vars.get("CPU_DISPATCH").unwrap(),
            "AVX;AVX2;AVX512_SKX"
        );
    }

    #[test]
    fn test_tensorflow_lite_config() {
        let config = tensorflow_lite_deep_config();
        assert_eq!(config.id, DeepProjectId::TensorFlowLite);
        assert_eq!(
            config.cmake_vars.get("TFLITE_ENABLE_XNNPACK").unwrap(),
            "ON"
        );
        assert_eq!(config.cmake_vars.get("XNNPACK_ENABLE_AVX2").unwrap(), "ON");
        assert!(config.dependencies.contains(&DeepProjectId::Abseil));
        assert!(config.dependencies.contains(&DeepProjectId::Protobuf));
    }

    #[test]
    fn test_protobuf_config() {
        let config = protobuf_deep_config();
        assert_eq!(config.id, DeepProjectId::Protobuf);
        assert_eq!(
            config
                .cmake_vars
                .get("protobuf_BUILD_PROTOC_BINARIES")
                .unwrap(),
            "ON"
        );
        assert!(config.dependencies.contains(&DeepProjectId::Abseil));
    }

    #[test]
    fn test_grpc_config() {
        let config = grpc_deep_config();
        assert_eq!(config.id, DeepProjectId::Grpc);
        assert_eq!(
            config.cmake_vars.get("gRPC_SSL_PROVIDER").unwrap(),
            "module"
        );
        assert!(config.dependencies.contains(&DeepProjectId::Abseil));
        assert!(config.dependencies.contains(&DeepProjectId::Protobuf));
    }

    #[test]
    fn test_abseil_config() {
        let config = abseil_deep_config();
        assert_eq!(config.id, DeepProjectId::Abseil);
        assert_eq!(config.cmake_vars.get("CMAKE_CXX_STANDARD").unwrap(), "17");
        assert!(config.dependencies.is_empty());
    }

    #[test]
    fn test_leveldb_config() {
        let config = leveldb_deep_config();
        assert_eq!(config.id, DeepProjectId::LevelDb);
        assert_eq!(config.cmake_vars.get("HAVE_SNAPPY").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("HAVE_CRC32C").unwrap(), "ON");
        assert!(config.cflags.iter().any(|f| f == "-msse4.2"));
    }

    #[test]
    fn test_rocksdb_config() {
        let config = rocksdb_deep_config();
        assert_eq!(config.id, DeepProjectId::RocksDb);
        assert_eq!(config.cmake_vars.get("WITH_ZSTD").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("WITH_LZ4").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("PORTABLE").unwrap(), "OFF");
        assert!(config
            .test_config
            .as_ref()
            .unwrap()
            .benchmark_config
            .is_some());
    }

    #[test]
    fn test_duckdb_config() {
        let config = duckdb_deep_config();
        assert_eq!(config.id, DeepProjectId::DuckDb);
        assert_eq!(
            config
                .cmake_vars
                .get("ENABLE_VECTORIZED_EXECUTION")
                .unwrap(),
            "ON"
        );
        assert_eq!(
            config.cmake_vars.get("BUILD_PARQUET_EXTENSION").unwrap(),
            "ON"
        );
    }

    #[test]
    fn test_clickhouse_config() {
        let config = clickhouse_deep_config();
        assert_eq!(config.id, DeepProjectId::ClickHouse);
        assert_eq!(config.cmake_vars.get("CMAKE_CXX_STANDARD").unwrap(), "23");
        assert_eq!(config.cmake_vars.get("ENABLE_AVX512").unwrap(), "ON");
        assert_eq!(config.simd_level, DeepSimdLevel::Avx512Full);
    }

    #[test]
    fn test_scylladb_config() {
        let config = scylladb_deep_config();
        assert_eq!(config.id, DeepProjectId::ScyllaDb);
        assert_eq!(config.cmake_vars.get("Seastar_DPDK").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("Seastar_IO_URING").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("CMAKE_CXX_STANDARD").unwrap(), "20");
        assert!(config.cxxflags.iter().any(|f| f == "-fcoroutines"));
    }

    // ── X86ProjectBuild Tests ──────────────────────────────────────────────

    #[test]
    fn test_build_orchestrator_creation() {
        let registry = test_registry();
        let build = X86ProjectBuild::new(&registry);
        assert!(build.incremental);
        assert!(build.auto_patch);
        assert!(!build.clean_build);
    }

    #[test]
    fn test_resolve_build_order() {
        let mut registry = test_registry();
        registry.register(abseil_deep_config());
        registry.register(protobuf_deep_config());

        let mut build = X86ProjectBuild::new(&registry);
        let order = build.resolve_build_order(&registry);
        assert!(!order.is_empty());
        assert_eq!(order[0], DeepProjectId::Abseil); // Abseil has no deps, comes first
    }

    #[test]
    fn test_needs_rebuild_no_directory() {
        let registry = test_registry();
        let build = X86ProjectBuild::new(&registry);
        let config = DeepProjectConfig::new(DeepProjectId::Llvm);
        let dir = PathBuf::from("/nonexistent/build/dir");
        assert!(build.needs_rebuild(&config, &dir));
    }

    #[test]
    fn test_cancel_and_reset() {
        let registry = test_registry();
        let build = X86ProjectBuild::new(&registry);
        assert!(!build.is_cancelled());
        build.cancel_all();
        assert!(build.is_cancelled());
        build.reset_cancellation();
        assert!(!build.is_cancelled());
    }

    // ── DeepBuildCache Tests ───────────────────────────────────────────────

    #[test]
    fn test_cache_creation() {
        let tmp = env::temp_dir().join("llvm-native-test-cache");
        let cache = DeepBuildCache::new(&tmp);
        assert!(cache.enabled);
        assert_eq!(cache.current_size, 0);
        assert!(cache.hit_rate() >= 0.0);
    }

    #[test]
    fn test_cache_key_computation() {
        let key1 = DeepBuildCache::compute_key("int main() {}", &["-O2".to_string()]);
        let key2 = DeepBuildCache::compute_key("int main() {}", &["-O2".to_string()]);
        let key3 = DeepBuildCache::compute_key("int main() {}", &["-O3".to_string()]);
        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_cache_stats() {
        let tmp = env::temp_dir().join("llvm-native-test-cache-stats");
        let cache = DeepBuildCache::new(&tmp);
        let stats = cache.stats();
        assert!(stats.contains("Cache:"));
        assert!(stats.contains("hit rate"));
    }

    // ── X86ProjectTest Tests ───────────────────────────────────────────────

    #[test]
    fn test_test_system_creation() {
        let registry = test_registry();
        let test_sys = X86ProjectTest::new(&registry);
        assert_eq!(test_sys.default_timeout_secs, TEST_TIMEOUT_SECS);
        assert!(test_sys.rerun_failed);
        assert_eq!(test_sys.rerun_attempts, 3);
    }

    #[test]
    fn test_empty_test_report() {
        let report = DeepTestReport::new(DeepProjectId::Llvm);
        assert!(!report.all_passed);
        assert_eq!(report.total, 0);
        assert_eq!(report.pass_rate(), 1.0);
    }

    #[test]
    fn test_test_report_with_results() {
        let mut report = DeepTestReport::new(DeepProjectId::Llvm);
        report.total = 10;
        report.passed = 8;
        report.failed = 2;
        assert!(!report.all_passed);
        assert!((report.pass_rate() - 0.8).abs() < 0.001);
        assert!(report.summary().contains("8/10"));
    }

    // ── X86ProjectOptimize Tests ───────────────────────────────────────────

    #[test]
    fn test_optimize_creation() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        assert!(!opt.keep_intermediates);
        assert!(!opt.verbose);
    }

    #[test]
    fn test_pgo_instrumented_flags() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        let flags = opt.generate_pgo_instrumented_flags();
        assert!(flags.iter().any(|f| f.contains("fprofile-generate")));
    }

    #[test]
    fn test_pgo_use_flags() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        let flags = opt.generate_pgo_use_flags(Path::new("/tmp/profiles"));
        assert!(flags.iter().any(|f| f.contains("fprofile-use")));
    }

    #[test]
    fn test_thin_lto_cmake_flags() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        let flags = opt.generate_thin_lto_cmake_flags();
        assert_eq!(flags.get("LLVM_ENABLE_LTO").unwrap(), "Thin");
        assert!(flags.get("CMAKE_C_FLAGS").unwrap().contains("flto=thin"));
    }

    #[test]
    fn test_full_lto_cmake_flags() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        let flags = opt.generate_full_lto_cmake_flags();
        assert_eq!(flags.get("LLVM_ENABLE_LTO").unwrap(), "Full");
        assert!(flags.get("CMAKE_C_FLAGS").unwrap().contains("flto=full"));
    }

    #[test]
    fn test_fmv_attribute_generation() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        let targets = vec!["x86-64".to_string(), "x86-64-v3".to_string()];
        let attr = opt.generate_fmv_attributes(&targets);
        assert!(attr.contains("target_clones"));
        assert!(attr.contains("default"));
        assert!(attr.contains("avx2"));
    }

    #[test]
    fn test_fmv_sanitize_target() {
        let registry = test_registry();
        let opt = X86ProjectOptimize::new(&registry);
        assert_eq!(opt.sanitize_fmv_target("x86-64"), "default");
        assert_eq!(opt.sanitize_fmv_target("x86-64-v2"), "sse4.2,popcnt");
        assert_eq!(
            opt.sanitize_fmv_target("x86-64-v3"),
            "avx2,bmi,bmi2,fma,lzcnt"
        );
        assert_eq!(
            opt.sanitize_fmv_target("x86-64-v4"),
            "avx512f,avx512bw,avx512dq,avx512vl"
        );
        assert_eq!(opt.sanitize_fmv_target("haswell"), "avx2");
        assert_eq!(opt.sanitize_fmv_target("unknown"), "unknown");
    }

    // ── DeepLtoConfig Tests ────────────────────────────────────────────────

    #[test]
    fn test_lto_config_default() {
        let lto = DeepLtoConfig::default();
        assert!(!lto.enabled);
        assert_eq!(lto.mode, "thin");
        assert!(lto.use_new_pm);
    }

    #[test]
    fn test_lto_compiler_flags_disabled() {
        let lto = DeepLtoConfig::default();
        assert!(lto.compiler_flags().is_empty());
    }

    #[test]
    fn test_lto_compiler_flags_enabled() {
        let mut lto = DeepLtoConfig::default();
        lto.enabled = true;
        let flags = lto.compiler_flags();
        assert!(flags.iter().any(|f| f.contains("flto=thin")));
    }

    // ── DeepPatch Tests ────────────────────────────────────────────────────

    #[test]
    fn test_patch_inline_creation() {
        let patch = DeepPatch::new_inline(
            "Fix missing include",
            "src/main.c",
            "#include <old.h>",
            "#include <new.h>",
        );
        assert_eq!(patch.target_file, "src/main.c");
        assert!(patch.required);
        assert!(!patch.is_diff_file);
    }

    #[test]
    fn test_patch_diff_creation() {
        let patch =
            DeepPatch::new_diff("Backport fix", "src/config.h", Path::new("/tmp/fix.patch"));
        assert!(patch.is_diff_file);
        assert!(patch.patch_file_path.is_some());
    }

    // ── DeepBuildReport Tests ──────────────────────────────────────────────

    #[test]
    fn test_build_report_creation() {
        let report = DeepBuildReport::new(DeepProjectId::Llvm);
        assert_eq!(report.status, DeepBuildStatus::Pending);
        assert_eq!(report.tus_compiled, 0);
        assert!(report.elapsed().is_zero());
        assert!(!report.is_success());
    }

    #[test]
    fn test_build_report_summary() {
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        report.status = DeepBuildStatus::Success;
        report.tus_compiled = 5000;
        report.warning_count = 12;
        let summary = report.summary();
        assert!(summary.contains("LLVM/Clang"));
        assert!(summary.contains("success"));
    }

    // ── DeepBuildEvent Tests ───────────────────────────────────────────────

    #[test]
    fn test_build_event_types() {
        let types = [
            DeepBuildEventType::BuildStarted,
            DeepBuildEventType::BuildCompleted,
            DeepBuildEventType::BuildFailed,
            DeepBuildEventType::ConfigureStarted,
            DeepBuildEventType::CompileStarted,
        ];
        for t in &types {
            assert!(!t.as_str().is_empty());
        }
    }

    #[test]
    fn test_event_logging() {
        let mut log = Vec::new();
        log_event(
            &mut log,
            DeepBuildEvent {
                project_id: DeepProjectId::Llvm,
                event_type: DeepBuildEventType::BuildStarted,
                message: "Starting LLVM build".to_string(),
                timestamp: SystemTime::now(),
                duration: None,
            },
        );
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].project_id, DeepProjectId::Llvm);
    }

    // ── DeepSanitizer Tests ────────────────────────────────────────────────

    #[test]
    fn test_sanitizer_flags() {
        assert_eq!(DeepSanitizer::Address.to_cflag(), "-fsanitize=address");
        assert_eq!(DeepSanitizer::Thread.to_cflag(), "-fsanitize=thread");
        assert_eq!(DeepSanitizer::Undefined.to_cflag(), "-fsanitize=undefined");
        assert_eq!(
            DeepSanitizer::AddressUndefined.to_cflag(),
            "-fsanitize=address,undefined"
        );
    }

    // ── DeepSimdLevel Tests ────────────────────────────────────────────────

    #[test]
    fn test_simd_level_to_march() {
        assert_eq!(DeepSimdLevel::Sse2.to_march_flag(), Some("pentium4"));
        assert_eq!(DeepSimdLevel::Avx2.to_march_flag(), Some("haswell"));
        assert_eq!(
            DeepSimdLevel::Avx512F.to_march_flag(),
            Some("skylake-avx512")
        );
        assert_eq!(DeepSimdLevel::None.to_march_flag(), None);
    }

    #[test]
    fn test_simd_level_to_gcc_target_flag() {
        assert_eq!(DeepSimdLevel::Sse2.to_gcc_target_flag(), None);
        assert_eq!(DeepSimdLevel::Avx2.to_gcc_target_flag(), Some("avx2"));
        assert_eq!(
            DeepSimdLevel::Avx512Full.to_gcc_target_flag(),
            Some("avx512f,avx512bw,avx512dq,avx512vl,avx512cd")
        );
    }

    // ── DeepBuildStatus Tests ──────────────────────────────────────────────

    #[test]
    fn test_build_status_terminal() {
        assert!(DeepBuildStatus::Success.is_terminal());
        assert!(DeepBuildStatus::Failed.is_terminal());
        assert!(DeepBuildStatus::Cancelled.is_terminal());
        assert!(!DeepBuildStatus::Pending.is_terminal());
        assert!(!DeepBuildStatus::Building.is_terminal());
    }

    #[test]
    fn test_build_status_running() {
        assert!(DeepBuildStatus::Configuring.is_running());
        assert!(DeepBuildStatus::Building.is_running());
        assert!(!DeepBuildStatus::Pending.is_running());
        assert!(!DeepBuildStatus::Success.is_running());
    }

    // ── DeepOptimizationReport Tests ───────────────────────────────────────

    #[test]
    fn test_opt_report_summary() {
        let mut report = DeepOptimizationReport::new(DeepProjectId::Llvm);
        report.pgo_applied = true;
        report.pgo_speedup_pct = Some(15.0);
        report.lto_applied = true;
        report.lto_size_reduction_pct = Some(10.0);

        let summary = report.summary();
        assert!(summary.contains("LLVM/Clang"));
        assert!(summary.contains("PGO"));
        assert!(summary.contains("LTO"));
    }

    // ── Utility Tests ──────────────────────────────────────────────────────

    #[test]
    fn test_build_summary_empty() {
        let summary = build_summary(&[]);
        assert!(summary.contains("0 total"));
    }

    #[test]
    fn test_build_summary_with_results() {
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        report.status = DeepBuildStatus::Success;
        report.tus_compiled = 100;
        let summary = build_summary(&[report]);
        assert!(summary.contains("1 total"));
        assert!(summary.contains("1 succeeded"));
    }

    #[test]
    fn test_test_summary() {
        let mut results = BTreeMap::new();
        let mut report = DeepTestReport::new(DeepProjectId::Llvm);
        report.total = 100;
        report.passed = 95;
        report.failed = 3;
        report.skipped = 2;
        results.insert(DeepProjectId::Llvm, report);

        let summary = test_summary(&results);
        assert!(summary.contains("Projects tested: 1"));
        assert!(summary.contains("95 passed"));
    }

    #[test]
    fn test_cmake_presets_generation() {
        let mut registry = test_registry();
        registry.register(llvm_deep_config());
        let presets = generate_cmake_presets(&registry);
        assert!(presets.contains("\"version\": 6"));
        assert!(presets.contains("llvm-release"));
    }

    #[test]
    fn test_default_release_opt_config() {
        let config = default_release_opt_config();
        assert!(config.enable_thin_lto);
        assert!(config.enable_fmv);
    }

    #[test]
    fn test_aggressive_opt_config() {
        let config = aggressive_opt_config();
        assert!(config.enable_pgo);
        assert!(config.enable_thin_lto);
        assert!(config.enable_bolt);
        assert!(config.enable_fmv);
        assert!(config.use_cs_pgo);
    }

    // ── Integration-style Tests ────────────────────────────────────────────

    #[test]
    fn test_full_registry_workflow() {
        let mut registry = test_registry();
        registry.register_default_projects();
        registry.init_subsystems();

        // Verify all projects registered
        assert_eq!(registry.projects.len(), 15);

        // Verify no duplicate IDs
        let ids: Vec<_> = registry.projects.keys().collect();
        let unique: HashSet<_> = ids.iter().copied().collect();
        assert_eq!(ids.len(), unique.len());

        // Verify build order is not empty
        let order = registry.build_order();
        assert!(!order.is_empty());

        // Verify all registered projects appear in the order
        for id in registry.projects.keys() {
            assert!(
                order.contains(id),
                "Project {} should be in build order",
                id.display_name()
            );
        }
    }

    #[test]
    fn test_dependency_chain() {
        // Test the common chain: Abseil -> Protobuf -> gRPC -> TensorFlow Lite
        let mut registry = test_registry();
        registry.register(abseil_deep_config());
        registry.register(protobuf_deep_config());
        registry.register(grpc_deep_config());
        registry.register(tensorflow_lite_deep_config());

        let order = registry.build_order();

        let absl_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Abseil)
            .unwrap();
        let proto_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Protobuf)
            .unwrap();
        let grpc_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::Grpc)
            .unwrap();
        let tflite_pos = order
            .iter()
            .position(|&id| id == DeepProjectId::TensorFlowLite)
            .unwrap();

        assert!(absl_pos < proto_pos);
        assert!(absl_pos < grpc_pos);
        assert!(proto_pos < grpc_pos);
        assert!(absl_pos < tflite_pos);
        assert!(proto_pos < tflite_pos);
    }

    #[test]
    fn test_all_project_factories_produce_valid_configs() {
        let factories: Vec<fn() -> DeepProjectConfig> = vec![
            llvm_deep_config,
            linux_kernel_deep_config,
            qt_deep_config,
            boost_deep_config,
            ffmpeg_deep_config,
            opencv_deep_config,
            tensorflow_lite_deep_config,
            protobuf_deep_config,
            grpc_deep_config,
            abseil_deep_config,
            leveldb_deep_config,
            rocksdb_deep_config,
            duckdb_deep_config,
            clickhouse_deep_config,
            scylladb_deep_config,
        ];

        let mut seen_ids = HashSet::new();
        for factory in factories {
            let config = factory();
            assert!(
                !config.name.is_empty(),
                "Config from factory should have a name"
            );
            assert!(!config.version.is_empty(), "Config should have a version");
            assert!(
                !seen_ids.contains(&config.id),
                "Duplicate project ID: {:?}",
                config.id
            );
            seen_ids.insert(config.id);
        }
        assert_eq!(seen_ids.len(), 15);
    }

    #[test]
    fn test_simd_level_ordering() {
        // Verify SIMD levels have a logical ordering
        assert!(DeepSimdLevel::Avx2 > DeepSimdLevel::Avx);
        assert!(DeepSimdLevel::Avx512Full > DeepSimdLevel::Avx512F);
        assert!(DeepSimdLevel::Sse42 > DeepSimdLevel::Sse2);
        assert!(DeepSimdLevel::Avx > DeepSimdLevel::Sse42);
    }

    #[test]
    fn test_deep_build_stage_ordering() {
        assert!(DeepBuildStage::Stage3 > DeepBuildStage::Stage2);
        assert!(DeepBuildStage::Stage2 > DeepBuildStage::Stage1);
        assert!(DeepBuildStage::Stage1 > DeepBuildStage::Stage0);
    }

    // ── Cross-Compilation Target Tests ────────────────────────────────────

    #[test]
    fn test_x86_cross_target_x86_64_linux() {
        let target = X86CrossTarget::x86_64_linux_gnu();
        assert_eq!(target.triple, X86_64_LINUX_TRIPLE);
        assert!(!target.is_32bit);
        assert_eq!(target.data_model, X86DataModel::Lp64);
        assert_eq!(target.stack_alignment, 16);
        assert_eq!(target.red_zone_size, 128);
    }

    #[test]
    fn test_x86_cross_target_i686() {
        let target = X86CrossTarget::i686_linux_gnu();
        assert_eq!(target.triple, X86_32_LINUX_TRIPLE);
        assert!(target.is_32bit);
        assert_eq!(target.data_model, X86DataModel::Ilp32);
        assert_eq!(target.red_zone_size, 0);
    }

    #[test]
    fn test_x86_cross_target_windows() {
        let target = X86CrossTarget::x86_64_windows_msvc();
        assert_eq!(target.os, X86TargetOs::Windows);
        assert_eq!(target.data_model, X86DataModel::Llp64);
        assert!(!target.default_pic);
    }

    #[test]
    fn test_cross_target_cmake_toolchain() {
        let target = X86CrossTarget::x86_64_linux_gnu();
        let tc = target.to_cmake_toolchain();
        assert!(tc.contains("CMAKE_SYSTEM_NAME Linux"));
        assert!(tc.contains("x86_64-unknown-linux-gnu"));
    }

    // ── Data Model Tests ──────────────────────────────────────────────────

    #[test]
    fn test_data_model_sizes() {
        assert_eq!(X86DataModel::Lp64.sizeof_long(), 8);
        assert_eq!(X86DataModel::Lp64.sizeof_pointer(), 8);
        assert_eq!(X86DataModel::Ilp32.sizeof_long(), 4);
        assert_eq!(X86DataModel::Ilp32.sizeof_pointer(), 4);
        assert_eq!(X86DataModel::Llp64.sizeof_long(), 4);
        assert_eq!(X86DataModel::Llp64.sizeof_pointer(), 8);
    }

    // ── Container Build Tests ─────────────────────────────────────────────

    #[test]
    fn test_container_build_config_default() {
        let cfg = ContainerBuildConfig::default();
        assert_eq!(cfg.base_image, "ubuntu:24.04");
        assert!(cfg.use_buildkit);
        assert!(cfg.rm);
        assert!(!cfg.packages.is_empty());
    }

    #[test]
    fn test_container_runtime_commands() {
        assert_eq!(ContainerRuntime::Docker.command(), "docker");
        assert_eq!(ContainerRuntime::Podman.command(), "podman");
        assert_eq!(ContainerRuntime::Singularity.command(), "singularity");
    }

    #[test]
    fn test_dockerfile_generation() {
        let config = llvm_deep_config();
        let container_cfg = ContainerBuildConfig::default();
        let dockerfile = generate_project_dockerfile(&config, &container_cfg);
        assert!(dockerfile.contains("FROM ubuntu:24.04"));
        assert!(dockerfile.contains("clang"));
        assert!(dockerfile.contains("cmake"));
    }

    // ── Build Matrix Tests ────────────────────────────────────────────────

    #[test]
    fn test_build_matrix_generation() {
        let matrix = generate_build_matrix(&[DeepProjectId::Llvm]);
        assert!(!matrix.is_empty());
        for entry in &matrix {
            if entry.variant == DeepBuildVariant::Debug {
                assert!(!entry.lto, "Debug builds should not have LTO");
            }
        }
    }

    #[test]
    fn test_build_matrix_entry_key() {
        let entry = BuildMatrixEntry {
            project_id: DeepProjectId::Llvm,
            variant: DeepBuildVariant::Release,
            simd_level: DeepSimdLevel::Avx2,
            target: X86_64_LINUX_TRIPLE.to_string(),
            microarch: "haswell".to_string(),
            lto: true,
            sanitizer: None,
            labels: vec![],
        };
        let key = entry.key();
        assert!(key.contains("llvm"));
        assert!(key.contains("release"));
        assert!(key.contains("lto"));
    }

    // ── Patch Set Tests ───────────────────────────────────────────────────

    #[test]
    fn test_patch_set_creation() {
        let set = PatchSet::new(DeepProjectId::Llvm);
        assert!(set.auto_apply);
        assert_eq!(set.total_patches(), 0);
    }

    #[test]
    fn test_patch_set_add_and_count() {
        let mut set = PatchSet::new(DeepProjectId::Llvm);
        set.add(
            "build-fix",
            DeepPatch::new_inline("test", "file.c", "old", "new"),
        );
        set.add(
            "build-fix",
            DeepPatch::new_inline("test2", "file2.c", "old", "new"),
        );
        assert_eq!(set.total_patches(), 2);
        assert_eq!(set.required_patches().len(), 2);
    }

    #[test]
    fn test_common_clang_compat_patches() {
        let set = common_clang_compat_patches(DeepProjectId::Llvm);
        assert!(set.total_patches() > 0);
    }

    // ── CI Pipeline Tests ─────────────────────────────────────────────────

    #[test]
    fn test_ci_pipeline_default() {
        let pipeline = CIPipelineConfig::default();
        assert!(!pipeline.nightly);
        assert!(pipeline.include_sanitizers);
        assert!(!pipeline.projects.is_empty());
    }

    #[test]
    fn test_github_actions_workflow() {
        let pipeline = CIPipelineConfig::default();
        let yaml = generate_github_actions_workflow(&pipeline);
        assert!(yaml.contains("on:"));
        assert!(yaml.contains("runs-on"));
        assert!(yaml.contains("steps:"));
    }

    #[test]
    fn test_gitlab_ci_yaml() {
        let mut pipeline = CIPipelineConfig::default();
        pipeline.projects = vec![DeepProjectId::Llvm];
        let yaml = generate_gitlab_ci_yaml(&pipeline);
        assert!(yaml.contains("stages:"));
        assert!(yaml.contains("build-llvm"));
    }

    // ── Build History Tests ───────────────────────────────────────────────

    #[test]
    fn test_build_history_recording() {
        let mut history = BuildHistory::new(DeepProjectId::Llvm);
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        report.status = DeepBuildStatus::Success;
        report.tus_compiled = 500;
        report.warning_count = 3;
        history.record(&report);
        history.record(&report);
        assert_eq!(history.records.len(), 2);
    }

    #[test]
    fn test_build_history_trends() {
        let mut history = BuildHistory::new(DeepProjectId::Llvm);
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        report.status = DeepBuildStatus::Success;
        for _ in 0..5 {
            history.record(&report);
        }
        let summary = history.trend_summary();
        assert!(summary.contains("Build Trends"));
    }

    // ── Differential Build Tests ──────────────────────────────────────────

    #[test]
    fn test_diff_builds_no_change() {
        let prev = DeepBuildReport::new(DeepProjectId::Llvm);
        let curr = DeepBuildReport::new(DeepProjectId::Llvm);
        let diff = diff_builds(&prev, &curr);
        assert_eq!(diff.impact, DiffImpact::NoChange);
        assert_eq!(diff.size_delta_bytes, 0);
    }

    #[test]
    fn test_diff_builds_error() {
        let mut prev = DeepBuildReport::new(DeepProjectId::Llvm);
        prev.status = DeepBuildStatus::Success;
        let mut curr = DeepBuildReport::new(DeepProjectId::Llvm);
        curr.status = DeepBuildStatus::Failed;
        curr.error_count = 5;
        let diff = diff_builds(&prev, &curr);
        assert_eq!(diff.impact, DiffImpact::Breaking);
    }

    #[test]
    fn test_diff_impact_display() {
        assert_eq!(DiffImpact::NoChange.emoji(), "");
        assert_eq!(DiffImpact::Minor.emoji(), "🟢");
        assert_eq!(DiffImpact::Breaking.emoji(), "🔴");
    }

    // ── Glob Match Tests ──────────────────────────────────────────────────

    #[test]
    fn test_glob_match_simple() {
        assert!(glob_match("*.c", "main.c"));
        assert!(glob_match("*.cpp", "foo.cpp"));
        assert!(!glob_match("*.c", "main.h"));
        assert!(glob_match("src/*.c", "src/main.c"));
        assert!(!glob_match("src/*.c", "test/main.c"));
    }

    #[test]
    fn test_glob_match_wildcard() {
        assert!(glob_match("**/*.rs", "src/main.rs"));
        assert!(glob_match("**/*.rs", "src/clang/test.rs"));
        assert!(!glob_match("**/*.rs", "src/main.c"));
    }

    // ── SCons & Premake Tests ─────────────────────────────────────────────

    #[test]
    fn test_scons_support() {
        let scons = X86SconsSupport::new(Path::new("/tmp"));
        assert!(scons.build_command().contains("scons"));
        assert_eq!(scons.target_platform, "posix");
    }

    #[test]
    fn test_premake_support() {
        let premake = X86PremakeSupport::new(Path::new("/tmp"));
        let cmd = premake.generate_command();
        assert!(cmd.contains("premake5"));
        assert!(cmd.contains("linux"));
        assert!(cmd.contains("x86_64"));
    }

    #[test]
    fn test_premake_windows_cross() {
        let premake = X86PremakeSupport::windows_cross();
        assert_eq!(premake.action, "vs2022");
        assert_eq!(premake.os, "windows");
    }

    // ── Feature Detection Matrix Tests ────────────────────────────────────

    #[test]
    fn test_feature_matrix_contains_avx2() {
        let matrix = x86_compiler_feature_matrix();
        let avx2_entry = matrix.iter().find(|e| e.flag == "-mavx2");
        assert!(avx2_entry.is_some());
        let entry = avx2_entry.unwrap();
        assert!(entry.clang_support);
        assert!(entry.gcc_support);
    }

    #[test]
    fn test_feature_matrix_thin_lto() {
        let matrix = x86_compiler_feature_matrix();
        let thin_lto = matrix.iter().find(|e| e.flag == "-flto=thin");
        assert!(thin_lto.is_some());
        assert!(!thin_lto.unwrap().gcc_support, "ThinLTO is Clang-only");
    }

    #[test]
    fn test_feature_matrix_size() {
        let matrix = x86_compiler_feature_matrix();
        assert_eq!(matrix.len(), 10);
    }

    // ── Build Isolation Tests ─────────────────────────────────────────────

    #[test]
    fn test_isolated_env_none() {
        let env = IsolatedBuildEnv {
            isolation_type: IsolationType::None,
            root_path: None,
            packages: vec![],
            pass_env: vec![],
            work_dir: PathBuf::from("/tmp"),
            use_overlay: false,
        };
        assert!(env.command_prefix().is_empty());
    }

    #[test]
    fn test_isolated_env_chroot() {
        let env = IsolatedBuildEnv {
            isolation_type: IsolationType::Chroot,
            root_path: Some(PathBuf::from("/chroot")),
            packages: vec![],
            pass_env: vec![],
            work_dir: PathBuf::from("/tmp"),
            use_overlay: false,
        };
        let prefix = env.command_prefix();
        assert!(prefix.contains(&"chroot".to_string()));
        assert!(prefix.contains(&"/chroot".to_string()));
    }

    // ── Sub-Variant Config Tests ──────────────────────────────────────────

    #[test]
    fn test_llvm_minimal_config() {
        let config = llvm_minimal_config();
        assert_eq!(config.cmake_vars.get("LLVM_BUILD_TOOLS").unwrap(), "OFF");
        assert_eq!(config.cmake_vars.get("LLVM_BUILD_TESTS").unwrap(), "OFF");
    }

    #[test]
    fn test_llvm_fuzz_config() {
        let config = llvm_fuzz_config();
        assert_eq!(config.variant, DeepBuildVariant::Fuzz);
        assert!(config.cflags.iter().any(|f| f.contains("fuzzer")));
    }

    #[test]
    fn test_qt_core_only_config() {
        let config = qt_core_only_config();
        assert_eq!(config.cmake_vars.get("QT_FEATURE_gui").unwrap(), "OFF");
        assert_eq!(config.cmake_vars.get("QT_FEATURE_widgets").unwrap(), "OFF");
    }

    #[test]
    fn test_ffmpeg_minimal_config() {
        let config = ffmpeg_minimal_config();
        assert!(config
            .configure_flags
            .iter()
            .any(|f| f.contains("--disable-decoders")));
        assert!(config
            .configure_flags
            .iter()
            .any(|f| f.contains("--enable-decoder=h264")));
    }

    #[test]
    fn test_opencv_cuda_config() {
        let config = opencv_cuda_config();
        assert_eq!(config.cmake_vars.get("WITH_CUDA").unwrap(), "ON");
        assert_eq!(config.cmake_vars.get("OPENCV_DNN_CUDA").unwrap(), "ON");
    }

    // ── SIMD Dispatch Codegen Tests ───────────────────────────────────────

    #[test]
    fn test_simd_dispatch_code_generation() {
        let entries = vec![SimdDispatchEntry {
            function_name: "process_block".to_string(),
            base_isa: DeepSimdLevel::Sse2,
            variants: vec![
                SimdVariant {
                    isa_level: DeepSimdLevel::Avx2,
                    suffix: "_avx2".to_string(),
                    required_features: vec!["avx2".to_string()],
                },
                SimdVariant {
                    isa_level: DeepSimdLevel::Avx512F,
                    suffix: "_avx512".to_string(),
                    required_features: vec!["avx512f".to_string()],
                },
            ],
            resolver: "resolve_process_block".to_string(),
        }];
        let code = generate_simd_dispatch_code(&entries);
        assert!(code.contains("process_block"));
        assert!(code.contains("cpuid.h"));
        assert!(code.contains("cpu_has_feature"));
    }

    // ── Build Notifier Tests ──────────────────────────────────────────────

    #[test]
    fn test_notifier_format_message() {
        let notifier = BuildNotifier::default();
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        report.tus_compiled = 100;
        report.warning_count = 2;
        report.error_count = 0;
        let msg = notifier.format_message(&notifier.templates.success, &report);
        assert!(msg.contains("LLVM/Clang"));
        assert!(msg.contains("succeeded"));
    }

    // ── Platform Info Tests ───────────────────────────────────────────────

    #[test]
    fn test_platform_info_detection() {
        let info = X86PlatformInfo::detect();
        assert!(!info.cpu_model.is_empty());
        assert!(info.cpu_cores > 0);
        assert!(info.cpu_threads > 0);
        assert!(info.total_memory_mb > 0);
        assert!(!info.cpu_features.is_empty());
    }

    #[test]
    fn test_platform_info_summary() {
        let info = X86PlatformInfo::detect();
        let summary = info.summary();
        assert!(summary.contains("cores"));
        assert!(summary.contains("RAM"));
    }

    // ── Build Profiler Tests ──────────────────────────────────────────────

    #[test]
    fn test_build_profiler() {
        let mut profiler = BuildProfiler::new(DeepProjectId::Llvm);
        profiler.add_result(&["-O2".to_string()], 120.0, 50_000_000, 1000);
        profiler.add_result(&["-O3".to_string()], 180.0, 55_000_000, 950);
        profiler.add_result(&["-Os".to_string()], 90.0, 30_000_000, 1200);
        let best = profiler.evaluate();
        assert!(best.is_some());
        assert!(!profiler.configurations.is_empty());
        let report = profiler.report();
        assert!(report.contains("Build Profiling Report"));
    }

    #[test]
    fn test_build_profiler_report_contains_best() {
        let mut profiler = BuildProfiler::new(DeepProjectId::Llvm);
        profiler.add_result(&["-O2".to_string()], 100.0, 40_000_000, 1000);
        profiler.evaluate();
        let report = profiler.report();
        assert!(report.contains("Best configuration"));
    }

    // ── Toolchain Database Tests ──────────────────────────────────────────

    #[test]
    fn test_toolchain_database_size() {
        let db = x86_toolchain_database();
        assert!(db.len() >= 8);
    }

    #[test]
    fn test_find_toolchain_by_triple() {
        let toolchain = find_toolchain("x86_64-unknown-linux-gnu");
        assert!(toolchain.is_some());
        assert_eq!(toolchain.unwrap().data_model, X86DataModel::Lp64);
    }

    #[test]
    fn test_find_toolchain_musl() {
        let toolchain = find_toolchain("x86_64-unknown-linux-musl");
        assert!(toolchain.is_some());
        assert!(toolchain
            .unwrap()
            .default_ldflags
            .contains(&"-static".to_string()));
    }

    #[test]
    fn test_known_triples() {
        let triples = known_triples();
        assert!(triples.contains(&"x86_64-unknown-linux-gnu".to_string()));
        assert!(triples.contains(&"i686-unknown-linux-gnu".to_string()));
    }

    // ── Health Check Tests ────────────────────────────────────────────────

    #[test]
    fn test_health_check_runs() {
        let result = check_build_environment();
        assert!(!result.checks.is_empty());
        let report = result.print_report();
        assert!(report.contains("Build Environment Health Check"));
    }

    #[test]
    fn test_health_check_items_have_names() {
        let result = check_build_environment();
        for check in &result.checks {
            assert!(!check.name.is_empty());
        }
    }

    // ── Diagnostic Comparison Tests ───────────────────────────────────────

    #[test]
    fn test_diagnostic_comparison() {
        let clang_out = "file.c:10:5: warning: unused variable
file.c:20:1: error: expected ';'";
        let gcc_out = "file.c:10:5: warning: unused variable";
        let comparison = compare_diagnostics(clang_out, gcc_out);
        assert_eq!(comparison.clang_errors, 1);
        assert_eq!(comparison.clang_warnings, 1);
        assert_eq!(comparison.gcc_errors, 0);
        assert_eq!(comparison.gcc_warnings, 1);
    }

    #[test]
    fn test_diagnostic_comparison_summary() {
        let comparison = compare_diagnostics("error: x", "warning: y");
        let summary = comparison.summary();
        assert!(summary.contains("Clang"));
        assert!(summary.contains("GCC"));
    }

    // ── Report Export Tests ───────────────────────────────────────────────

    #[test]
    fn test_export_build_report_json() {
        let report = DeepBuildReport::new(DeepProjectId::Llvm);
        let json = export_build_report(&report, "json");
        assert!(json.contains(""project""));
        assert!(json.contains(""status""));
    }

    #[test]
    fn test_export_build_report_markdown() {
        let report = DeepBuildReport::new(DeepProjectId::Llvm);
        let md = export_build_report(&report, "markdown");
        assert!(md.contains("# Build Report"));
        assert!(md.contains("LLVM/Clang"));
    }

    #[test]
    fn test_export_test_report_junit() {
        let mut report = DeepTestReport::new(DeepProjectId::Llvm);
        report.total = 1;
        report.passed = 1;
        report.cases.push(DeepTestCase {
            suite: "TestSuite".to_string(),
            name: "test_foo".to_string(),
            passed: true,
            duration: Duration::from_millis(100),
            failure_message: None,
            output: String::new(),
            tags: vec![],
            is_flaky: false,
            skipped: false,
        });
        let xml = export_test_report(&report, "junit");
        assert!(xml.contains("testsuite"));
        assert!(xml.contains("testcase"));
    }

    // ── Project Scan Tests ────────────────────────────────────────────────

    #[test]
    fn test_scan_empty_directory() {
        let tmp = env::temp_dir().join("llvm-native-scan-empty");
        let _ = fs::create_dir_all(&tmp);
        let result = scan_for_projects(&tmp).unwrap();
        assert!(result.detected_projects.is_empty());
        assert!(result.directories_scanned > 0);
        let _ = fs::remove_dir_all(&tmp);
    }

    // ── Build Script Generation Tests ─────────────────────────────────────

    #[test]
    fn test_build_script_cmake() {
        let registry = test_registry();
        let config = llvm_deep_config();
        let script = generate_build_script(&config, &registry);
        assert!(script.contains("#!/usr/bin/env bash"));
        assert!(script.contains("cmake -G Ninja"));
        assert!(script.contains("export CC=clang"));
        assert!(script.contains("set -euo pipefail"));
    }

    #[test]
    fn test_build_script_autotools() {
        let registry = test_registry();
        let config = ffmpeg_deep_config();
        let script = generate_build_script(&config, &registry);
        assert!(script.contains("./configure"));
        assert!(script.contains("--enable-gpl"));
    }

    // ── Schedule Tests ────────────────────────────────────────────────────

    #[test]
    fn test_build_schedule_creation() {
        let schedule = BuildSchedule::new("nightly");
        assert_eq!(schedule.name, "nightly");
        assert!(schedule.enabled);
        assert!(!schedule.is_due());
        assert!(schedule.projects.is_empty());
    }

    #[test]
    fn test_build_scheduler_add() {
        let mut scheduler = BuildScheduler::new();
        scheduler.add(BuildSchedule::new("test-schedule"));
        assert_eq!(scheduler.schedules.len(), 1);
        assert!(scheduler.due_schedules().is_empty());
    }

    #[test]
    fn test_scheduler_list() {
        let mut scheduler = BuildScheduler::new();
        let mut schedule = BuildSchedule::new("nightly");
        schedule.projects = vec![DeepProjectId::Llvm];
        schedule.cron_expr = Some("0 2 * * *".to_string());
        scheduler.add(schedule);
        let list = scheduler.list_schedules();
        assert!(list.contains("nightly"));
        assert!(list.contains("llvm"));
    }

    // ── Build Metrics Tests ───────────────────────────────────────────────

    #[test]
    fn test_build_metrics_throughput() {
        let metrics = BuildMetrics {
            project_id: DeepProjectId::Llvm,
            wall_time_secs: 100.0,
            cpu_time_secs: 400.0,
            user_time_secs: 350.0,
            system_time_secs: 50.0,
            max_rss_mb: 4096.0,
            page_faults: 10000,
            context_switches: 50000,
            io_read_bytes: 100_000_000,
            io_write_bytes: 200_000_000,
            compile_units: 5000,
            link_units: 100,
            cache_hits: 4500,
            cache_misses: 500,
            success: true,
        };
        assert!(metrics.throughput_tus_per_sec() > 0.0);
        assert!(metrics.cache_hit_rate() > 0.8);
        assert!(metrics.format_summary().contains("Build Metrics"));
    }

    #[test]
    fn test_build_metrics_zero_time() {
        let metrics = BuildMetrics {
            wall_time_secs: 0.0,
            cpu_time_secs: 0.0,
            user_time_secs: 0.0,
            system_time_secs: 0.0,
            max_rss_mb: 0.0,
            page_faults: 0,
            context_switches: 0,
            io_read_bytes: 0,
            io_write_bytes: 0,
            compile_units: 0,
            link_units: 0,
            cache_hits: 0,
            cache_misses: 0,
            success: false,
            project_id: DeepProjectId::Llvm,
        };
        assert_eq!(metrics.throughput_tus_per_sec(), 0.0);
        assert_eq!(metrics.cache_hit_rate(), 0.0);
    }

    // ── Warning Baseline Tests ────────────────────────────────────────────

    #[test]
    fn test_warning_baseline_new() {
        let baseline = WarningBaseline::new(DeepProjectId::Llvm);
        assert_eq!(baseline.warning_count, 0);
        assert!(baseline.warning_hashes.is_empty());
    }

    #[test]
    fn test_warning_hash_stability() {
        let hash1 = WarningBaseline::hash_warning("unused variable 'x'", "file.c", 10);
        let hash2 = WarningBaseline::hash_warning("unused variable 'x'", "file.c", 10);
        assert_eq!(hash1, hash2);
        let hash3 = WarningBaseline::hash_warning("unused variable 'x'", "file.c", 11);
        assert_ne!(hash1, hash3);
    }

    #[test]
    fn test_warning_baseline_add() {
        let mut baseline = WarningBaseline::new(DeepProjectId::Llvm);
        let hash = WarningBaseline::hash_warning("unused variable", "file.c", 5);
        baseline.add_warning(hash.clone());
        assert_eq!(baseline.warning_count, 1);
        assert!(baseline.is_known(&hash));
    }

    // ── NEON-to-SSE Translation Tests ─────────────────────────────────────

    #[test]
    fn test_neon_to_sse_mapping() {
        let map = neon_to_sse_mapping_table();
        assert!(map.len() >= 20);
        assert_eq!(map.get("vaddq_f32").unwrap(), "_mm_add_ps");
        assert_eq!(map.get("vmulq_f32").unwrap(), "_mm_mul_ps");
    }

    #[test]
    fn test_translate_neon_to_sse_simple() {
        let neon_code = "float32x4_t a = vaddq_f32(x, y);";
        let sse_code = translate_neon_to_sse(neon_code);
        assert!(sse_code.contains("_mm_add_ps"));
        assert!(!sse_code.contains("vaddq_f32"));
    }

    #[test]
    fn test_translate_neon_adds_header() {
        let neon_code = "float32x4_t a = _mm_add_ps(x, y);";
        let result = translate_neon_to_sse(neon_code);
        assert!(result.contains("#include <xmmintrin.h>"));
    }

    // ── Static Analysis Tests ─────────────────────────────────────────────

    #[test]
    fn test_static_analysis_config_default() {
        let cfg = StaticAnalysisConfig::default();
        assert!(cfg.run_clang_tidy);
        assert!(!cfg.run_iwyu);
        assert!(cfg.warnings_as_errors);
        assert!(!cfg.tidy_checks.is_empty());
    }

    // ── Benchmark Config Tests ────────────────────────────────────────────

    #[test]
    fn test_extended_benchmark_config_default() {
        let cfg = ExtendedBenchmarkConfig::default();
        assert!(cfg.warmup);
        assert_eq!(cfg.iterations, 10);
        assert!(cfg.compare_baseline);
        assert_eq!(cfg.max_regression_pct, 5.0);
    }

    #[test]
    fn test_bench_output_formats() {
        assert_eq!(BenchOutputFormat::Json as u8, BenchOutputFormat::Json as u8);
        assert_ne!(BenchOutputFormat::Json as u8, BenchOutputFormat::Csv as u8);
    }

    // ── Exhaustive Project ID Validation Tests ───────────────────────────

    #[test]
    fn test_all_project_ids_have_display_names() {
        for id in &[
            DeepProjectId::Llvm,
            DeepProjectId::LinuxKernel,
            DeepProjectId::Qt,
            DeepProjectId::Boost,
            DeepProjectId::Ffmpeg,
            DeepProjectId::OpenCV,
            DeepProjectId::TensorFlowLite,
            DeepProjectId::Protobuf,
            DeepProjectId::Grpc,
            DeepProjectId::Abseil,
            DeepProjectId::LevelDb,
            DeepProjectId::RocksDb,
            DeepProjectId::DuckDb,
            DeepProjectId::ClickHouse,
            DeepProjectId::ScyllaDb,
        ] {
            let name = id.display_name();
            assert!(!name.is_empty(), "Missing display name for {:?}", id);
        }
    }

    #[test]
    fn test_project_id_round_trip() {
        for id_str in DEEP_PROJECT_IDS {
            let id = DeepProjectId::from_str(id_str).unwrap();
            assert_eq!(id.as_str(), id_str);
        }
    }

    #[test]
    fn test_all_simd_levels_have_mappings() {
        let levels = [
            DeepSimdLevel::None,
            DeepSimdLevel::Mmx,
            DeepSimdLevel::Sse,
            DeepSimdLevel::Sse2,
            DeepSimdLevel::Sse3,
            DeepSimdLevel::Ssse3,
            DeepSimdLevel::Sse41,
            DeepSimdLevel::Sse42,
            DeepSimdLevel::Avx,
            DeepSimdLevel::Avx2,
            DeepSimdLevel::Avx512F,
            DeepSimdLevel::Avx512Full,
        ];
        for level in &levels {
            // At minimum, None should not have march; everything else should be valid
            let _ = level.to_march_flag();
            let _ = level.to_gcc_target_flag();
        }
    }

    #[test]
    fn test_build_variant_exhaustive_as_str() {
        let variants = [
            DeepBuildVariant::Debug,
            DeepBuildVariant::Release,
            DeepBuildVariant::RelWithDebInfo,
            DeepBuildVariant::MinSizeRel,
            DeepBuildVariant::PgoInstrumented,
            DeepBuildVariant::PgoOptimized,
            DeepBuildVariant::Sanitized,
            DeepBuildVariant::Fuzz,
            DeepBuildVariant::Coverage,
            DeepBuildVariant::Custom,
        ];
        for variant in &variants {
            let s = variant.as_str();
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_build_status_exhaustive() {
        let statuses = [
            DeepBuildStatus::Pending,
            DeepBuildStatus::Configuring,
            DeepBuildStatus::Building,
            DeepBuildStatus::Success,
            DeepBuildStatus::Failed,
            DeepBuildStatus::Skipped,
            DeepBuildStatus::Cancelled,
        ];
        for status in &statuses {
            let s = status.to_string();
            assert!(!s.is_empty());
            let _ = status.is_terminal();
            let _ = status.is_running();
        }
    }

    #[test]
    fn test_sanitizer_exhaustive() {
        let sanitizers = [
            DeepSanitizer::Address,
            DeepSanitizer::Undefined,
            DeepSanitizer::Memory,
            DeepSanitizer::Thread,
            DeepSanitizer::Leak,
            DeepSanitizer::HwAddress,
            DeepSanitizer::AddressUndefined,
        ];
        for san in &sanitizers {
            let flag = san.to_cflag();
            assert!(flag.starts_with("-fsanitize="));
        }
    }

    #[test]
    fn test_build_system_exhaustive() {
        let systems = [
            DeepBuildSystem::Cmake,
            DeepBuildSystem::Make,
            DeepBuildSystem::Autotools,
            DeepBuildSystem::Meson,
            DeepBuildSystem::Bazel,
            DeepBuildSystem::BoostBuild,
            DeepBuildSystem::QMake,
            DeepBuildSystem::Kbuild,
            DeepBuildSystem::Ninja,
            DeepBuildSystem::Custom,
        ];
        for sys in &systems {
            assert!(!sys.as_str().is_empty());
        }
    }

    #[test]
    fn test_test_framework_exhaustive() {
        let frameworks = [
            DeepTestFramework::Ctest,
            DeepTestFramework::GTest,
            DeepTestFramework::BoostTest,
            DeepTestFramework::Catch2,
            DeepTestFramework::PythonUnittest,
            DeepTestFramework::ShellScript,
            DeepTestFramework::MakeCheck,
            DeepTestFramework::Custom,
        ];
        for fw in &frameworks {
            assert!(!fw.as_str().is_empty());
        }
    }

    // ── Formatting Round-Trip Tests ────────────────────────────────────────

    #[test]
    fn test_deep_project_id_display_format() {
        let id = DeepProjectId::Llvm;
        assert_eq!(format!("{}", id), "llvm");
    }

    #[test]
    fn test_deep_build_status_display() {
        assert_eq!(format!("{}", DeepBuildStatus::Success), "success");
        assert_eq!(format!("{}", DeepBuildStatus::Failed), "failed");
    }

    #[test]
    fn test_x86_diag_level_display() {
        assert_eq!(X86DiagLevel::Warning.as_str(), "warning");
        assert_eq!(X86DiagLevel::Error.as_str(), "error");
        assert_eq!(format!("{}", X86DiagLevel::Note), "note");
    }

    // ── Edge Case Tests ───────────────────────────────────────────────────

    #[test]
    fn test_empty_registry_build_order() {
        let registry = test_registry();
        let order = registry.build_order();
        assert!(order.is_empty());
    }

    #[test]
    fn test_deep_build_report_json_empty() {
        let report = DeepBuildReport::new(DeepProjectId::Llvm);
        let json = report.to_json();
        assert!(json.contains(""project":"llvm""));
        assert!(json.contains(""status":"pending""));
    }

    #[test]
    fn test_patch_non_existent_file() {
        let tmp = env::temp_dir().join("llvm-native-patch-test");
        let _ = fs::create_dir_all(&tmp);
        let patch = DeepPatch::new_inline("test", "nonexistent.c", "old", "new");
        let result = patch.apply(&tmp);
        assert!(result.is_err());
        let _ = fs::remove_dir_all(&tmp);
    }

    #[test]
    fn test_deep_stage_report_default() {
        let report = DeepStageReport::new(DeepBuildStage::Stage1);
        assert_eq!(report.status, DeepBuildStatus::Pending);
        assert_eq!(report.tus_compiled, 0);
        assert!(report.comparison_passed.is_none());
    }

    #[test]
    fn test_deep_opt_pass_default() {
        let pass = DeepOptPass {
            name: "TestPass".to_string(),
            enabled: true,
            effect: "Testing".to_string(),
            speedup_pct: Some(10.0),
            size_change_pct: Some(-5.0),
        };
        assert!(pass.enabled);
        assert_eq!(pass.speedup_pct, Some(10.0));
    }

    #[test]
    fn test_deep_opt_report_new() {
        let report = DeepOptimizationReport::new(DeepProjectId::Ffmpeg);
        assert!(!report.pgo_applied);
        assert!(!report.lto_applied);
        assert_eq!(report.binary_size_bytes, 0);
        assert!(report.summary().contains("FFmpeg"));
    }

    #[test]
    fn test_cache_hit_rate_empty() {
        let tmp = env::temp_dir().join("llvm-native-cache-empty");
        let cache = DeepBuildCache::new(&tmp);
        assert!((cache.hit_rate() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_x86_target_os_exhaustive() {
        let os_list = [
            X86TargetOs::Linux,
            X86TargetOs::Windows,
            X86TargetOs::MacOs,
            X86TargetOs::FreeBsd,
            X86TargetOs::NetBsd,
            X86TargetOs::OpenBsd,
            X86TargetOs::Android,
            X86TargetOs::Ios,
            X86TargetOs::None_,
        ];
        for os in &os_list {
            assert!(!os.as_str().is_empty());
            assert!(!os.cmake_name().is_empty());
        }
    }

    #[test]
    fn test_archive_format_exhaustive() {
        let formats = [
            ArchiveFormat::TarGz,
            ArchiveFormat::TarXz,
            ArchiveFormat::TarBz2,
            ArchiveFormat::TarZstd,
            ArchiveFormat::Zip,
            ArchiveFormat::SevenZip,
        ];
        for fmt in &formats {
            assert!(!fmt.extension().is_empty());
            assert!(!fmt.mime_type().is_empty());
        }
    }

    #[test]
    fn test_checksum_algorithm_exhaustive() {
        let algos = [
            ChecksumAlgorithm::Md5,
            ChecksumAlgorithm::Sha1,
            ChecksumAlgorithm::Sha256,
            ChecksumAlgorithm::Sha512,
            ChecksumAlgorithm::Blake3,
        ];
        for algo in &algos {
            assert!(!algo.as_str().is_empty());
            assert!(!algo.command().is_empty());
        }
    }

    #[test]
    fn test_container_runtime_exhaustive() {
        let runtimes = [
            ContainerRuntime::Docker,
            ContainerRuntime::Podman,
            ContainerRuntime::Singularity,
            ContainerRuntime::Enroot,
        ];
        for rt in &runtimes {
            assert!(!rt.command().is_empty());
        }
    }

    #[test]
    fn test_ci_system_exhaustive() {
        let systems = [
            CISystem::GitHubActions,
            CISystem::GitLabCI,
            CISystem::Jenkins,
            CISystem::Buildkite,
            CISystem::CircleCI,
            CISystem::TravisCI,
            CISystem::AzurePipelines,
        ];
        for sys in &systems {
            assert!(!sys.as_str().is_empty());
        }
    }

    #[test]
    fn test_isolation_type_exhaustive() {
        let types = [
            IsolationType::None,
            IsolationType::Chroot,
            IsolationType::SystemdNspawn,
            IsolationType::Bubblewrap,
            IsolationType::Firejail,
            IsolationType::DockerContainer,
        ];
        for t in &types {
            // Just verify they exist and have values
            let _ = format!("{:?}", t);
        }
    }

    #[test]
    fn test_diff_impact_exhaustive() {
        let impacts = [
            DiffImpact::NoChange,
            DiffImpact::Minor,
            DiffImpact::Moderate,
            DiffImpact::Major,
            DiffImpact::Breaking,
        ];
        for imp in &impacts {
            assert!(!imp.as_str().is_empty());
            assert!(!imp.emoji().is_empty());
        }
    }

    #[test]
    fn test_finding_severity_exhaustive() {
        let severities = [
            FindingSeverity::Note,
            FindingSeverity::Warning,
            FindingSeverity::Error,
            FindingSeverity::Fatal,
        ];
        for _sev in &severities {
            // Verify they can be formatted
            let _ = format!("{:?}", _sev);
        }
    }

    // ── Comprehensive Factory Function Test ───────────────────────────────

    #[test]
    fn test_all_factory_functions_consistency() {
        let factories: Vec<(&str, fn() -> DeepProjectConfig)> = vec![
            ("llvm", llvm_deep_config),
            ("llvm-minimal", llvm_minimal_config),
            ("llvm-fuzz", llvm_fuzz_config),
            ("llvm-bootstrap", llvm_bootstrap_config),
            ("linux-kernel", linux_kernel_deep_config),
            ("linux-kernel-i386", linux_kernel_i386_config),
            ("qt", qt_deep_config),
            ("qt-core", qt_core_only_config),
            ("boost", boost_deep_config),
            ("ffmpeg", ffmpeg_deep_config),
            ("ffmpeg-minimal", ffmpeg_minimal_config),
            ("opencv", opencv_deep_config),
            ("opencv-cuda", opencv_cuda_config),
            ("tensorflow-lite", tensorflow_lite_deep_config),
            ("protobuf", protobuf_deep_config),
            ("grpc", grpc_deep_config),
            ("abseil", abseil_deep_config),
            ("leveldb", leveldb_deep_config),
            ("rocksdb", rocksdb_deep_config),
            ("duckdb", duckdb_deep_config),
            ("clickhouse", clickhouse_deep_config),
            ("scylladb", scylladb_deep_config),
        ];

        for (label, factory) in factories {
            let config = factory();
            assert!(
                !config.name.is_empty(),
                "Factory '{}' produced config with empty name",
                label
            );
            assert!(
                !config.version.is_empty(),
                "Factory '{}' produced config with empty version",
                label
            );
        }
    }

    // ── Test for report export scenarios ──────────────────────────────────

    #[test]
    fn test_export_build_report_with_test_results() {
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        let mut test_report = DeepTestReport::new(DeepProjectId::Llvm);
        test_report.total = 10;
        test_report.passed = 9;
        test_report.failed = 1;
        report.test_report = Some(test_report);
        let md = export_build_report(&report, "markdown");
        assert!(md.contains("Test Results"));
        assert!(md.contains("9/10"));
    }

    #[test]
    fn test_export_build_report_with_optimizations() {
        let mut report = DeepBuildReport::new(DeepProjectId::Llvm);
        let mut opt_report = DeepOptimizationReport::new(DeepProjectId::Llvm);
        opt_report.pgo_applied = true;
        opt_report.pgo_speedup_pct = Some(12.0);
        report.opt_report = Some(opt_report);
        let md = export_build_report(&report, "markdown");
        assert!(md.contains("Optimizations"));
    }

    // ── X86PlatformInfo Detection Tests ───────────────────────────────────

    #[test]
    fn test_platform_info_has_cpu_model() {
        let info = X86PlatformInfo::detect();
        assert!(!info.cpu_model.is_empty(), "CPU model should not be empty");
    }

    #[test]
    fn test_platform_info_has_features() {
        let info = X86PlatformInfo::detect();
        assert!(
            !info.cpu_features.is_empty(),
            "CPU features should not be empty"
        );
        // On x86-64, SSE2 should always be present
        assert!(
            info.cpu_features.iter().any(|f| f.contains("sse2")),
            "SSE2 should be present on any x86-64 system"
        );
    }

    #[test]
    fn test_platform_info_kernel_version() {
        let info = X86PlatformInfo::detect();
        assert!(
            !info.kernel_version.is_empty(),
            "Kernel version should not be empty"
        );
    }

    // ── NeonToSse Translation Edge Cases ──────────────────────────────────

    #[test]
    fn test_neon_translation_no_change_for_pure_sse() {
        let sse_code = "_mm_add_ps(a, b);";
        let result = translate_neon_to_sse(sse_code);
        // Should still contain the SSE intrinsic
        assert!(result.contains("_mm_add_ps"));
    }

    #[test]
    fn test_neon_translation_empty_input() {
        let result = translate_neon_to_sse("");
        assert!(result.is_empty());
    }

    // ── Content-Addressed Cache Tests ─────────────────────────────────────

    #[test]
    fn test_content_addressed_cache_new() {
        let tmp = env::temp_dir().join("llvm-native-cac-test");
        let cache = ContentAddressedCache::new(&tmp);
        assert!(!cache.writable);
        assert_eq!(cache.estimated_size, 0);
        assert!(cache.remote_endpoint.is_none());
    }

    // ── Extended Benchmark Parsing Tests ──────────────────────────────────

    #[test]
    fn test_bench_measurement_defaults() {
        let measurement = BenchMeasurement {
            name: "test_bench".to_string(),
            iterations: 100,
            real_time_ns: 1000,
            cpu_time_ns: 950,
            time_unit: "ns".to_string(),
            bytes_per_second: 1_000_000,
            items_per_second: 500_000,
            counters: HashMap::new(),
            label: None,
        };
        assert_eq!(measurement.iterations, 100);
        assert!(measurement.real_time_ns > 0);
    }

    // ── Build Profiler Score Consistency Tests ────────────────────────────

    #[test]
    fn test_build_profiler_better_score_for_faster_runtime() {
        let mut profiler = BuildProfiler::new(DeepProjectId::Llvm);
        // Same build time and size, faster runtime => higher score
        profiler.add_result(&["-O2".to_string()], 100.0, 50_000_000, 500);
        profiler.add_result(&["-O3".to_string()], 100.0, 50_000_000, 1000);
        profiler.evaluate();
        let best = profiler.best_config.as_ref().unwrap();
        // The faster runtime (500ns) should score higher and be ranked first
        assert_eq!(best.runtime_perf_ns_per_iter, 500);
    }

    // ── Project Scan Edge Cases ───────────────────────────────────────────

    #[test]
    fn test_scan_non_existent_directory() {
        let result = scan_for_projects(Path::new("/nonexistent/path/for/testing"));
        // Should not panic; may return Ok with empty results
        match result {
            Ok(r) => assert!(r.detected_projects.is_empty()),
            Err(_) => { /* also acceptable - OS-specific behavior */ }
        }
    }

    // ── Final Integration Test ────────────────────────────────────────────

    #[test]
    fn test_comprehensive_registry_workflow() {
        let mut registry = test_registry();
        registry.register_default_projects();
        registry.init_subsystems();

        // Verify all 15 projects registered
        assert_eq!(registry.projects.len(), 15);

        // Build order should contain all projects
        let order = registry.build_order();
        assert_eq!(order.len(), 15);

        // No duplicate entries
        let unique: HashSet<_> = order.iter().copied().collect();
        assert_eq!(unique.len(), order.len());

        // Generate toolchain
        let toolchain = registry.generate_toolchain_file();
        assert!(toolchain.contains("clang"));
        assert!(toolchain.contains("Linux"));

        // Generate presets
        let presets = generate_cmake_presets(&registry);
        assert!(presets.contains("version"));

        // Validate dependencies (Abseil has no deps, so should be fine)
        let issues = registry.validate_dependencies();
        // Some projects depend on others, so issues may exist
        // but at minimum they should be reported, not panic
        let _ = issues.len();

        // Build summary with no builds yet
        let summary = build_summary(&[]);
        assert!(summary.contains("0 total"));

        // Test summary with no results
        let empty_tests = BTreeMap::new();
        let test_summ = test_summary(&empty_tests);
        assert!(test_summ.contains("Projects tested: 0"));
    }

    #[test]
    fn test_all_deep_project_ids_enumerable() {
        // Test that we can enumerate all 15 projects
        let all_ids = [
            DeepProjectId::Llvm,
            DeepProjectId::LinuxKernel,
            DeepProjectId::Qt,
            DeepProjectId::Boost,
            DeepProjectId::Ffmpeg,
            DeepProjectId::OpenCV,
            DeepProjectId::TensorFlowLite,
            DeepProjectId::Protobuf,
            DeepProjectId::Grpc,
            DeepProjectId::Abseil,
            DeepProjectId::LevelDb,
            DeepProjectId::RocksDb,
            DeepProjectId::DuckDb,
            DeepProjectId::ClickHouse,
            DeepProjectId::ScyllaDb,
        ];
        assert_eq!(all_ids.len(), DEEP_PROJECT_IDS.len());
        for id in &all_ids {
            assert!(DEEP_PROJECT_IDS.contains(&id.as_str()));
        }
    }

    #[test]
    fn test_simd_level_total_order() {
        let levels = vec![
            DeepSimdLevel::None,
            DeepSimdLevel::Mmx,
            DeepSimdLevel::Sse,
            DeepSimdLevel::Sse2,
            DeepSimdLevel::Sse3,
            DeepSimdLevel::Ssse3,
            DeepSimdLevel::Sse41,
            DeepSimdLevel::Sse42,
            DeepSimdLevel::Avx,
            DeepSimdLevel::Avx2,
            DeepSimdLevel::Avx512F,
            DeepSimdLevel::Avx512Full,
        ];
        for i in 0..levels.len() - 1 {
            assert!(
                levels[i + 1] > levels[i],
                "{:?} should be greater than {:?}",
                levels[i + 1],
                levels[i]
            );
        }
    }

    #[test]
    fn test_deep_build_stage_total_order() {
        let stages = vec![
            DeepBuildStage::Stage0,
            DeepBuildStage::Stage1,
            DeepBuildStage::Stage2,
            DeepBuildStage::Stage3,
        ];
        for i in 0..stages.len() - 1 {
            assert!(
                stages[i + 1] > stages[i],
                "{:?} should be greater than {:?}",
                stages[i + 1],
                stages[i]
            );
        }
        assert_eq!(DeepBuildStage::Stage0.index(), 0);
        assert_eq!(DeepBuildStage::Stage3.index(), 3);
        assert_eq!(DeepBuildStage::Single.index(), 0);
    }

    #[test]
    fn test_patch_categories_constants() {
        assert!(!PATCH_CATEGORY_BUILD_FIX.is_empty());
        assert!(!PATCH_CATEGORY_COMPATIBILITY.is_empty());
        assert!(!PATCH_CATEGORY_PERFORMANCE.is_empty());
        assert!(!PATCH_CATEGORY_SECURITY.is_empty());
        assert!(!PATCH_CATEGORY_X86_SPECIFIC.is_empty());
        assert!(!PATCH_CATEGORY_CLANG_COMPAT.is_empty());
    }

    #[test]
    fn test_deep_lto_config_compiler_flags() {
        let mut lto = DeepLtoConfig::default();
        lto.enabled = true;
        lto.mode = "thin".to_string();
        let flags = lto.compiler_flags();
        assert!(flags.iter().any(|f| f.contains("flto=thin")));
        let linker_flags = lto.linker_flags();
        assert!(linker_flags.iter().any(|f| f.contains("flto=thin")));
    }

    #[test]
    fn test_deep_lto_config_full_mode() {
        let mut lto = DeepLtoConfig::default();
        lto.enabled = true;
        lto.mode = "full".to_string();
        let flags = lto.compiler_flags();
        assert!(flags.iter().any(|f| f.contains("flto=full")));
    }

    #[test]
    fn test_bolt_modes_constant() {
        assert!(!BOLT_MODES.is_empty());
        assert!(BOLT_MODES.contains(&"hfsort"));
        assert!(BOLT_MODES.contains(&"hfsort+"));
        assert!(BOLT_MODES.contains(&"cdsplit"));
    }
}