domainforge-core 0.13.0

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
use crate::graph::Graph;
use crate::parser::error::{ParseError, ParseResult};
use crate::parser::{ParseOptions, Rule, SeaParser};
use crate::patterns::Pattern;
use crate::policy::{
    AggregateFunction, BinaryOp, Expression, Policy, PolicyKind as CorePolicyKind,
    PolicyModality as CorePolicyModality, Quantifier as PolicyQuantifier, UnaryOp, WindowSpec,
};
use crate::primitives::{ConceptChange, Entity, Flow, RelationType, Resource, Role, Severity};
use crate::units::unit_from_string;
use crate::SemanticVersion;
use chrono::Duration;
use pest::iterators::{Pair, Pairs};
use pest::{Parser, Span};
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_json::Value as JsonValue;
use std::collections::HashMap;

/// File-level metadata from header annotations
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FileMetadata {
    pub namespace: Option<String>,
    pub version: Option<String>,
    pub owner: Option<String>,
    pub profile: Option<String>,
    pub imports: Vec<ImportDecl>,
}

/// Import declaration for a module file
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportDecl {
    pub specifier: ImportSpecifier,
    pub from_module: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ImportSpecifier {
    Named(Vec<ImportItem>),
    Wildcard(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportItem {
    pub name: String,
    pub alias: Option<String>,
}

/// Policy metadata
#[derive(Debug, Clone, PartialEq)]
pub struct PolicyMetadata {
    pub kind: Option<PolicyKind>,
    pub modality: Option<PolicyModality>,
    pub priority: Option<i32>,
    pub rationale: Option<String>,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum PolicyKind {
    Constraint,
    Derivation,
    Obligation,
}

impl std::fmt::Display for PolicyKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PolicyKind::Constraint => write!(f, "Constraint"),
            PolicyKind::Derivation => write!(f, "Derivation"),
            PolicyKind::Obligation => write!(f, "Obligation"),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum PolicyModality {
    Obligation,
    Prohibition,
    Permission,
}

impl std::fmt::Display for PolicyModality {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PolicyModality::Obligation => write!(f, "Obligation"),
            PolicyModality::Prohibition => write!(f, "Prohibition"),
            PolicyModality::Permission => write!(f, "Permission"),
        }
    }
}

/// Metric declaration AST node
#[derive(Debug, Clone, PartialEq)]
pub struct MetricMetadata {
    pub refresh_interval: Option<Duration>,
    pub unit: Option<String>,
    pub threshold: Option<Decimal>,
    pub severity: Option<Severity>,
    pub target: Option<Decimal>,
    pub window: Option<Duration>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TargetFormat {
    Calm,
    Kg,
    Sbvr,
    Protobuf,
}

impl std::fmt::Display for TargetFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TargetFormat::Calm => write!(f, "CALM"),
            TargetFormat::Kg => write!(f, "KG"),
            TargetFormat::Sbvr => write!(f, "SBVR"),
            TargetFormat::Protobuf => write!(f, "Protobuf"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MappingRule {
    pub primitive_type: String,
    pub primitive_name: String,
    pub target_type: String,
    pub fields: HashMap<String, JsonValue>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProjectionOverride {
    pub primitive_type: String,
    pub primitive_name: String,
    pub fields: HashMap<String, JsonValue>,
}

/// Abstract Syntax Tree for SEA DSL
/// Abstract Syntax Tree for SEA DSL
#[derive(Debug, Clone, PartialEq)]
pub struct Spanned<T> {
    pub node: T,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Ast {
    pub metadata: FileMetadata,
    pub declarations: Vec<Spanned<AstNode>>,
}

/// AST Node types
#[derive(Debug, Clone, PartialEq)]
pub enum AstNode {
    Export(Box<Spanned<AstNode>>),
    Entity {
        name: String,
        version: Option<String>,
        annotations: HashMap<String, JsonValue>,
        domain: Option<String>,
    },
    Resource {
        name: String,
        annotations: HashMap<String, JsonValue>,
        unit_name: Option<String>,
        domain: Option<String>,
    },
    Flow {
        resource_name: String,
        annotations: HashMap<String, JsonValue>,
        from_entity: String,
        to_entity: String,
        quantity: Option<Decimal>,
    },
    Pattern {
        name: String,
        regex: String,
    },
    Role {
        name: String,
        domain: Option<String>,
    },
    Relation {
        name: String,
        subject_role: String,
        predicate: String,
        object_role: String,
        via_flow: Option<String>,
    },
    Dimension {
        name: String,
    },
    UnitDeclaration {
        symbol: String,
        dimension: String,
        factor: Decimal,
        base_unit: String,
    },
    Policy {
        name: String,
        version: Option<String>,
        metadata: PolicyMetadata,
        expression: Expression,
    },
    Instance {
        name: String,
        entity_type: String,
        fields: HashMap<String, Expression>,
    },
    ConceptChange {
        name: String,
        from_version: String,
        to_version: String,
        migration_policy: String,
        breaking_change: bool,
    },
    Metric {
        name: String,
        expression: Expression,
        metadata: MetricMetadata,
    },
    MappingDecl {
        name: String,
        target: TargetFormat,
        rules: Vec<MappingRule>,
    },
    ProjectionDecl {
        name: String,
        target: TargetFormat,
        overrides: Vec<ProjectionOverride>,
    },
}

/// Parse source code into an AST
pub fn parse_source(source: &str) -> ParseResult<Ast> {
    let pairs = SeaParser::parse(Rule::program, source)?;
    build_ast(pairs)
}

/// Build AST from pest pairs
fn build_ast(pairs: Pairs<Rule>) -> ParseResult<Ast> {
    let mut metadata = FileMetadata::default();
    let mut declarations = Vec::new();

    for pair in pairs {
        match pair.as_rule() {
            Rule::program => {
                for inner in pair.into_inner() {
                    match inner.as_rule() {
                        Rule::file_header => {
                            metadata = parse_file_header(inner)?;
                        }
                        Rule::declaration => {
                            for decl in inner.into_inner() {
                                let node = parse_declaration(decl)?;
                                declarations.push(node);
                            }
                        }
                        Rule::EOI => {}
                        _ => {}
                    }
                }
            }
            Rule::EOI => {}
            _ => {}
        }
    }

    Ok(Ast {
        metadata,
        declarations,
    })
}

/// Parse file header annotations
fn parse_file_header(pair: Pair<Rule>) -> ParseResult<FileMetadata> {
    let mut metadata = FileMetadata::default();

    for annotation in pair.into_inner() {
        match annotation.as_rule() {
            Rule::annotation => {
                let mut inner = annotation.into_inner();
                let name = inner.next().ok_or_else(|| {
                    ParseError::GrammarError("Expected annotation name".to_string())
                })?;
                let value = inner.next().ok_or_else(|| {
                    ParseError::GrammarError("Expected annotation value".to_string())
                })?;

                let name_str = name.as_str().to_lowercase();
                let value_str = parse_string_literal(value)?;

                match name_str.as_str() {
                    "namespace" => metadata.namespace = Some(value_str),
                    "version" => metadata.version = Some(value_str),
                    "owner" => metadata.owner = Some(value_str),
                    "profile" => metadata.profile = Some(value_str),
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unknown annotation: {}",
                            name_str
                        )))
                    }
                }
            }
            Rule::import_decl => {
                metadata.imports.push(parse_import_decl(annotation)?);
            }
            _ => {}
        }
    }

    Ok(metadata)
}

/// Parse a single declaration
fn parse_declaration(pair: Pair<Rule>) -> ParseResult<Spanned<AstNode>> {
    let (line, column) = pair.line_col();
    let node = match pair.as_rule() {
        Rule::export_decl => {
            let mut inner = pair.into_inner();
            let wrapped = inner.next().ok_or_else(|| {
                ParseError::GrammarError("Expected declaration after export".to_string())
            })?;
            let node = parse_declaration(wrapped)?;
            Ok(AstNode::Export(Box::new(node)))
        }
        Rule::declaration_inner => {
            let inner = pair
                .into_inner()
                .next()
                .ok_or_else(|| ParseError::GrammarError("Empty declaration".to_string()))?;
            // Recursively call parse_declaration, but we need to unwrap the result if we want to avoid double spanning?
            // Actually declaration_inner is just a wrapper. The inner parse_declaration returns Spanned<AstNode>.
            // We should just return that directly.
            return parse_declaration(inner);
        }
        Rule::dimension_decl => parse_dimension(pair),
        Rule::unit_decl => parse_unit_declaration(pair),
        Rule::entity_decl => parse_entity(pair),
        Rule::resource_decl => parse_resource(pair),
        Rule::flow_decl => parse_flow(pair),
        Rule::pattern_decl => parse_pattern(pair),
        Rule::role_decl => parse_role(pair),
        Rule::relation_decl => parse_relation(pair),
        Rule::instance_decl => parse_instance(pair),
        Rule::policy_decl => parse_policy(pair),
        Rule::concept_change_decl => parse_concept_change(pair),
        Rule::metric_decl => parse_metric(pair),
        Rule::mapping_decl => parse_mapping(pair),
        Rule::projection_decl => parse_projection(pair),
        _ => Err(ParseError::GrammarError(format!(
            "Unexpected rule: {:?}",
            pair.as_rule()
        ))),
    }?;

    Ok(Spanned { node, line, column })
}

fn parse_import_decl(pair: Pair<Rule>) -> ParseResult<ImportDecl> {
    let mut inner = pair.into_inner();
    let specifier_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Missing import specifier".to_string()))?;
    let from_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Missing import source".to_string()))?;

    let specifier = match specifier_pair.as_rule() {
        Rule::import_specifier | Rule::import_named | Rule::import_wildcard => {
            parse_import_specifier(specifier_pair)?
        }
        _ => {
            return Err(ParseError::GrammarError(format!(
                "Unexpected import specifier: {:?}",
                specifier_pair.as_rule()
            )))
        }
    };

    Ok(ImportDecl {
        specifier,
        from_module: parse_string_literal(from_pair)?,
    })
}

fn parse_import_specifier(pair: Pair<Rule>) -> ParseResult<ImportSpecifier> {
    match pair.as_rule() {
        Rule::import_wildcard => {
            let mut inner = pair.into_inner();
            let alias = parse_identifier(inner.next().ok_or_else(|| {
                ParseError::GrammarError("Expected alias for wildcard import".to_string())
            })?)?;
            Ok(ImportSpecifier::Wildcard(alias))
        }
        Rule::import_specifier | Rule::import_named => {
            let mut items = Vec::new();
            for item in pair.into_inner() {
                if item.as_rule() == Rule::import_item {
                    items.push(parse_import_item(item)?);
                }
            }
            Ok(ImportSpecifier::Named(items))
        }
        _ => Err(ParseError::GrammarError(
            "Invalid import specifier".to_string(),
        )),
    }
}

fn parse_import_item(pair: Pair<Rule>) -> ParseResult<ImportItem> {
    let mut inner = pair.into_inner();
    let name_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected import item name".to_string()))?;
    let alias = inner.next().map(parse_identifier).transpose()?;

    Ok(ImportItem {
        name: parse_identifier(name_pair)?,
        alias,
    })
}

/// Parse dimension declaration
fn parse_dimension(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();
    let name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected dimension name".to_string()))?,
    )?;

    Ok(AstNode::Dimension { name })
}

/// Parse unit declaration
fn parse_unit_declaration(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let symbol = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected unit symbol".to_string()))?,
    )?;

    let dimension = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected dimension name".to_string()))?,
    )?;

    let factor_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected factor".to_string()))?;
    let factor = parse_decimal(factor_pair)?;

    let base_unit = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected base unit".to_string()))?,
    )?;

    Ok(AstNode::UnitDeclaration {
        symbol,
        dimension,
        factor,
        base_unit,
    })
}

/// Parse entity declaration
fn parse_entity(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected entity name".to_string()))?,
    )?;

    let mut version = None;
    let mut annotations = HashMap::new();
    let mut domain = None;

    for part in inner {
        match part.as_rule() {
            Rule::version => {
                version = Some(part.as_str().to_string());
            }
            Rule::entity_annotation => {
                let mut annotation_inner = part.into_inner();
                let key_pair = annotation_inner
                    .next()
                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;

                match key_pair.as_rule() {
                    Rule::ea_replaces => {
                        let target_name =
                            parse_name(annotation_inner.next().ok_or_else(|| {
                                ParseError::GrammarError("Expected name in replaces".to_string())
                            })?)?;
                        // Check for optional version
                        let mut target_version = None;
                        if let Some(next) = annotation_inner.next() {
                            if next.as_rule() == Rule::version {
                                target_version = Some(next.as_str().to_string());
                            }
                        }

                        let value = if let Some(v) = target_version {
                            format!("{} v{}", target_name, v)
                        } else {
                            target_name
                        };
                        annotations.insert("replaces".to_string(), JsonValue::String(value));
                    }
                    Rule::ea_changes => {
                        let array_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected string array in changes".to_string())
                        })?;
                        let mut changes = Vec::new();
                        for item in array_pair.into_inner() {
                            changes.push(parse_string_literal(item)?);
                        }
                        annotations.insert(
                            "changes".to_string(),
                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
                        );
                    }
                    Rule::identifier => {
                        let key = parse_identifier(key_pair)?.to_lowercase();
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected annotation value".to_string())
                        })?;
                        let value = parse_annotation_value(value_pair)?;
                        println!("debug insert annotation {} = {:?}", key, value);
                        annotations.insert(key, value);
                    }
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unexpected flow annotation: {}",
                            key_pair.as_str()
                        )));
                    }
                }
            }
            Rule::in_keyword => {
                // Skip "in"
            }
            Rule::identifier => {
                // This must be the domain
                domain = Some(parse_identifier(part)?);
            }
            _ => {}
        }
    }

    Ok(AstNode::Entity {
        name,
        version,
        annotations,
        domain,
    })
}

/// Parse concept change declaration
fn parse_concept_change(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name =
        parse_name(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected concept change name".to_string())
        })?)?;

    let mut from_version = String::new();
    let mut to_version = String::new();
    let mut migration_policy = String::new();
    let mut breaking_change = false;

    for part in inner {
        if part.as_rule() == Rule::concept_change_annotation {
            let mut annotation_inner = part.into_inner();

            let key_pair = annotation_inner
                .next()
                .ok_or_else(|| ParseError::GrammarError("Expected annotation key".to_string()))?;
            let value_pair = annotation_inner
                .next()
                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;

            match key_pair.as_rule() {
                Rule::cc_from_version => from_version = parse_version(value_pair)?,
                Rule::cc_to_version => to_version = parse_version(value_pair)?,
                Rule::cc_migration_policy => migration_policy = parse_identifier(value_pair)?,
                Rule::cc_breaking_change => {
                    breaking_change = value_pair.as_str() == "true";
                }
                _ => {}
            }
        }
    }

    if from_version.is_empty() {
        return Err(ParseError::GrammarError(
            "Missing cc_from_version annotation".to_string(),
        ));
    }

    if to_version.is_empty() {
        return Err(ParseError::GrammarError(
            "Missing cc_to_version annotation".to_string(),
        ));
    }

    if migration_policy.is_empty() {
        return Err(ParseError::GrammarError(
            "Missing cc_migration_policy annotation".to_string(),
        ));
    }

    Ok(AstNode::ConceptChange {
        name,
        from_version,
        to_version,
        migration_policy,
        breaking_change,
    })
}

/// Parse resource declaration
fn parse_resource(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
    )?;

    let mut annotations = HashMap::new();
    let mut unit_name = None;
    let mut domain = None;
    let mut saw_in_keyword = false;

    for part in inner {
        match part.as_rule() {
            Rule::resource_annotation => {
                let mut annotation_inner = part.into_inner();
                let key_pair = annotation_inner
                    .next()
                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;

                match key_pair.as_rule() {
                    Rule::ea_replaces => {
                        let target_name =
                            parse_name(annotation_inner.next().ok_or_else(|| {
                                ParseError::GrammarError("Expected name in replaces".to_string())
                            })?)?;
                        // Check for optional version
                        let mut target_version = None;
                        if let Some(next) = annotation_inner.next() {
                            if next.as_rule() == Rule::version {
                                target_version = Some(next.as_str().to_string());
                            }
                        }

                        let value = if let Some(v) = target_version {
                            format!("{} v{}", target_name, v)
                        } else {
                            target_name
                        };
                        annotations.insert("replaces".to_string(), JsonValue::String(value));
                    }
                    Rule::ea_changes => {
                        let array_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected string array in changes".to_string())
                        })?;
                        let mut changes = Vec::new();
                        for item in array_pair.into_inner() {
                            changes.push(parse_string_literal(item)?);
                        }
                        annotations.insert(
                            "changes".to_string(),
                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
                        );
                    }
                    Rule::identifier => {
                        let key = parse_identifier(key_pair)?.to_lowercase();
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected annotation value".to_string())
                        })?;
                        let value = parse_annotation_value(value_pair)?;
                        annotations.insert(key, value);
                    }
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unexpected flow annotation: {}",
                            key_pair.as_str()
                        )));
                    }
                }
            }
            Rule::in_keyword => {
                // Mark that we've seen 'in', next identifier is domain
                saw_in_keyword = true;
            }
            Rule::identifier => {
                // If we've seen 'in' keyword, this is domain; otherwise it's unit
                if saw_in_keyword {
                    domain = Some(parse_identifier(part)?);
                    saw_in_keyword = false; // Reset for safety
                } else {
                    unit_name = Some(parse_identifier(part)?);
                }
            }
            _ => {}
        }
    }

    Ok(AstNode::Resource {
        name,
        annotations,
        unit_name,
        domain,
    })
}

/// Parse flow declaration
fn parse_flow(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let resource_name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
    )?;

    let mut annotations = HashMap::new();
    let mut from_entity = None;
    let mut to_entity = None;
    let mut quantity = None;
    let mut pending_annotation_key: Option<String> = None;

    for part in inner {
        match part.as_rule() {
            Rule::flow_annotation => {
                let mut annotation_inner = part.into_inner();
                let key_pair = annotation_inner
                    .next()
                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;

                match key_pair.as_rule() {
                    Rule::ea_replaces => {
                        let target_name =
                            parse_name(annotation_inner.next().ok_or_else(|| {
                                ParseError::GrammarError("Expected name in replaces".to_string())
                            })?)?;
                        // Check for optional version
                        let mut target_version = None;
                        if let Some(next) = annotation_inner.next() {
                            if next.as_rule() == Rule::version {
                                target_version = Some(next.as_str().to_string());
                            }
                        }

                        let value = if let Some(v) = target_version {
                            format!("{} v{}", target_name, v)
                        } else {
                            target_name
                        };
                        annotations.insert("replaces".to_string(), JsonValue::String(value));
                    }
                    Rule::ea_changes => {
                        let array_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected string array in changes".to_string())
                        })?;
                        let mut changes = Vec::new();
                        for item in array_pair.into_inner() {
                            changes.push(parse_string_literal(item)?);
                        }
                        annotations.insert(
                            "changes".to_string(),
                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
                        );
                    }
                    Rule::identifier => {
                        let key = parse_identifier(key_pair)?.to_lowercase();
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected annotation value".to_string())
                        })?;
                        let value = parse_annotation_value(value_pair)?;
                        annotations.insert(key, value);
                    }
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unexpected flow annotation: {}",
                            key_pair.as_str()
                        )));
                    }
                }
            }
            Rule::identifier => {
                if pending_annotation_key.is_some() {
                    return Err(ParseError::GrammarError(
                        "Unexpected annotation key without value".to_string(),
                    ));
                }
                pending_annotation_key = Some(parse_identifier(part)?.to_lowercase());
            }
            Rule::annotation_value
            | Rule::object_literal
            | Rule::string_array
            | Rule::boolean
            | Rule::number
            | Rule::string_literal => {
                if let Some(key) = pending_annotation_key.take() {
                    let value = parse_annotation_value(part)?;
                    annotations.insert(key, value);
                    continue;
                }

                if part.as_rule() == Rule::string_literal {
                    // These are from_entity and to_entity in order
                    let parsed = parse_string_literal(part)?;
                    if from_entity.is_none() {
                        from_entity = Some(parsed);
                    } else if to_entity.is_none() {
                        to_entity = Some(parsed);
                    }
                } else if part.as_rule() == Rule::number {
                    quantity = Some(parse_decimal(part)?);
                }
            }
            _ => {}
        }
    }

    Ok(AstNode::Flow {
        resource_name,
        annotations,
        from_entity: from_entity
            .ok_or_else(|| ParseError::GrammarError("Expected from entity".to_string()))?,
        to_entity: to_entity
            .ok_or_else(|| ParseError::GrammarError("Expected to entity".to_string()))?,
        quantity,
    })
}

/// Parse pattern declaration
fn parse_pattern(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected pattern name".to_string()))?,
    )?;

    let regex_literal = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected regex for pattern".to_string()))?;
    let regex = parse_string_literal(regex_literal)?;

    Ok(AstNode::Pattern { name, regex })
}

/// Parse role declaration
fn parse_role(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected role name".to_string()))?,
    )?;

    let mut domain = None;
    for part in inner {
        match part.as_rule() {
            Rule::in_keyword => {
                // Skip "in"
            }
            Rule::identifier => {
                domain = Some(parse_identifier(part)?);
            }
            _ => {}
        }
    }

    Ok(AstNode::Role { name, domain })
}

/// Parse relation declaration
fn parse_relation(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected relation name".to_string()))?,
    )?;

    let subject_literal = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected subject role in relation".to_string()))?;
    let subject_role = parse_string_literal(subject_literal)?;

    let predicate_literal = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected predicate in relation".to_string()))?;
    let predicate = parse_string_literal(predicate_literal)?;

    let object_literal = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected object role in relation".to_string()))?;
    let object_role = parse_string_literal(object_literal)?;

    let via_flow = if let Some(via_pair) = inner.next() {
        match via_pair.as_rule() {
            Rule::string_literal => Some(parse_string_literal(via_pair)?),
            _ => {
                let mut via_inner = via_pair.into_inner();
                let flow_literal = via_inner.next().ok_or_else(|| {
                    ParseError::GrammarError("Expected flow name after via".to_string())
                })?;
                Some(parse_string_literal(flow_literal)?)
            }
        }
    } else {
        None
    };

    Ok(AstNode::Relation {
        name,
        subject_role,
        predicate,
        object_role,
        via_flow,
    })
}

/// Parse instance declaration
fn parse_instance(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_identifier(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected instance name".to_string()))?,
    )?;

    let entity_type = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected entity type".to_string()))?,
    )?;

    let mut fields = HashMap::new();

    // Parse optional instance body
    if let Some(body_pair) = inner.next() {
        if body_pair.as_rule() == Rule::instance_body {
            for field_pair in body_pair.into_inner() {
                if field_pair.as_rule() == Rule::instance_field {
                    let span = field_pair.as_span();
                    let mut field_inner = field_pair.into_inner();

                    let field_name = parse_identifier(field_inner.next().ok_or_else(|| {
                        ParseError::GrammarError("Expected field name".to_string())
                    })?)?;

                    if fields.contains_key(&field_name) {
                        let (line, column) = span.start_pos().line_col();
                        return Err(ParseError::GrammarError(format!(
                            "Duplicate field name '{}' at line {}, column {}",
                            field_name, line, column
                        )));
                    }

                    let field_value = parse_expression(field_inner.next().ok_or_else(|| {
                        ParseError::GrammarError("Expected field value".to_string())
                    })?)?;

                    fields.insert(field_name, field_value);
                }
            }
        }
    }

    Ok(AstNode::Instance {
        name,
        entity_type,
        fields,
    })
}

/// Parse policy declaration
fn parse_policy(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_identifier(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected policy name".to_string()))?,
    )?;

    let mut metadata = PolicyMetadata {
        kind: None,
        modality: None,
        priority: None,
        rationale: None,
        tags: Vec::new(),
    };
    let mut version: Option<String> = None;

    for next_pair in inner {
        match next_pair.as_rule() {
            Rule::policy_kind => {
                metadata.kind = Some(match next_pair.as_str().to_lowercase().as_str() {
                    "constraint" => PolicyKind::Constraint,
                    "derivation" => PolicyKind::Derivation,
                    "obligation" => PolicyKind::Obligation,
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unknown policy kind: {}",
                            next_pair.as_str()
                        )))
                    }
                });
            }
            Rule::policy_modality => {
                metadata.modality = Some(match next_pair.as_str().to_lowercase().as_str() {
                    "obligation" => PolicyModality::Obligation,
                    "prohibition" => PolicyModality::Prohibition,
                    "permission" => PolicyModality::Permission,
                    _ => {
                        return Err(ParseError::GrammarError(format!(
                            "Unknown policy modality: {}",
                            next_pair.as_str()
                        )))
                    }
                });
            }
            Rule::number => {
                metadata.priority = Some(parse_number(next_pair)?);
            }
            Rule::policy_annotation => {
                parse_policy_annotation(next_pair, &mut metadata)?;
            }
            Rule::version => {
                version = Some(next_pair.as_str().to_string());
            }
            Rule::expression => {
                let expression = parse_expression(next_pair)?;
                return Ok(AstNode::Policy {
                    name,
                    version,
                    metadata,
                    expression,
                });
            }
            _ => {}
        }
    }

    Err(ParseError::GrammarError(
        "Policy missing expression".to_string(),
    ))
}

fn parse_policy_annotation(pair: Pair<Rule>, metadata: &mut PolicyMetadata) -> ParseResult<()> {
    let mut inner = pair.into_inner();

    let name = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected annotation name".to_string()))?;
    let value = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;

    let name_str = name.as_str().to_lowercase();

    match name_str.as_str() {
        "rationale" => {
            metadata.rationale = Some(parse_string_literal(value)?);
        }
        "tags" => {
            if value.as_rule() == Rule::string_array {
                for tag_pair in value.into_inner() {
                    if tag_pair.as_rule() == Rule::string_literal {
                        metadata.tags.push(parse_string_literal(tag_pair)?);
                    }
                }
            } else {
                metadata.tags.push(parse_string_literal(value)?);
            }
        }
        _ => {
            return Err(ParseError::GrammarError(format!(
                "Unknown policy annotation: {}",
                name_str
            )))
        }
    }

    Ok(())
}

/// Parse expression
fn parse_expression(pair: Pair<Rule>) -> ParseResult<Expression> {
    match pair.as_rule() {
        Rule::expression => {
            let inner = pair
                .into_inner()
                .next()
                .ok_or_else(|| ParseError::GrammarError("Empty expression".to_string()))?;
            parse_expression(inner)
        }
        Rule::or_expr => parse_or_expr(pair),
        Rule::and_expr => parse_and_expr(pair),
        Rule::not_expr => parse_not_expr(pair),
        Rule::comparison_expr => parse_comparison_expr(pair),
        Rule::additive_expr => parse_additive_expr(pair),
        Rule::multiplicative_expr => parse_multiplicative_expr(pair),
        Rule::unary_expr => parse_unary_expr(pair),
        Rule::cast_expr => parse_cast_expr(pair),
        Rule::primary_expr => parse_primary_expr(pair),
        _ => Err(ParseError::InvalidExpression(format!(
            "Unexpected expression rule: {:?}",
            pair.as_rule()
        ))),
    }
}

/// Parse a single expression string into an Expression AST node.
pub fn parse_expression_from_str(source: &str) -> ParseResult<Expression> {
    let pairs = SeaParser::parse(Rule::expression, source)
        .map_err(|e| ParseError::GrammarError(format!("Parse error: {}", e)))?;
    let parsed_pairs: Vec<_> = pairs.collect();

    if parsed_pairs.is_empty() {
        return Err(ParseError::GrammarError("Empty expression".to_string()));
    }
    if parsed_pairs.len() > 1 {
        return Err(ParseError::GrammarError(
            "Trailing input detected after expression".to_string(),
        ));
    }

    let pair = parsed_pairs.into_iter().next().unwrap();

    // Check that the entire input was consumed (no trailing characters)
    let consumed = pair.as_span().end();
    let trimmed_source = source.trim_end();
    if consumed < trimmed_source.len() {
        return Err(ParseError::GrammarError(format!(
            "Trailing input after expression: '{}'",
            &source[consumed..]
        )));
    }

    parse_expression(pair)
}

/// Parse OR expression
fn parse_or_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let mut left =
        parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected left expression in OR".to_string())
        })?)?;

    for right_pair in inner {
        let right = parse_expression(right_pair)?;
        left = Expression::Binary {
            left: Box::new(left),
            op: BinaryOp::Or,
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse AND expression
fn parse_and_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let mut left =
        parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected left expression in AND".to_string())
        })?)?;

    for right_pair in inner {
        let right = parse_expression(right_pair)?;
        left = Expression::Binary {
            left: Box::new(left),
            op: BinaryOp::And,
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse NOT expression
fn parse_not_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let first = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected expression in NOT".to_string()))?;

    // Check if this is actually a NOT expression or just a comparison_expr
    if first.as_rule() == Rule::not_expr {
        // This is a recursive NOT, parse it
        let expr = parse_expression(first)?;
        Ok(Expression::Unary {
            op: UnaryOp::Not,
            operand: Box::new(expr),
        })
    } else {
        // This is just a comparison_expr, parse it directly
        parse_expression(first)
    }
}

/// Parse comparison expression
fn parse_comparison_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let mut left = parse_expression(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected left expression in comparison".to_string())
    })?)?;

    if let Some(op_pair) = inner.next() {
        let op = parse_comparison_op(op_pair)?;
        let right = parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected right expression in comparison".to_string())
        })?)?;
        left = Expression::Binary {
            left: Box::new(left),
            op,
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse comparison operator
fn parse_comparison_op(pair: Pair<Rule>) -> ParseResult<BinaryOp> {
    let op_str = pair.as_str();
    match op_str {
        "=" => Ok(BinaryOp::Equal),
        "!=" => Ok(BinaryOp::NotEqual),
        ">" => Ok(BinaryOp::GreaterThan),
        "<" => Ok(BinaryOp::LessThan),
        ">=" => Ok(BinaryOp::GreaterThanOrEqual),
        "<=" => Ok(BinaryOp::LessThanOrEqual),
        _ if op_str.eq_ignore_ascii_case("contains") => Ok(BinaryOp::Contains),
        _ if op_str.eq_ignore_ascii_case("startswith") => Ok(BinaryOp::StartsWith),
        _ if op_str.eq_ignore_ascii_case("endswith") => Ok(BinaryOp::EndsWith),
        _ if op_str.eq_ignore_ascii_case("matches") => Ok(BinaryOp::Matches),
        _ if op_str.eq_ignore_ascii_case("before") => Ok(BinaryOp::Before),
        _ if op_str.eq_ignore_ascii_case("after") => Ok(BinaryOp::After),
        _ if op_str.eq_ignore_ascii_case("during") => Ok(BinaryOp::During),
        _ if op_str.eq_ignore_ascii_case("has_role") => Ok(BinaryOp::HasRole),
        _ => Err(ParseError::InvalidExpression(format!(
            "Unknown comparison operator: {}",
            op_str
        ))),
    }
}

/// Parse additive expression
fn parse_additive_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let mut left = parse_expression(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected left expression in additive".to_string())
    })?)?;

    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_str() {
            "+" => BinaryOp::Plus,
            "-" => BinaryOp::Minus,
            _ => {
                return Err(ParseError::InvalidExpression(
                    "Invalid additive operator".to_string(),
                ))
            }
        };
        let right = parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected right expression in additive".to_string())
        })?)?;
        left = Expression::Binary {
            left: Box::new(left),
            op,
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse multiplicative expression
fn parse_multiplicative_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let mut left = parse_expression(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected left expression in multiplicative".to_string())
    })?)?;

    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_str() {
            "*" => BinaryOp::Multiply,
            "/" => BinaryOp::Divide,
            _ => {
                return Err(ParseError::InvalidExpression(
                    "Invalid multiplicative operator".to_string(),
                ))
            }
        };
        let right = parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected right expression in multiplicative".to_string())
        })?)?;
        left = Expression::Binary {
            left: Box::new(left),
            op,
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse cast expression
fn parse_cast_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let primary = parse_expression(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected primary expression in cast".to_string())
    })?)?;

    if let Some(as_pair) = inner.next() {
        let target_type = parse_string_literal(as_pair)?;
        Ok(Expression::cast(primary, target_type))
    } else {
        Ok(primary)
    }
}

/// Parse unary expression
fn parse_unary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let first = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected expression in unary".to_string()))?;

    if first.as_str() == "-" {
        // Unary minus
        let expr = parse_expression(inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected expression after unary minus".to_string())
        })?)?;
        Ok(Expression::Unary {
            op: UnaryOp::Negate,
            operand: Box::new(expr),
        })
    } else {
        parse_expression(first)
    }
}

/// Parse primary expression
fn parse_primary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let inner = pair.into_inner().next().ok_or_else(|| {
        ParseError::GrammarError("Expected inner expression in primary".to_string())
    })?;

    match inner.as_rule() {
        Rule::expression => parse_expression(inner),
        Rule::group_by_expr => parse_group_by_expr(inner),
        Rule::aggregation_expr => parse_aggregation_expr(inner),
        Rule::quantified_expr => parse_quantified_expr(inner),
        Rule::member_access => parse_member_access(inner),
        Rule::literal => parse_literal_expr(inner),
        Rule::identifier => {
            let name = parse_identifier(inner)?;
            Ok(Expression::Variable(name))
        }
        _ => Err(ParseError::InvalidExpression(format!(
            "Unexpected primary expression: {:?}",
            inner.as_rule()
        ))),
    }
}

/// Parse aggregation expression
fn parse_aggregation_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();

    let function_pair = inner.next().ok_or_else(|| {
        ParseError::GrammarError(
            "Expected aggregate function in aggregation expression".to_string(),
        )
    })?;
    let function = parse_aggregate_fn(function_pair)?;

    let collection_pair = inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected collection in aggregation expression".to_string())
    })?;

    // Aggregation can be a simple form (e.g., sum(flows), sum(flows.quantity))
    // or the comprehension form (e.g., sum(f in flows where f.resource = "Money": f.quantity as "USD")).
    if collection_pair.as_rule() == Rule::aggregation_comprehension {
        // Parse aggregation comprehension
        let mut comp_inner = collection_pair.into_inner();
        let variable_pair = comp_inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected variable in aggregation comprehension".to_string())
        })?;
        let variable = parse_identifier(variable_pair)?;
        // Next token should be collection
        let collection_token = comp_inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected collection in aggregation comprehension".to_string())
        })?;
        let collection_name = parse_collection(collection_token)?;
        let collection = Box::new(Expression::Variable(collection_name));

        let mut next_pair = comp_inner.next().ok_or_else(|| {
            ParseError::GrammarError(
                "Expected predicate expression, projection, or window in aggregation comprehension"
                    .to_string(),
            )
        })?;

        let mut window = None;
        if next_pair.as_rule() == Rule::window_clause {
            window = Some(parse_window_clause(next_pair)?);
            next_pair = comp_inner.next().ok_or_else(|| {
                ParseError::GrammarError(
                    "Expected predicate or projection expression in aggregation comprehension"
                        .to_string(),
                )
            })?;
        }

        let remaining_pairs: Vec<Pair<Rule>> =
            std::iter::once(next_pair).chain(comp_inner).collect();

        let mut expr_pairs: Vec<Pair<Rule>> = Vec::new();
        let mut target_unit: Option<String> = None;
        for pair in remaining_pairs {
            match pair.as_rule() {
                Rule::expression => expr_pairs.push(pair),
                Rule::string_literal => {
                    target_unit = Some(parse_string_literal(pair)?);
                }
                Rule::identifier if pair.as_str().eq_ignore_ascii_case("as") => {
                    // skip explicit AS token
                }
                other => {
                    return Err(ParseError::GrammarError(format!(
                        "Unexpected token {:?} in aggregation comprehension",
                        other
                    )))
                }
            }
        }

        let (predicate, projection) = match expr_pairs.len() {
            2 => {
                let mut expr_iter = expr_pairs.into_iter();
                let predicate_expr = parse_expression(expr_iter.next().ok_or_else(|| {
                    ParseError::GrammarError(
                        "Expected predicate expression in aggregation comprehension".to_string(),
                    )
                })?)?;
                let projection_expr = parse_expression(expr_iter.next().ok_or_else(|| {
                    ParseError::GrammarError(
                        "Expected projection expression in aggregation comprehension".to_string(),
                    )
                })?)?;
                (predicate_expr, projection_expr)
            }
            1 => {
                let projection_expr =
                    parse_expression(expr_pairs.into_iter().next().ok_or_else(|| {
                        ParseError::GrammarError(
                            "Expected projection expression in aggregation comprehension"
                                .to_string(),
                        )
                    })?)?;
                (Expression::Literal(JsonValue::Bool(true)), projection_expr)
            }
            other => {
                return Err(ParseError::GrammarError(format!(
                    "Unexpected number of expressions in aggregation comprehension: {}",
                    other
                )))
            }
        };

        return Ok(Expression::AggregationComprehension {
            function,
            variable,
            collection,
            window,
            predicate: Box::new(predicate),
            projection: Box::new(projection),
            target_unit,
        });
    }

    // Parse aggregation_simple
    let mut simple_inner = collection_pair.into_inner();

    // First item is either collection or identifier
    let first_pair = simple_inner.next().ok_or_else(|| {
        ParseError::GrammarError(
            "Expected collection or identifier in aggregation_simple".to_string(),
        )
    })?;

    let collection = match first_pair.as_rule() {
        Rule::collection => parse_collection(first_pair)?,
        Rule::identifier => parse_identifier(first_pair)?,
        _ => {
            return Err(ParseError::GrammarError(format!(
                "Expected collection or identifier, got {:?}",
                first_pair.as_rule()
            )))
        }
    };

    let mut field: Option<String> = None;
    let mut filter: Option<Expression> = None;

    // Parse optional field and filter
    for item in simple_inner {
        match item.as_rule() {
            Rule::identifier => {
                field = Some(parse_identifier(item)?);
            }
            Rule::expression => {
                filter = Some(parse_expression(item)?);
            }
            _ => {}
        }
    }

    Ok(Expression::aggregation(
        function,
        Expression::Variable(collection),
        field,
        filter,
    ))
}

/// Parse aggregate function
fn parse_aggregate_fn(pair: Pair<Rule>) -> ParseResult<AggregateFunction> {
    let fn_str = pair.as_str();
    match fn_str.to_lowercase().as_str() {
        "count" => Ok(AggregateFunction::Count),
        "sum" => Ok(AggregateFunction::Sum),
        "min" => Ok(AggregateFunction::Min),
        "max" => Ok(AggregateFunction::Max),
        "avg" => Ok(AggregateFunction::Avg),
        _ => Err(ParseError::InvalidExpression(format!(
            "Unknown aggregate function: {}",
            fn_str
        ))),
    }
}

/// Parse quantified expression
fn parse_quantified_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();

    let quantifier = parse_quantifier(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected quantifier in quantified expression".to_string())
    })?)?;
    let variable = parse_identifier(inner.next().ok_or_else(|| {
        ParseError::GrammarError(
            "Expected variable identifier in quantified expression".to_string(),
        )
    })?)?;
    let collection = parse_collection(inner.next().ok_or_else(|| {
        ParseError::GrammarError(
            "Expected collection identifier in quantified expression".to_string(),
        )
    })?)?;
    let condition = parse_expression(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected quantified condition expression".to_string())
    })?)?;

    Ok(Expression::Quantifier {
        quantifier,
        variable,
        collection: Box::new(Expression::Variable(collection)),
        condition: Box::new(condition),
    })
}

/// Parse quantifier
fn parse_quantifier(pair: Pair<Rule>) -> ParseResult<PolicyQuantifier> {
    let q_str = pair.as_str();
    match q_str.to_lowercase().as_str() {
        "forall" => Ok(PolicyQuantifier::ForAll),
        "exists" => Ok(PolicyQuantifier::Exists),
        "exists_unique" => Ok(PolicyQuantifier::ExistsUnique),
        _ => Err(ParseError::InvalidExpression(format!(
            "Unknown quantifier: {}",
            q_str
        ))),
    }
}

/// Parse collection type
fn parse_collection(pair: Pair<Rule>) -> ParseResult<String> {
    Ok(pair.as_str().to_lowercase())
}

/// Parse member access
fn parse_member_access(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();
    let object = parse_identifier(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected object identifier in member access".to_string())
    })?)?;
    let member = parse_identifier(inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected member identifier in member access".to_string())
    })?)?;

    Ok(Expression::MemberAccess { object, member })
}

/// Parse literal expression
fn parse_literal_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let inner = pair
        .into_inner()
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected literal content".to_string()))?;

    match inner.as_rule() {
        Rule::string_literal => {
            let s = parse_string_literal(inner)?;
            Ok(Expression::Literal(JsonValue::String(s)))
        }
        Rule::multiline_string => {
            let s = parse_multiline_string(inner)?;
            Ok(Expression::Literal(JsonValue::String(s)))
        }
        Rule::quantity_literal => {
            let mut parts = inner.into_inner();
            let number_part = parts.next().ok_or_else(|| {
                ParseError::GrammarError("Expected number in quantity literal".to_string())
            })?;
            let unit_part = parts.next().ok_or_else(|| {
                ParseError::GrammarError("Expected unit string in quantity literal".to_string())
            })?;
            let value = parse_decimal(number_part)?;
            let unit = parse_string_literal(unit_part)?;
            Ok(Expression::QuantityLiteral { value, unit })
        }
        Rule::time_literal => {
            // Parse ISO 8601 timestamp (already includes quotes in grammar)
            let timestamp = inner.as_str();
            // Remove surrounding quotes
            let timestamp = timestamp.trim_start_matches('"').trim_end_matches('"');
            Ok(Expression::TimeLiteral(timestamp.to_string()))
        }
        Rule::interval_literal => {
            // Parse interval("start", "end")
            let mut parts = inner.into_inner();
            let start_part = parts.next().ok_or_else(|| {
                ParseError::GrammarError("Expected start time in interval literal".to_string())
            })?;
            let end_part = parts.next().ok_or_else(|| {
                ParseError::GrammarError("Expected end time in interval literal".to_string())
            })?;
            let start = parse_string_literal(start_part)?;
            let end = parse_string_literal(end_part)?;
            Ok(Expression::IntervalLiteral { start, end })
        }
        Rule::number => {
            let n = parse_decimal(inner)?;
            // Convert Decimal to f64 for JSON Number representation
            let f = n.to_f64().ok_or_else(|| {
                ParseError::InvalidQuantity(format!(
                    "Decimal value {} cannot be represented as f64",
                    n
                ))
            })?;
            // Ensure the value is finite
            if !f.is_finite() {
                return Err(ParseError::InvalidQuantity(format!(
                    "Decimal value {} converts to non-finite f64: {}",
                    n, f
                )));
            }
            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
                ParseError::InvalidQuantity(format!(
                    "Cannot create JSON Number from f64 value: {}",
                    f
                ))
            })?;
            Ok(Expression::Literal(JsonValue::Number(num)))
        }
        Rule::boolean => {
            let b = inner.as_str().eq_ignore_ascii_case("true");
            Ok(Expression::Literal(JsonValue::Bool(b)))
        }
        _ => Err(ParseError::InvalidExpression(format!(
            "Unknown literal type: {:?}",
            inner.as_rule()
        ))),
    }
}

/// Parse name (handles both string_literal and multiline_string)
fn parse_name(pair: Pair<Rule>) -> ParseResult<String> {
    let inner = pair.into_inner().next().ok_or_else(|| {
        ParseError::GrammarError("Expected inner token for name but got empty pair".to_string())
    })?;
    match inner.as_rule() {
        Rule::string_literal => parse_string_literal(inner),
        Rule::multiline_string => parse_multiline_string(inner),
        _ => Err(ParseError::GrammarError(format!(
            "Expected string or multiline string for name, got {:?}",
            inner.as_rule()
        ))),
    }
}

/// Parse string literal (handles escape sequences)
fn parse_string_literal(pair: Pair<Rule>) -> ParseResult<String> {
    let s = pair.as_str();
    if s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') {
        return Err(ParseError::GrammarError(format!(
            "Invalid string literal: {}",
            s
        )));
    }

    // Use serde_json to properly parse and unescape the string
    // The string already has quotes, so pass it directly
    match serde_json::from_str(s) {
        Ok(unescaped) => Ok(unescaped),
        Err(e) => Err(ParseError::GrammarError(format!(
            "Invalid string literal escape sequences: {} - {}",
            s, e
        ))),
    }
}

/// Parse multiline string (removes triple quotes and handles escape sequences)
fn parse_multiline_string(pair: Pair<Rule>) -> ParseResult<String> {
    let s = pair.as_str();
    if s.len() < 6 || !s.starts_with("\"\"\"") || !s.ends_with("\"\"\"") {
        return Err(ParseError::GrammarError(format!(
            "Invalid multiline string: {}",
            s
        )));
    }

    let content = &s[3..s.len() - 3];

    // Escape special characters for JSON compatibility
    let escaped = content
        .replace('\\', "\\\\") // Backslash must be first
        .replace('"', "\\\"") // Double quotes
        .replace('\n', "\\n") // Newlines
        .replace('\r', "\\r") // Carriage returns
        .replace('\t', "\\t"); // Tabs

    // Create a JSON string and parse it to handle escape sequences
    let json_string = format!("\"{}\"", escaped);
    match serde_json::from_str(&json_string) {
        Ok(unescaped) => Ok(unescaped),
        Err(e) => Err(ParseError::GrammarError(format!(
            "Invalid multiline string escape sequences in '{}': {}",
            s, e
        ))),
    }
}

/// Parse identifier
fn parse_identifier(pair: Pair<Rule>) -> ParseResult<String> {
    Ok(pair.as_str().to_string())
}

/// Parse semantic version (validated by grammar)
fn parse_version(pair: Pair<Rule>) -> ParseResult<String> {
    Ok(pair.as_str().to_string())
}

/// Parse number as i32
fn parse_number(pair: Pair<Rule>) -> ParseResult<i32> {
    pair.as_str()
        .parse()
        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid number: {}", pair.as_str())))
}

/// Parse number as Decimal
fn parse_decimal(pair: Pair<Rule>) -> ParseResult<Decimal> {
    pair.as_str()
        .parse()
        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid decimal: {}", pair.as_str())))
}

/// Parse group_by expression
fn parse_group_by_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
    let mut inner = pair.into_inner();

    let variable_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected variable in group_by".to_string()))?;
    let variable = parse_identifier(variable_pair)?;

    let collection_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected collection in group_by".to_string()))?;
    let collection_name = parse_collection(collection_pair)?;
    let collection = Box::new(Expression::Variable(collection_name));

    let next_pair = inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected key or where clause in group_by".to_string())
    })?;

    // Collect remaining pairs to determine structure without cloning
    let remaining: Vec<Pair<Rule>> = std::iter::once(next_pair).chain(inner).collect();

    let (filter_expr, key_expr, condition_expr) = match remaining.len() {
        3 => {
            let mut iter = remaining.into_iter();
            let filter = parse_expression(iter.next().ok_or_else(|| {
                ParseError::GrammarError("Expected filter expression in group_by".to_string())
            })?)?;
            let key = parse_expression(iter.next().ok_or_else(|| {
                ParseError::GrammarError("Expected key expression in group_by".to_string())
            })?)?;
            let condition = parse_expression(iter.next().ok_or_else(|| {
                ParseError::GrammarError("Expected condition expression in group_by".to_string())
            })?)?;
            (Some(filter), key, condition)
        }
        2 => {
            let mut iter = remaining.into_iter();
            let key = parse_expression(iter.next().ok_or_else(|| {
                ParseError::GrammarError("Expected key expression in group_by".to_string())
            })?)?;
            let condition = parse_expression(iter.next().ok_or_else(|| {
                ParseError::GrammarError("Expected condition expression in group_by".to_string())
            })?)?;
            (None, key, condition)
        }
        other => {
            return Err(ParseError::GrammarError(format!(
                "Unexpected number of expressions in group_by: {}",
                other
            )))
        }
    };

    Ok(Expression::GroupBy {
        variable,
        collection,
        filter: filter_expr.map(Box::new),
        key: Box::new(key_expr),
        condition: Box::new(condition_expr),
    })
}

/// Parse window clause
fn parse_window_clause(pair: Pair<Rule>) -> ParseResult<WindowSpec> {
    let mut inner = pair.into_inner();

    let duration_pair = inner.next().ok_or_else(|| {
        ParseError::GrammarError("Expected duration in window clause".to_string())
    })?;
    let duration_i32 = parse_number(duration_pair)?;
    if duration_i32 < 0 {
        return Err(ParseError::InvalidQuantity(
            "Window duration must be non-negative".to_string(),
        ));
    }
    let duration = duration_i32 as u64;

    let unit_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected unit in window clause".to_string()))?;
    let unit = parse_string_literal(unit_pair)?;

    Ok(WindowSpec { duration, unit })
}

fn expression_kind(expr: &Expression) -> &'static str {
    match expr {
        Expression::Literal(_) => "literal",
        Expression::QuantityLiteral { .. } => "quantity_literal",
        Expression::TimeLiteral(_) => "time_literal",
        Expression::IntervalLiteral { .. } => "interval_literal",
        Expression::Variable(_) => "variable",
        Expression::GroupBy { .. } => "group_by",
        Expression::Binary { .. } => "binary",
        Expression::Unary { .. } => "unary",
        Expression::Cast { .. } => "cast",
        Expression::Quantifier { .. } => "quantifier",
        Expression::MemberAccess { .. } => "member_access",
        Expression::Aggregation { .. } => "aggregation",
        Expression::AggregationComprehension { .. } => "aggregation_comprehension",
    }
}

/// Convert an Expression to a JSON Value for instance fields
fn expression_to_json(expr: &Expression) -> ParseResult<JsonValue> {
    match expr {
        Expression::Literal(v) => Ok(v.clone()),
        Expression::Variable(name) => Ok(JsonValue::String(name.clone())),
        Expression::QuantityLiteral { value, unit } => Ok(json!({
            "value": value.to_string(),
            "unit": unit
        })),
        Expression::TimeLiteral(timestamp) => Ok(JsonValue::String(timestamp.clone())),
        _ => Err(ParseError::UnsupportedExpression {
            kind: expression_kind(expr).to_string(),
            span: None,
        }),
    }
}

/// Parse mapping declaration
fn parse_mapping(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected mapping name".to_string()))?,
    )?;

    let target_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
    let target = parse_target_format(target_pair)?;

    let mut rules = Vec::new();

    for rule_pair in inner {
        if rule_pair.as_rule() == Rule::mapping_rule {
            rules.push(parse_mapping_rule(rule_pair)?);
        }
    }

    Ok(AstNode::MappingDecl {
        name,
        target,
        rules,
    })
}

fn parse_target_format(pair: Pair<Rule>) -> ParseResult<TargetFormat> {
    match pair.as_str().to_lowercase().as_str() {
        "calm" => Ok(TargetFormat::Calm),
        "kg" => Ok(TargetFormat::Kg),
        "sbvr" => Ok(TargetFormat::Sbvr),
        "protobuf" | "proto" => Ok(TargetFormat::Protobuf),
        _ => Err(ParseError::GrammarError(format!(
            "Unknown target format: {}",
            pair.as_str()
        ))),
    }
}

fn parse_mapping_rule(pair: Pair<Rule>) -> ParseResult<MappingRule> {
    let mut inner = pair.into_inner();

    let primitive_type = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
        .as_str()
        .to_string();

    let primitive_name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
    )?;

    let target_structure = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected target structure".to_string()))?;

    let mut target_inner = target_structure.into_inner();
    let target_type = parse_identifier(
        target_inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected target type".to_string()))?,
    )?;

    let mut fields = HashMap::new();
    for field_pair in target_inner {
        if field_pair.as_rule() == Rule::mapping_field {
            let mut field_inner = field_pair.into_inner();
            let key = parse_identifier(
                field_inner
                    .next()
                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
            )?;
            let value_pair = field_inner
                .next()
                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;

            let value = match value_pair.as_rule() {
                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
                Rule::boolean => JsonValue::Bool(value_pair.as_str().eq_ignore_ascii_case("true")),
                Rule::object_literal => parse_object_literal(value_pair)?,
                _ => {
                    return Err(ParseError::GrammarError(
                        "Unexpected mapping field value".to_string(),
                    ))
                }
            };
            fields.insert(key, value);
        }
    }

    Ok(MappingRule {
        primitive_type,
        primitive_name,
        target_type,
        fields,
    })
}

fn parse_object_literal(pair: Pair<Rule>) -> ParseResult<JsonValue> {
    let mut map = serde_json::Map::new();
    let mut inner = pair.into_inner();
    while let Some(key_pair) = inner.next() {
        let key = parse_string_literal(key_pair)?;
        let value_pair = inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected value in object literal".to_string())
        })?;
        let value = parse_annotation_value(value_pair)?;
        map.insert(key, value);
    }
    Ok(JsonValue::Object(map))
}

fn parse_annotation_value(pair: Pair<Rule>) -> ParseResult<JsonValue> {
    match pair.as_rule() {
        Rule::annotation_value => {
            let mut inner = pair.into_inner();
            let value_pair = inner
                .next()
                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
            parse_annotation_value(value_pair)
        }
        Rule::string_literal => Ok(JsonValue::String(parse_string_literal(pair)?)),
        Rule::string_array => {
            let mut values = Vec::new();
            for item in pair.into_inner() {
                values.push(JsonValue::String(parse_string_literal(item)?));
            }
            Ok(JsonValue::Array(values))
        }
        Rule::boolean => Ok(JsonValue::Bool(pair.as_str().eq_ignore_ascii_case("true"))),
        Rule::number => {
            let d = parse_decimal(pair)?;
            let f = d.to_f64().ok_or_else(|| {
                ParseError::InvalidQuantity(format!(
                    "Decimal value {} cannot be represented as f64",
                    d
                ))
            })?;
            if !f.is_finite() {
                return Err(ParseError::InvalidQuantity(format!(
                    "Decimal value {} converts to non-finite f64",
                    d
                )));
            }
            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
                ParseError::InvalidQuantity(format!("Cannot create JSON Number from decimal {}", d))
            })?;
            Ok(JsonValue::Number(num))
        }
        Rule::object_literal => parse_object_literal(pair),
        _ => Err(ParseError::GrammarError(format!(
            "Unexpected annotation value: {}",
            pair.as_str()
        ))),
    }
}

/// Parse projection declaration
fn parse_projection(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected projection name".to_string()))?,
    )?;

    let target_pair = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
    let target = parse_target_format(target_pair)?;

    let mut overrides = Vec::new();

    for rule_pair in inner {
        if rule_pair.as_rule() == Rule::projection_rule {
            overrides.push(parse_projection_rule(rule_pair)?);
        }
    }

    Ok(AstNode::ProjectionDecl {
        name,
        target,
        overrides,
    })
}

fn parse_projection_rule(pair: Pair<Rule>) -> ParseResult<ProjectionOverride> {
    let mut inner = pair.into_inner();

    let primitive_type = inner
        .next()
        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
        .as_str()
        .to_string();

    let primitive_name = parse_string_literal(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
    )?;

    let mut fields = HashMap::new();
    for field_pair in inner {
        if field_pair.as_rule() == Rule::projection_field {
            let mut field_inner = field_pair.into_inner();
            let key = parse_identifier(
                field_inner
                    .next()
                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
            )?;
            let value_pair = field_inner
                .next()
                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;

            let value = match value_pair.as_rule() {
                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
                Rule::property_mapping => parse_property_mapping(value_pair)?,
                _ => {
                    return Err(ParseError::GrammarError(
                        "Unexpected projection field value".to_string(),
                    ))
                }
            };
            fields.insert(key, value);
        }
    }

    Ok(ProjectionOverride {
        primitive_type,
        primitive_name,
        fields,
    })
}

fn parse_property_mapping(pair: Pair<Rule>) -> ParseResult<JsonValue> {
    let mut map = serde_json::Map::new();
    let mut inner = pair.into_inner();
    while let Some(key_pair) = inner.next() {
        let key = parse_string_literal(key_pair)?;
        let value_pair = inner.next().ok_or_else(|| {
            ParseError::GrammarError("Expected value in property mapping".to_string())
        })?;
        let value = parse_string_literal(value_pair)?;
        map.insert(key, JsonValue::String(value));
    }
    Ok(JsonValue::Object(map))
}

fn unwrap_export(spanned: &Spanned<AstNode>) -> &AstNode {
    match &spanned.node {
        AstNode::Export(inner) => &inner.node,
        other => other,
    }
}

/// Resolve a name in a namespace-keyed map.
/// Tries (default_namespace, name) first, then scans all namespaces for an unqualified match.
/// Returns None if not found, or the concept ID if exactly one match exists.
fn resolve_by_name(
    map: &HashMap<(String, String), crate::ConceptId>,
    name: &str,
    default_namespace: &str,
) -> Result<Option<crate::ConceptId>, ParseError> {
    // Try exact match in default namespace first
    if let Some(id) = map.get(&(default_namespace.to_string(), name.to_string())) {
        return Ok(Some(id.clone()));
    }
    // Fall back to any namespace with this name
    let matches: Vec<(&str, &crate::ConceptId)> = map
        .iter()
        .filter(|((_, n), _)| n == name)
        .map(|((namespace, _), id)| (namespace.as_str(), id))
        .collect();
    if matches.len() == 1 {
        return Ok(Some(matches[0].1.clone()));
    }
    if matches.len() > 1 {
        let mut namespaces: Vec<&str> = matches
            .into_iter()
            .map(|(namespace, _)| namespace)
            .collect();
        namespaces.sort_unstable();
        namespaces.dedup();
        return Err(ParseError::Validation(format!(
            "Ambiguous reference '{}' found in namespaces: {}",
            name,
            namespaces.join(", ")
        )));
    }
    Ok(None)
}

/// Convert AST to Graph
pub fn ast_to_graph(ast: Ast) -> ParseResult<Graph> {
    ast_to_graph_with_options(ast, &ParseOptions::default())
}

pub fn ast_to_graph_with_options(mut ast: Ast, options: &ParseOptions) -> ParseResult<Graph> {
    use crate::parser::profiles::ProfileRegistry;
    let registry = ProfileRegistry::global();
    let active_profile = ast
        .metadata
        .profile
        .clone()
        .or_else(|| options.active_profile.clone())
        .unwrap_or_else(|| "default".to_string());
    ast.metadata.profile.get_or_insert(active_profile.clone());

    if registry.get(&active_profile).is_none() {
        let available = registry.list_names().join(", ");
        let message = format!(
            "Unknown profile: '{}'. Available profiles: {}",
            active_profile, available
        );
        if options.tolerate_profile_warnings {
            log::warn!("{}", message);
        } else {
            return Err(ParseError::Validation(message));
        }
    }

    let mut graph = Graph::new();
    let mut entity_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
    let mut role_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
    let mut resource_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
    let mut relation_map: HashMap<String, crate::ConceptId> = HashMap::new();

    let default_namespace = ast
        .metadata
        .namespace
        .clone()
        .or_else(|| options.default_namespace.clone())
        .unwrap_or_else(|| "default".to_string());

    // First pass: Register dimensions and units
    {
        use crate::units::{Dimension, Unit, UnitError, UnitRegistry};
        let registry = UnitRegistry::global();
        let mut registry = registry.write().map_err(|e| {
            ParseError::GrammarError(format!("Failed to lock unit registry: {}", e))
        })?;

        for node in &ast.declarations {
            let node = unwrap_export(node);
            match node {
                AstNode::Dimension { name } => {
                    let dim = Dimension::parse(name);
                    registry.register_dimension(dim);
                }
                AstNode::UnitDeclaration {
                    symbol,
                    dimension,
                    factor,
                    base_unit,
                } => {
                    let dim = Dimension::parse(dimension);
                    let unit = Unit::new(
                        symbol.clone(),
                        symbol.clone(),
                        dim,
                        *factor,
                        base_unit.clone(),
                    );
                    match registry.get_unit(symbol) {
                        Ok(existing) => {
                            if existing != &unit {
                                return Err(ParseError::GrammarError(format!(
                                    "Conflicting unit '{}' already registered (existing: dimension={}, base_factor={}, base_unit={}; new: dimension={}, base_factor={}, base_unit={})",
                                    symbol,
                                    existing.dimension(),
                                    existing.base_factor(),
                                    existing.base_unit(),
                                    unit.dimension(),
                                    unit.base_factor(),
                                    unit.base_unit(),
                                )));
                            }
                        }
                        Err(UnitError::UnitNotFound(_)) => {
                            registry.register(unit).map_err(|e| {
                                ParseError::GrammarError(format!("Failed to register unit: {}", e))
                            })?;
                        }
                        Err(err) => {
                            return Err(ParseError::GrammarError(format!(
                                "Failed to inspect unit '{}': {}",
                                symbol, err
                            )));
                        }
                    }
                }
                _ => {}
            }
        }
    }

    // Register patterns with eager regex validation
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Pattern { name, regex } = node {
            let namespace = default_namespace.clone();
            let pattern = Pattern::new(name.clone(), namespace, regex.clone())
                .map_err(ParseError::GrammarError)?;

            graph
                .add_pattern(pattern)
                .map_err(ParseError::GrammarError)?;
        }
    }

    // Register concept changes
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::ConceptChange {
            name,
            from_version,
            to_version,
            migration_policy,
            breaking_change,
        } = node
        {
            let change = ConceptChange::new(
                name.clone(),
                from_version.clone(),
                to_version.clone(),
                migration_policy.clone(),
                *breaking_change,
            );
            graph.add_concept_change(change).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add concept change: {}", e))
            })?;
        }
    }

    // Second pass: Add roles, entities, and resources
    for node in &ast.declarations {
        let node = unwrap_export(node);
        match node {
            AstNode::Role { name, domain } => {
                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
                let key = (namespace.clone(), name.clone());
                if role_map.contains_key(&key) {
                    return Err(ParseError::duplicate_declaration_no_loc(format!(
                        "Role '{}' already declared in namespace '{}'",
                        name, namespace
                    )));
                }

                let role = Role::new_with_namespace(name.clone(), namespace);
                let role_id = role.id().clone();
                graph
                    .add_role(role)
                    .map_err(|e| ParseError::GrammarError(format!("Failed to add role: {}", e)))?;
                role_map.insert(key, role_id);
            }
            AstNode::Entity {
                name,
                domain,
                version,
                annotations,
            } => {
                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
                let key = (namespace.clone(), name.clone());
                if entity_map.contains_key(&key) {
                    return Err(ParseError::duplicate_declaration_no_loc(format!(
                        "Entity '{}' already declared in namespace '{}'",
                        name, namespace
                    )));
                }

                let mut entity = Entity::new_with_namespace(name.clone(), namespace);

                if let Some(v_str) = version {
                    let sem_ver = SemanticVersion::parse(v_str).map_err(|e| {
                        ParseError::GrammarError(format!(
                            "Invalid entity version '{}': {}",
                            v_str, e
                        ))
                    })?;
                    entity = entity.with_version(sem_ver);
                }

                if let Some(replaces_val) = annotations.get("replaces") {
                    if let Some(replaces_str) = replaces_val.as_str() {
                        entity = entity.with_replaces(replaces_str.to_string());
                    }
                }

                if let Some(changes_val) = annotations.get("changes") {
                    if let Some(changes_arr) = changes_val.as_array() {
                        let changes: Vec<String> = changes_arr
                            .iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect();
                        entity = entity.with_changes(changes);
                    }
                }

                let entity_id = entity.id().clone();
                graph.add_entity(entity).map_err(|e| {
                    ParseError::GrammarError(format!("Failed to add entity: {}", e))
                })?;
                entity_map.insert(key, entity_id);
            }
            AstNode::Resource {
                name,
                unit_name,
                domain,
                ..
            } => {
                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
                let key = (namespace.clone(), name.clone());
                if resource_map.contains_key(&key) {
                    return Err(ParseError::duplicate_declaration_no_loc(format!(
                        "Resource '{}' already declared in namespace '{}'",
                        name, namespace
                    )));
                }

                let unit = unit_from_string(unit_name.as_deref().unwrap_or("units"));
                let resource = Resource::new_with_namespace(name.clone(), unit, namespace);
                let resource_id = resource.id().clone();
                graph.add_resource(resource).map_err(|e| {
                    ParseError::GrammarError(format!("Failed to add resource: {}", e))
                })?;
                resource_map.insert(key, resource_id);
            }
            _ => {}
        }
    }

    // Third pass: Add flows
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Flow {
            resource_name,
            from_entity,
            to_entity,
            quantity,
            ..
        } = node
        {
            let from_id = resolve_by_name(&entity_map, from_entity, &default_namespace)?
                .ok_or_else(|| ParseError::undefined_entity_no_loc(from_entity))?;

            let to_id = resolve_by_name(&entity_map, to_entity, &default_namespace)?
                .ok_or_else(|| ParseError::undefined_entity_no_loc(to_entity))?;

            let resource_id = resolve_by_name(&resource_map, resource_name, &default_namespace)?
                .ok_or_else(|| ParseError::undefined_resource_no_loc(resource_name))?;

            let qty = quantity.unwrap_or(Decimal::ZERO);
            let flow = Flow::new_with_namespace(
                resource_id.clone(),
                from_id.clone(),
                to_id.clone(),
                qty,
                default_namespace.clone(),
            );

            graph
                .add_flow(flow)
                .map_err(|e| ParseError::GrammarError(format!("Failed to add flow: {}", e)))?;
        }
    }

    // Fourth pass: Add relations
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Relation {
            name,
            subject_role,
            predicate,
            object_role,
            via_flow,
        } = node
        {
            if relation_map.contains_key(name) {
                return Err(ParseError::duplicate_declaration_no_loc(format!(
                    "Relation '{}' already declared",
                    name
                )));
            }

            let subject_id = resolve_by_name(&role_map, subject_role, &default_namespace)?
                .ok_or_else(|| {
                    ParseError::GrammarError(format!("Undefined subject role '{}'", subject_role))
                })?;

            let object_id = resolve_by_name(&role_map, object_role, &default_namespace)?
                .ok_or_else(|| {
                    ParseError::GrammarError(format!("Undefined object role '{}'", object_role))
                })?;

            let via_flow_id = if let Some(flow_name) = via_flow {
                Some(
                    resolve_by_name(&resource_map, flow_name, &default_namespace)?
                        .ok_or_else(|| ParseError::undefined_resource_no_loc(flow_name))?,
                )
            } else {
                None
            };

            let relation = RelationType::new(
                name.clone(),
                default_namespace.clone(),
                subject_id.clone(),
                predicate.clone(),
                object_id.clone(),
                via_flow_id,
            );

            let relation_id = relation.id().clone();
            graph.add_relation_type(relation).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add relation '{}': {}", name, e))
            })?;
            relation_map.insert(name.clone(), relation_id);
        }
    }

    // Instance pass: Add instances (after entities are created)
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Instance {
            name,
            entity_type,
            fields,
        } = node
        {
            let namespace = default_namespace.clone();
            let mut instance = crate::primitives::Instance::new_with_namespace(
                name.clone(),
                entity_type.clone(),
                namespace,
            );

            // Evaluate and set fields
            for (field_name, field_expr) in fields {
                let value = expression_to_json(field_expr)?;
                instance.set_field(field_name.clone(), value);
            }

            graph.add_entity_instance(instance).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add entity instance '{}': {}", name, e))
            })?;
        }
    }

    // Fifth pass: Add policies
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Policy {
            name,
            version,
            metadata,
            expression,
        } = node
        {
            let namespace = ast
                .metadata
                .namespace
                .as_ref()
                .cloned()
                .or_else(|| options.default_namespace.clone())
                .unwrap_or_else(|| "default".to_string());

            let kind = metadata.kind.as_ref().map(|kind| match kind {
                PolicyKind::Constraint => CorePolicyKind::Constraint,
                PolicyKind::Derivation => CorePolicyKind::Derivation,
                PolicyKind::Obligation => CorePolicyKind::Obligation,
            });

            let modality = metadata.modality.as_ref().map(|modality| match modality {
                PolicyModality::Obligation => CorePolicyModality::Obligation,
                PolicyModality::Prohibition => CorePolicyModality::Prohibition,
                PolicyModality::Permission => CorePolicyModality::Permission,
            });

            let mut policy =
                Policy::new_with_namespace(name.clone(), namespace, expression.clone())
                    .with_metadata(
                        kind,
                        modality,
                        metadata.priority,
                        metadata.rationale.clone(),
                        metadata.tags.clone(),
                    );

            let version_to_apply = version
                .as_ref()
                .cloned()
                .or_else(|| ast.metadata.version.clone());

            if let Some(version_str) = version_to_apply {
                let semantic_version = SemanticVersion::parse(&version_str).map_err(|err| {
                    ParseError::GrammarError(format!(
                        "Invalid policy version '{}': {}",
                        version_str, err
                    ))
                })?;
                policy = policy.with_version(semantic_version);
            }

            graph.add_policy(policy).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add policy '{}': {}", name, e))
            })?;
        }
    }

    // Sixth pass: Add metrics
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::Metric {
            name,
            expression,
            metadata,
        } = node
        {
            let namespace = ast
                .metadata
                .namespace
                .as_ref()
                .cloned()
                .or_else(|| options.default_namespace.clone())
                .unwrap_or_else(|| "default".to_string());

            let mut metric =
                crate::primitives::Metric::new(name.clone(), namespace, expression.clone());

            if let Some(duration) = metadata.refresh_interval {
                metric = metric.with_refresh_interval(duration);
            }

            if let Some(unit) = &metadata.unit {
                metric = metric.with_unit(unit.clone());
            }

            if let Some(threshold) = metadata.threshold {
                metric = metric.with_threshold(threshold);
            }

            if let Some(severity) = metadata.severity.clone() {
                metric = metric.with_severity(severity);
            }

            if let Some(target) = metadata.target {
                metric = metric.with_target(target);
            }

            if let Some(duration) = metadata.window {
                metric = metric.with_window(duration);
            }

            graph.add_metric(metric).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add metric '{}': {}", name, e))
            })?;
        }
    }

    // Seventh pass: Add mappings
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::MappingDecl {
            name,
            target,
            rules,
        } = node
        {
            let namespace = ast
                .metadata
                .namespace
                .clone()
                .or_else(|| options.default_namespace.clone())
                .unwrap_or_else(|| "default".to_string());
            let mapping = crate::primitives::MappingContract::new(
                crate::ConceptId::from_concept(&namespace, name),
                name.clone(),
                namespace,
                target.clone(),
                rules.clone(),
            );
            graph
                .add_mapping(mapping)
                .map_err(|e| ParseError::GrammarError(format!("Failed to add mapping: {}", e)))?;
        }
    }

    // Eighth pass: Add projections
    for node in &ast.declarations {
        let node = unwrap_export(node);
        if let AstNode::ProjectionDecl {
            name,
            target,
            overrides,
        } = node
        {
            let namespace = ast
                .metadata
                .namespace
                .clone()
                .or_else(|| options.default_namespace.clone())
                .unwrap_or_else(|| "default".to_string());
            let projection = crate::primitives::ProjectionContract::new(
                crate::ConceptId::from_concept(&namespace, name),
                name.clone(),
                namespace,
                target.clone(),
                overrides.clone(),
            );
            graph.add_projection(projection).map_err(|e| {
                ParseError::GrammarError(format!("Failed to add projection: {}", e))
            })?;
        }
    }

    Ok(graph)
}

/// Parse metric declaration
fn parse_metric(pair: Pair<Rule>) -> ParseResult<AstNode> {
    let mut inner = pair.into_inner();

    let name = parse_name(
        inner
            .next()
            .ok_or_else(|| ParseError::GrammarError("Expected metric name".to_string()))?,
    )?;

    let mut metadata = MetricMetadata {
        refresh_interval: None,
        unit: None,
        threshold: None,
        severity: None,
        target: None,
        window: None,
    };

    let mut expression_pair = None;

    for part in inner {
        match part.as_rule() {
            Rule::metric_annotation => {
                let mut annotation_inner = part.into_inner();
                let key_pair = annotation_inner.next().ok_or_else(|| {
                    ParseError::GrammarError("Expected annotation key".to_string())
                })?;

                match key_pair.as_rule() {
                    Rule::ma_refresh_interval => {
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected refresh interval value".to_string())
                        })?;
                        let value = parse_number_i64(value_pair)?;
                        let unit_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected refresh interval unit".to_string())
                        })?;
                        let unit = parse_string_literal(unit_pair.clone())?;
                        let duration = parse_duration_with_unit(value, &unit, unit_pair.as_span())?;
                        metadata.refresh_interval = Some(duration);
                    }
                    Rule::ma_unit => {
                        let unit_pair = annotation_inner
                            .next()
                            .ok_or_else(|| ParseError::GrammarError("Expected unit".to_string()))?;
                        metadata.unit = Some(parse_string_literal(unit_pair)?);
                    }
                    Rule::ma_threshold => {
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected threshold value".to_string())
                        })?;
                        metadata.threshold = Some(parse_decimal(value_pair)?);
                    }
                    Rule::ma_severity => {
                        let severity_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected severity".to_string())
                        })?;
                        let severity_str = parse_string_literal(severity_pair.clone())?;
                        let severity =
                            parse_severity_value(&severity_str, severity_pair.as_span())?;
                        metadata.severity = Some(severity);
                    }
                    Rule::ma_target => {
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected target value".to_string())
                        })?;
                        metadata.target = Some(parse_decimal(value_pair)?);
                    }
                    Rule::ma_window => {
                        let value_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected window value".to_string())
                        })?;
                        let value = parse_number_i64(value_pair)?;
                        let unit_pair = annotation_inner.next().ok_or_else(|| {
                            ParseError::GrammarError("Expected window unit".to_string())
                        })?;
                        let unit = parse_string_literal(unit_pair.clone())?;
                        let duration = parse_duration_with_unit(value, &unit, unit_pair.as_span())?;
                        metadata.window = Some(duration);
                    }
                    _ => {
                        let (line, column) = key_pair.as_span().start_pos().line_col();
                        return Err(ParseError::GrammarError(format!(
                            "Unknown metric annotation '{}' at {}:{}",
                            key_pair.as_str(),
                            line,
                            column
                        )));
                    }
                }
            }
            Rule::expression => {
                expression_pair = Some(part);
            }
            _ => {}
        }
    }

    let expression = parse_expression(
        expression_pair
            .ok_or_else(|| ParseError::GrammarError("Expected metric expression".to_string()))?,
    )?;

    Ok(AstNode::Metric {
        name,
        expression,
        metadata,
    })
}

fn parse_duration_with_unit(value: i64, unit: &str, span: Span<'_>) -> ParseResult<Duration> {
    let normalized_unit = unit.to_ascii_lowercase();
    let multiplier = match normalized_unit.as_str() {
        "second" => Some(1),
        "seconds" | "s" => Some(1),
        "minute" => Some(60),
        "minutes" | "m" => Some(60),
        "hour" => Some(60 * 60),
        "hours" | "h" => Some(60 * 60),
        "day" => Some(60 * 60 * 24),
        "days" | "d" => Some(60 * 60 * 24),
        _ => None,
    }
    .ok_or_else(|| {
        let (line, column) = span.start_pos().line_col();
        ParseError::GrammarError(format!(
            "Invalid duration unit '{}' at {}:{} (allowed: second(s)/s, minute(s)/m, hour(s)/h, day(s)/d)",
            unit, line, column
        ))
    })?;

    let total_seconds = value.checked_mul(multiplier).ok_or_else(|| {
        let (line, column) = span.start_pos().line_col();
        ParseError::GrammarError(format!(
            "Duration overflow for value {} {} at {}:{}",
            value, unit, line, column
        ))
    })?;

    Ok(Duration::seconds(total_seconds))
}

fn parse_severity_value(value: &str, span: Span<'_>) -> ParseResult<Severity> {
    let normalized = value.to_ascii_lowercase();
    match normalized.as_str() {
        "info" => Ok(Severity::Info),
        "warning" => Ok(Severity::Warning),
        "error" => Ok(Severity::Error),
        "critical" => Ok(Severity::Critical),
        _ => {
            let (line, column) = span.start_pos().line_col();
            Err(ParseError::GrammarError(format!(
                "Unknown severity '{}' at {}:{} (expected one of: info, warning, error, critical)",
                value, line, column
            )))
        }
    }
}

fn parse_number_i64(pair: Pair<Rule>) -> ParseResult<i64> {
    let s = pair.as_str();
    s.parse::<i64>()
        .map_err(|_| ParseError::GrammarError(format!("Invalid integer: {}", s)))
}