oxirs-star 0.2.4

RDF-star and SPARQL-star grammar support for quoted triples
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
//! Reification utilities for converting between RDF-star and standard RDF.
//!
//! This module provides functionality to convert quoted triples to/from
//! standard RDF reification using rdf:Statement, rdf:subject, rdf:predicate, rdf:object.
//!
//! # New in this version
//!
//! - [`EmbeddedTriple`]: type alias for a quoted triple in embedded context.
//! - [`AnnotationStyle`]: enum controlling the reification annotation flavour.
//! - [`ReificationBridge`]: high-level bidirectional conversion API.

use std::collections::HashMap;

use tracing::{debug, span, Level};

use crate::model::{StarGraph, StarTerm, StarTriple};
use crate::{StarError, StarResult};

/// Standard RDF vocabulary for reification
pub mod vocab {
    pub const RDF_STATEMENT: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement";
    pub const RDF_SUBJECT: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject";
    pub const RDF_PREDICATE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate";
    pub const RDF_OBJECT: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#object";
    pub const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
}

/// Reification strategy for handling quoted triples
#[derive(Debug, Clone, PartialEq)]
pub enum ReificationStrategy {
    /// Standard RDF reification using rdf:Statement
    StandardReification,
    /// Use unique IRIs for each quoted triple
    UniqueIris,
    /// Use blank nodes for quoted triples
    BlankNodes,
    /// Singleton properties - each statement gets a unique property
    /// This avoids the need for rdf:Statement and reduces triple count
    SingletonProperties,
}

/// Reification context for managing identifiers and mappings
#[derive(Debug)]
pub struct ReificationContext {
    /// Strategy to use for reification
    strategy: ReificationStrategy,
    /// Counter for generating unique identifiers
    counter: usize,
    /// Base IRI for generating statement IRIs
    base_iri: String,
    /// Mapping from quoted triples to their reification identifiers
    triple_to_id: HashMap<String, String>,
    /// Mapping from reification identifiers to quoted triples
    id_to_triple: HashMap<String, StarTriple>,
}

impl ReificationContext {
    /// Create a new reification context
    pub fn new(strategy: ReificationStrategy, base_iri: Option<String>) -> Self {
        Self {
            strategy,
            counter: 0,
            base_iri: base_iri.unwrap_or_else(|| "http://example.org/statement/".to_string()),
            triple_to_id: HashMap::new(),
            id_to_triple: HashMap::new(),
        }
    }

    /// Generate a unique identifier for a quoted triple
    fn generate_id(&mut self, triple: &StarTriple) -> String {
        let triple_key = format!("{}|{}|{}", triple.subject, triple.predicate, triple.object);

        if let Some(existing_id) = self.triple_to_id.get(&triple_key) {
            return existing_id.clone();
        }

        let id = match self.strategy {
            ReificationStrategy::StandardReification | ReificationStrategy::UniqueIris => {
                self.counter += 1;
                format!("{}{}", self.base_iri, self.counter)
            }
            ReificationStrategy::BlankNodes => {
                self.counter += 1;
                format!("_:stmt{}", self.counter)
            }
            ReificationStrategy::SingletonProperties => {
                self.counter += 1;
                format!("{}property/{}", self.base_iri, self.counter)
            }
        };

        self.triple_to_id.insert(triple_key, id.clone());
        self.id_to_triple.insert(id.clone(), triple.clone());
        id
    }

    /// Get the identifier for a quoted triple if it exists
    pub fn get_id(&self, triple: &StarTriple) -> Option<&String> {
        let triple_key = format!("{}|{}|{}", triple.subject, triple.predicate, triple.object);
        self.triple_to_id.get(&triple_key)
    }

    /// Get the quoted triple for an identifier if it exists
    pub fn get_triple(&self, id: &str) -> Option<&StarTriple> {
        self.id_to_triple.get(id)
    }
}

/// RDF-star to standard RDF reification converter
pub struct Reificator {
    context: ReificationContext,
}

impl Reificator {
    /// Create a new reificator with the specified strategy
    pub fn new(strategy: ReificationStrategy, base_iri: Option<String>) -> Self {
        Self {
            context: ReificationContext::new(strategy, base_iri),
        }
    }

    /// Convert an RDF-star graph to standard RDF using reification
    pub fn reify_graph(&mut self, star_graph: &StarGraph) -> StarResult<StarGraph> {
        let span = span!(Level::INFO, "reify_graph");
        let _enter = span.enter();

        let mut reified_graph = StarGraph::new();

        for triple in star_graph.triples() {
            let reified_triples = self.reify_triple(triple)?;
            for reified_triple in reified_triples {
                reified_graph.insert(reified_triple)?;
            }
        }

        debug!(
            "Reified {} triples to {} standard RDF triples",
            star_graph.len(),
            reified_graph.len()
        );
        Ok(reified_graph)
    }

    /// Convert a single RDF-star triple to standard RDF triples
    pub fn reify_triple(&mut self, triple: &StarTriple) -> StarResult<Vec<StarTriple>> {
        let mut result = Vec::new();

        // Process subject
        let subject = self.reify_term(&triple.subject, &mut result)?;

        // Process predicate (should not contain quoted triples in valid RDF-star)
        let predicate = self.reify_term(&triple.predicate, &mut result)?;

        // Process object
        let object = self.reify_term(&triple.object, &mut result)?;

        // Create the main triple with reified terms
        let main_triple = StarTriple::new(subject, predicate, object);
        result.push(main_triple);

        Ok(result)
    }

    /// Reify a single term, generating additional triples if needed
    fn reify_term(
        &mut self,
        term: &StarTerm,
        additional_triples: &mut Vec<StarTriple>,
    ) -> StarResult<StarTerm> {
        match term {
            StarTerm::QuotedTriple(quoted_triple) => {
                // Generate identifier for the quoted triple
                let stmt_id = self.context.generate_id(quoted_triple);

                // Create reification triples
                let reification_triples =
                    self.create_reification_triples(&stmt_id, quoted_triple)?;
                additional_triples.extend(reification_triples);

                // Return the statement identifier as the term
                match self.context.strategy {
                    ReificationStrategy::StandardReification | ReificationStrategy::UniqueIris => {
                        Ok(StarTerm::iri(&stmt_id)?)
                    }
                    ReificationStrategy::BlankNodes => {
                        let blank_id = &stmt_id[2..]; // Remove "_:" prefix
                        Ok(StarTerm::blank_node(blank_id)?)
                    }
                    ReificationStrategy::SingletonProperties => {
                        // For singleton properties, return the property IRI itself
                        Ok(StarTerm::iri(&stmt_id)?)
                    }
                }
            }
            _ => Ok(term.clone()),
        }
    }

    /// Create the standard reification triples for a quoted triple
    fn create_reification_triples(
        &mut self,
        stmt_id: &str,
        triple: &StarTriple,
    ) -> StarResult<Vec<StarTriple>> {
        let mut triples = Vec::new();

        // Singleton properties strategy - more efficient representation
        if matches!(
            self.context.strategy,
            ReificationStrategy::SingletonProperties
        ) {
            // Create a unique property IRI for this statement
            let property_term = StarTerm::iri(stmt_id)?;

            // Recursively reify subject and object (predicate stays as-is)
            let mut subject_additional = Vec::new();
            let reified_subject = self.reify_term(&triple.subject, &mut subject_additional)?;
            triples.extend(subject_additional);

            let mut object_additional = Vec::new();
            let reified_object = self.reify_term(&triple.object, &mut object_additional)?;
            triples.extend(object_additional);

            // subject <singleton-property> object
            triples.push(StarTriple::new(
                reified_subject,
                property_term.clone(),
                reified_object,
            ));

            // <singleton-property> rdf:singletonPropertyOf original-predicate
            triples.push(StarTriple::new(
                property_term,
                StarTerm::iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#singletonPropertyOf")?,
                triple.predicate.clone(),
            ));

            return Ok(triples);
        }

        // Create statement identifier term for other strategies
        let stmt_term = match self.context.strategy {
            ReificationStrategy::StandardReification | ReificationStrategy::UniqueIris => {
                StarTerm::iri(stmt_id)?
            }
            ReificationStrategy::BlankNodes => {
                let blank_id = &stmt_id[2..]; // Remove "_:" prefix
                StarTerm::blank_node(blank_id)?
            }
            ReificationStrategy::SingletonProperties => {
                unreachable!("Handled above")
            }
        };

        // stmt_id rdf:type rdf:Statement
        if matches!(
            self.context.strategy,
            ReificationStrategy::StandardReification
        ) {
            triples.push(StarTriple::new(
                stmt_term.clone(),
                StarTerm::iri(vocab::RDF_TYPE)?,
                StarTerm::iri(vocab::RDF_STATEMENT)?,
            ));
        }

        // Recursively reify subject, predicate, object
        let mut subject_additional = Vec::new();
        let reified_subject = self.reify_term(&triple.subject, &mut subject_additional)?;
        triples.extend(subject_additional);

        let mut predicate_additional = Vec::new();
        let reified_predicate = self.reify_term(&triple.predicate, &mut predicate_additional)?;
        triples.extend(predicate_additional);

        let mut object_additional = Vec::new();
        let reified_object = self.reify_term(&triple.object, &mut object_additional)?;
        triples.extend(object_additional);

        // stmt_id rdf:subject subject
        triples.push(StarTriple::new(
            stmt_term.clone(),
            StarTerm::iri(vocab::RDF_SUBJECT)?,
            reified_subject,
        ));

        // stmt_id rdf:predicate predicate
        triples.push(StarTriple::new(
            stmt_term.clone(),
            StarTerm::iri(vocab::RDF_PREDICATE)?,
            reified_predicate,
        ));

        // stmt_id rdf:object object
        triples.push(StarTriple::new(
            stmt_term,
            StarTerm::iri(vocab::RDF_OBJECT)?,
            reified_object,
        ));

        Ok(triples)
    }

    /// Convert standard RDF reification back to RDF-star (dereification)
    pub fn dereify_graph(&mut self, reified_graph: &StarGraph) -> StarResult<StarGraph> {
        let span = span!(Level::INFO, "dereify_graph");
        let _enter = span.enter();

        let mut star_graph = StarGraph::new();
        let mut processed_statements = std::collections::HashSet::new();
        let mut reconstructed_triples = std::collections::HashMap::new();

        // First pass: Find all rdf:Statement instances and reconstruct them
        for triple in reified_graph.triples() {
            if let (StarTerm::NamedNode(predicate), StarTerm::NamedNode(object)) =
                (&triple.predicate, &triple.object)
            {
                if predicate.iri == vocab::RDF_TYPE && object.iri == vocab::RDF_STATEMENT {
                    if let StarTerm::NamedNode(stmt_node) = &triple.subject {
                        if !processed_statements.contains(&stmt_node.iri) {
                            if let Some(star_triple) =
                                self.reconstruct_quoted_triple(reified_graph, &stmt_node.iri)?
                            {
                                reconstructed_triples.insert(stmt_node.iri.clone(), star_triple);
                                processed_statements.insert(stmt_node.iri.clone());
                            }
                        }
                    }
                }
            }
        }

        // Second pass: Process remaining triples and convert statement references to quoted triples
        for triple in reified_graph.triples() {
            // Skip reification meta-triples (rdf:type, rdf:subject, rdf:predicate, rdf:object)
            if self.is_reification_meta_triple(triple, &processed_statements) {
                continue;
            }

            // Check if this triple uses a reified statement as subject
            if let StarTerm::NamedNode(subject_node) = &triple.subject {
                if let Some(quoted_triple) = reconstructed_triples.get(&subject_node.iri) {
                    // Create a new triple with the quoted triple as subject
                    let new_triple = StarTriple::new(
                        StarTerm::quoted_triple(quoted_triple.clone()),
                        triple.predicate.clone(),
                        triple.object.clone(),
                    );
                    star_graph.insert(new_triple)?;
                } else {
                    star_graph.insert(triple.clone())?;
                }
            } else {
                star_graph.insert(triple.clone())?;
            }
        }

        debug!(
            "Dereified {} reified triples back to {} RDF-star triples",
            reified_graph.len(),
            star_graph.len()
        );
        Ok(star_graph)
    }

    /// Reconstruct a quoted triple from its reification
    fn reconstruct_quoted_triple(
        &self,
        graph: &StarGraph,
        stmt_iri: &str,
    ) -> StarResult<Option<StarTriple>> {
        let mut subject = None;
        let mut predicate = None;
        let mut object = None;

        let stmt_term = StarTerm::iri(stmt_iri)?;

        // Find the reification triples
        for triple in graph.triples() {
            if triple.subject == stmt_term {
                if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                    match pred_node.iri.as_str() {
                        vocab::RDF_SUBJECT => subject = Some(triple.object.clone()),
                        vocab::RDF_PREDICATE => predicate = Some(triple.object.clone()),
                        vocab::RDF_OBJECT => object = Some(triple.object.clone()),
                        _ => {}
                    }
                }
            }
        }

        if let (Some(s), Some(p), Some(o)) = (subject, predicate, object) {
            Ok(Some(StarTriple::new(s, p, o)))
        } else {
            Ok(None)
        }
    }

    /// Check if a triple is a reification meta-triple (rdf:type, rdf:subject, rdf:predicate, rdf:object)
    fn is_reification_meta_triple(
        &self,
        triple: &StarTriple,
        processed_statements: &std::collections::HashSet<String>,
    ) -> bool {
        // Check if this triple has a processed statement as subject
        if let StarTerm::NamedNode(subj_node) = &triple.subject {
            if processed_statements.contains(&subj_node.iri) {
                // Check if this is a reification meta-predicate
                if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                    match pred_node.iri.as_str() {
                        vocab::RDF_TYPE
                        | vocab::RDF_SUBJECT
                        | vocab::RDF_PREDICATE
                        | vocab::RDF_OBJECT => {
                            return true;
                        }
                        _ => {}
                    }
                }
            }
        }
        false
    }
}

/// Advanced reification strategies with hybrid approaches
#[derive(Debug, Clone, PartialEq)]
pub enum AdvancedReificationStrategy {
    /// Standard reification strategies
    Standard(ReificationStrategy),
    /// Hybrid approach: use different strategies based on context
    Hybrid {
        /// Strategy for simple quoted triples
        simple_strategy: ReificationStrategy,
        /// Strategy for nested quoted triples
        nested_strategy: ReificationStrategy,
        /// Strategy for quoted triples in specific predicates
        predicate_strategies: HashMap<String, ReificationStrategy>,
    },
    /// Conditional reification based on triple characteristics
    Conditional {
        /// Default strategy
        default_strategy: ReificationStrategy,
        /// Rules for selecting strategy
        rules: Vec<ReificationRule>,
    },
    /// Memory-optimized reification with caching
    Optimized {
        /// Base strategy
        base_strategy: ReificationStrategy,
        /// Enable aggressive caching
        aggressive_caching: bool,
        /// Maximum cache size
        max_cache_size: usize,
    },
}

/// Rule for conditional reification strategy selection
#[derive(Debug, Clone, PartialEq)]
pub struct ReificationRule {
    /// Condition to match
    pub condition: ReificationCondition,
    /// Strategy to use when condition matches
    pub strategy: ReificationStrategy,
    /// Priority (higher number = higher priority)
    pub priority: u32,
}

/// Conditions for reification strategy selection
#[derive(Debug, Clone, PartialEq)]
pub enum ReificationCondition {
    /// Match by predicate IRI
    PredicateIri(String),
    /// Match by subject type
    SubjectType(TermType),
    /// Match by object type
    ObjectType(TermType),
    /// Match by nesting depth
    NestingDepth(usize),
    /// Match by graph size
    GraphSize(usize),
    /// Custom condition function name
    Custom(String),
}

/// RDF term types for condition matching
#[derive(Debug, Clone, PartialEq)]
pub enum TermType {
    NamedNode,
    BlankNode,
    Literal,
    QuotedTriple,
    Variable,
}

/// Enhanced reificator with advanced strategies
pub struct AdvancedReificator {
    strategy: AdvancedReificationStrategy,
    contexts: HashMap<String, ReificationContext>,
    #[allow(dead_code)]
    cache: lru::LruCache<String, Vec<StarTriple>>,
    statistics: ReificationStatistics,
}

/// Statistics for reification operations
#[derive(Debug, Clone, Default)]
pub struct ReificationStatistics {
    /// Total triples processed
    pub total_triples: usize,
    /// Total quoted triples found
    pub quoted_triples: usize,
    /// Total reification triples generated
    pub reification_triples: usize,
    /// Cache hit rate
    pub cache_hit_rate: f64,
    /// Average processing time per triple (microseconds)
    pub avg_processing_time: f64,
    /// Strategy usage counts
    pub strategy_usage: HashMap<String, usize>,
}

impl AdvancedReificator {
    /// Create a new advanced reificator
    pub fn new(strategy: AdvancedReificationStrategy) -> Self {
        Self {
            strategy,
            contexts: HashMap::new(),
            cache: lru::LruCache::new(std::num::NonZeroUsize::new(1000).expect("1000 is non-zero")),
            statistics: ReificationStatistics::default(),
        }
    }

    /// Process a graph with advanced reification strategies
    pub fn reify_graph_advanced(&mut self, star_graph: &StarGraph) -> StarResult<StarGraph> {
        let span = span!(Level::INFO, "reify_graph_advanced");
        let _enter = span.enter();

        let start_time = std::time::Instant::now();
        let mut reified_graph = StarGraph::new();

        for triple in star_graph.triples() {
            self.statistics.total_triples += 1;

            let strategy = self.select_strategy_for_triple(triple)?;
            let strategy_name = format!("{strategy:?}");
            *self
                .statistics
                .strategy_usage
                .entry(strategy_name)
                .or_insert(0) += 1;

            let reified_triples = self.reify_triple_with_strategy(triple, &strategy)?;
            for reified_triple in reified_triples {
                reified_graph.insert(reified_triple)?;
                self.statistics.reification_triples += 1;
            }
        }

        let processing_time = start_time.elapsed();
        self.statistics.avg_processing_time =
            processing_time.as_micros() as f64 / self.statistics.total_triples as f64;

        debug!(
            "Advanced reification completed: {} triples -> {} triples in {:?}",
            star_graph.len(),
            reified_graph.len(),
            processing_time
        );

        Ok(reified_graph)
    }

    /// Select the appropriate reification strategy for a triple
    fn select_strategy_for_triple(&self, triple: &StarTriple) -> StarResult<ReificationStrategy> {
        match &self.strategy {
            AdvancedReificationStrategy::Standard(strategy) => Ok(strategy.clone()),
            AdvancedReificationStrategy::Hybrid {
                simple_strategy,
                nested_strategy,
                predicate_strategies,
            } => {
                // Check for predicate-specific strategies
                if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                    if let Some(strategy) = predicate_strategies.get(&pred_node.iri) {
                        return Ok(strategy.clone());
                    }
                }

                // Check for nesting
                if self.has_nested_quoted_triples(triple) {
                    Ok(nested_strategy.clone())
                } else {
                    Ok(simple_strategy.clone())
                }
            }
            AdvancedReificationStrategy::Conditional {
                default_strategy,
                rules,
            } => {
                // Evaluate rules by priority
                let mut applicable_rules: Vec<_> = rules
                    .iter()
                    .filter(|rule| self.evaluate_condition(&rule.condition, triple))
                    .collect();
                applicable_rules.sort_by_key(|rule| std::cmp::Reverse(rule.priority));

                if let Some(rule) = applicable_rules.first() {
                    Ok(rule.strategy.clone())
                } else {
                    Ok(default_strategy.clone())
                }
            }
            AdvancedReificationStrategy::Optimized { base_strategy, .. } => {
                Ok(base_strategy.clone())
            }
        }
    }

    /// Check if a triple contains nested quoted triples
    fn has_nested_quoted_triples(&self, triple: &StarTriple) -> bool {
        self.term_has_quoted_triples(&triple.subject)
            || self.term_has_quoted_triples(&triple.predicate)
            || self.term_has_quoted_triples(&triple.object)
    }

    /// Check if a term contains quoted triples
    fn term_has_quoted_triples(&self, term: &StarTerm) -> bool {
        match term {
            StarTerm::QuotedTriple(_inner_triple) => {
                // The term itself is a quoted triple
                true
            }
            _ => false,
        }
    }

    /// Evaluate a reification condition against a triple
    fn evaluate_condition(&self, condition: &ReificationCondition, triple: &StarTriple) -> bool {
        match condition {
            ReificationCondition::PredicateIri(iri) => {
                if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                    pred_node.iri == *iri
                } else {
                    false
                }
            }
            ReificationCondition::SubjectType(term_type) => {
                self.matches_term_type(&triple.subject, term_type)
            }
            ReificationCondition::ObjectType(term_type) => {
                self.matches_term_type(&triple.object, term_type)
            }
            ReificationCondition::NestingDepth(max_depth) => {
                self.calculate_nesting_depth(triple) <= *max_depth
            }
            ReificationCondition::GraphSize(_) => {
                // Would need graph context to evaluate properly
                true
            }
            ReificationCondition::Custom(_) => {
                // Would need custom evaluation logic
                false
            }
        }
    }

    /// Check if a term matches a term type
    fn matches_term_type(&self, term: &StarTerm, term_type: &TermType) -> bool {
        matches!(
            (term, term_type),
            (StarTerm::NamedNode(_), TermType::NamedNode)
                | (StarTerm::BlankNode(_), TermType::BlankNode)
                | (StarTerm::Literal(_), TermType::Literal)
                | (StarTerm::QuotedTriple(_), TermType::QuotedTriple)
                | (StarTerm::Variable(_), TermType::Variable)
        )
    }

    /// Calculate the nesting depth of quoted triples in a triple
    fn calculate_nesting_depth(&self, triple: &StarTriple) -> usize {
        let subject_depth = self.term_nesting_depth(&triple.subject);
        let predicate_depth = self.term_nesting_depth(&triple.predicate);
        let object_depth = self.term_nesting_depth(&triple.object);

        subject_depth.max(predicate_depth).max(object_depth)
    }

    /// Calculate the nesting depth of a term
    fn term_nesting_depth(&self, term: &StarTerm) -> usize {
        match term {
            StarTerm::QuotedTriple(inner_triple) => 1 + self.calculate_nesting_depth(inner_triple),
            _ => 0,
        }
    }

    /// Reify a triple using a specific strategy
    fn reify_triple_with_strategy(
        &mut self,
        triple: &StarTriple,
        strategy: &ReificationStrategy,
    ) -> StarResult<Vec<StarTriple>> {
        // Get or create context for this strategy
        let context_key = format!("{strategy:?}");
        if !self.contexts.contains_key(&context_key) {
            self.contexts.insert(
                context_key.clone(),
                ReificationContext::new(strategy.clone(), None),
            );
        }

        // Create a temporary reificator for this strategy
        let context = self
            .contexts
            .get_mut(&context_key)
            .expect("context should exist after insertion");
        let mut temp_reificator = Reificator {
            context: ReificationContext::new(strategy.clone(), None),
        };

        // Copy the state from our context
        temp_reificator.context.counter = context.counter;
        temp_reificator.context.triple_to_id = context.triple_to_id.clone();
        temp_reificator.context.id_to_triple = context.id_to_triple.clone();

        let result = temp_reificator.reify_triple(triple);

        // Copy back the state
        context.counter = temp_reificator.context.counter;
        context.triple_to_id = temp_reificator.context.triple_to_id;
        context.id_to_triple = temp_reificator.context.id_to_triple;

        result
    }

    /// Get reification statistics
    pub fn get_statistics(&self) -> &ReificationStatistics {
        &self.statistics
    }

    /// Reset statistics
    pub fn reset_statistics(&mut self) {
        self.statistics = ReificationStatistics::default();
    }

    /// Export reification mapping for external use
    pub fn export_mappings(&self) -> HashMap<String, HashMap<String, String>> {
        let mut mappings = HashMap::new();

        for (strategy_key, context) in &self.contexts {
            mappings.insert(strategy_key.clone(), context.triple_to_id.clone());
        }

        mappings
    }
}

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

    #[test]
    fn test_basic_reification() {
        let mut reificator = Reificator::new(ReificationStrategy::StandardReification, None);

        // Create a simple RDF-star triple
        let quoted_triple = StarTriple::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::iri("http://example.org/object").unwrap(),
        );

        let triple_with_quoted = StarTriple::new(
            StarTerm::QuotedTriple(Box::new(quoted_triple)),
            StarTerm::iri("http://example.org/hasMetadata").unwrap(),
            StarTerm::literal("metadata").unwrap(),
        );

        let reified_triples = reificator.reify_triple(&triple_with_quoted).unwrap();

        // Should generate multiple triples for reification
        assert!(reified_triples.len() > 1);
    }

    #[test]
    fn test_dereification() {
        let mut reificator = Reificator::new(ReificationStrategy::StandardReification, None);

        // Create a test graph with RDF-star
        let mut star_graph = StarGraph::new();
        let quoted_triple = StarTriple::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::iri("http://example.org/object").unwrap(),
        );

        let triple_with_quoted = StarTriple::new(
            StarTerm::QuotedTriple(Box::new(quoted_triple)),
            StarTerm::iri("http://example.org/hasMetadata").unwrap(),
            StarTerm::literal("metadata").unwrap(),
        );

        star_graph.insert(triple_with_quoted).unwrap();

        // Reify and then dereify
        let reified_graph = reificator.reify_graph(&star_graph).unwrap();
        let dereified_graph = reificator.dereify_graph(&reified_graph).unwrap();

        // Should round-trip successfully
        assert_eq!(star_graph.len(), dereified_graph.len());
    }

    #[test]
    fn test_advanced_reification_strategies() {
        let hybrid_strategy = AdvancedReificationStrategy::Hybrid {
            simple_strategy: ReificationStrategy::StandardReification,
            nested_strategy: ReificationStrategy::BlankNodes,
            predicate_strategies: HashMap::new(),
        };

        let mut advanced_reificator = AdvancedReificator::new(hybrid_strategy);

        // Test with a simple graph
        let mut star_graph = StarGraph::new();
        let quoted_triple = StarTriple::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::iri("http://example.org/object").unwrap(),
        );

        let triple_with_quoted = StarTriple::new(
            StarTerm::QuotedTriple(Box::new(quoted_triple)),
            StarTerm::iri("http://example.org/hasMetadata").unwrap(),
            StarTerm::literal("metadata").unwrap(),
        );

        star_graph.insert(triple_with_quoted).unwrap();

        let reified_graph = advanced_reificator
            .reify_graph_advanced(&star_graph)
            .unwrap();
        assert!(!reified_graph.is_empty());

        let stats = advanced_reificator.get_statistics();
        assert!(stats.total_triples > 0);
    }

    #[test]
    fn test_conditional_reification() {
        let rules = vec![ReificationRule {
            condition: ReificationCondition::PredicateIri("http://example.org/special".to_string()),
            strategy: ReificationStrategy::BlankNodes,
            priority: 10,
        }];

        let conditional_strategy = AdvancedReificationStrategy::Conditional {
            default_strategy: ReificationStrategy::StandardReification,
            rules,
        };

        let mut advanced_reificator = AdvancedReificator::new(conditional_strategy);

        // Create test data that matches the condition
        let mut star_graph = StarGraph::new();
        let quoted_triple = StarTriple::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/special").unwrap(), // Matches condition
            StarTerm::iri("http://example.org/object").unwrap(),
        );

        let triple_with_quoted = StarTriple::new(
            StarTerm::QuotedTriple(Box::new(quoted_triple)),
            StarTerm::iri("http://example.org/hasMetadata").unwrap(),
            StarTerm::literal("metadata").unwrap(),
        );

        star_graph.insert(triple_with_quoted).unwrap();

        let reified_graph = advanced_reificator
            .reify_graph_advanced(&star_graph)
            .unwrap();
        assert!(!reified_graph.is_empty());

        let stats = advanced_reificator.get_statistics();
        assert!(!stats.strategy_usage.is_empty());
    }
}

/// Utility functions for reification
pub mod utils {
    use super::*;

    /// Check if a graph contains reification patterns
    pub fn has_reifications(graph: &StarGraph) -> bool {
        for triple in graph.triples() {
            if let StarTerm::NamedNode(node) = &triple.predicate {
                if matches!(
                    node.iri.as_str(),
                    vocab::RDF_SUBJECT | vocab::RDF_PREDICATE | vocab::RDF_OBJECT
                ) {
                    return true;
                }
            }
        }
        false
    }

    /// Count the number of reification statements in a graph
    pub fn count_reifications(graph: &StarGraph) -> usize {
        let mut statements = std::collections::HashSet::new();

        for triple in graph.triples() {
            if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                if matches!(
                    pred_node.iri.as_str(),
                    vocab::RDF_SUBJECT | vocab::RDF_PREDICATE | vocab::RDF_OBJECT
                ) {
                    if let StarTerm::NamedNode(subj_node) = &triple.subject {
                        statements.insert(&subj_node.iri);
                    } else if let StarTerm::BlankNode(subj_node) = &triple.subject {
                        statements.insert(&subj_node.id);
                    }
                }
            }
        }

        statements.len()
    }

    /// Validate that reification patterns are complete
    pub fn validate_reifications(graph: &StarGraph) -> StarResult<()> {
        let mut statements = HashMap::new();

        for triple in graph.triples() {
            if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                match pred_node.iri.as_str() {
                    vocab::RDF_SUBJECT => {
                        if let Some(stmt_id) = extract_statement_id(&triple.subject) {
                            statements.entry(stmt_id).or_insert([false, false, false])[0] = true;
                        }
                    }
                    vocab::RDF_PREDICATE => {
                        if let Some(stmt_id) = extract_statement_id(&triple.subject) {
                            statements.entry(stmt_id).or_insert([false, false, false])[1] = true;
                        }
                    }
                    vocab::RDF_OBJECT => {
                        if let Some(stmt_id) = extract_statement_id(&triple.subject) {
                            statements.entry(stmt_id).or_insert([false, false, false])[2] = true;
                        }
                    }
                    _ => {}
                }
            }
        }

        // Check for incomplete reifications
        for (stmt_id, completeness) in statements {
            if !completeness.iter().all(|&x| x) {
                return Err(StarError::reification_error(format!(
                    "Incomplete reification for statement {stmt_id}"
                )));
            }
        }

        Ok(())
    }

    fn extract_statement_id(term: &StarTerm) -> Option<String> {
        match term {
            StarTerm::NamedNode(node) => Some(node.iri.clone()),
            StarTerm::BlankNode(node) => Some(format!("_:{}", node.id)),
            _ => None,
        }
    }
}

#[cfg(test)]
mod additional_tests {
    use super::*;

    #[test]
    fn test_basic_reification() {
        let mut reificator = Reificator::new(
            ReificationStrategy::StandardReification,
            Some("http://example.org/stmt/".to_string()),
        );

        // Create a quoted triple
        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );

        let outer = StarTriple::new(
            StarTerm::quoted_triple(inner.clone()),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );

        let mut star_graph = StarGraph::new();
        star_graph.insert(outer).unwrap();

        let reified = reificator.reify_graph(&star_graph).unwrap();

        // Should have multiple triples for reification
        assert!(reified.len() > 1);

        // Should contain rdf:type rdf:Statement triple
        let has_type_triple = reified.triples().iter().any(|t| {
            if let (StarTerm::NamedNode(p), StarTerm::NamedNode(o)) = (&t.predicate, &t.object) {
                p.iri == vocab::RDF_TYPE && o.iri == vocab::RDF_STATEMENT
            } else {
                false
            }
        });
        assert!(has_type_triple);
    }

    #[test]
    fn test_dereification() {
        // Create a reified graph manually
        let mut reified_graph = StarGraph::new();

        let stmt_iri = "http://example.org/stmt/1";

        // stmt rdf:type rdf:Statement
        reified_graph
            .insert(StarTriple::new(
                StarTerm::iri(stmt_iri).unwrap(),
                StarTerm::iri(vocab::RDF_TYPE).unwrap(),
                StarTerm::iri(vocab::RDF_STATEMENT).unwrap(),
            ))
            .unwrap();

        // stmt rdf:subject alice
        reified_graph
            .insert(StarTriple::new(
                StarTerm::iri(stmt_iri).unwrap(),
                StarTerm::iri(vocab::RDF_SUBJECT).unwrap(),
                StarTerm::iri("http://example.org/alice").unwrap(),
            ))
            .unwrap();

        // stmt rdf:predicate age
        reified_graph
            .insert(StarTriple::new(
                StarTerm::iri(stmt_iri).unwrap(),
                StarTerm::iri(vocab::RDF_PREDICATE).unwrap(),
                StarTerm::iri("http://example.org/age").unwrap(),
            ))
            .unwrap();

        // stmt rdf:object "25"
        reified_graph
            .insert(StarTriple::new(
                StarTerm::iri(stmt_iri).unwrap(),
                StarTerm::iri(vocab::RDF_OBJECT).unwrap(),
                StarTerm::literal("25").unwrap(),
            ))
            .unwrap();

        // stmt certainty "0.9"
        reified_graph
            .insert(StarTriple::new(
                StarTerm::iri(stmt_iri).unwrap(),
                StarTerm::iri("http://example.org/certainty").unwrap(),
                StarTerm::literal("0.9").unwrap(),
            ))
            .unwrap();

        let mut dereificator = Reificator::new(
            ReificationStrategy::StandardReification,
            Some("http://example.org/stmt/".to_string()),
        );

        let star_graph = dereificator.dereify_graph(&reified_graph).unwrap();

        // Should have one triple with quoted triple as subject
        assert_eq!(star_graph.len(), 1);

        let triple = &star_graph.triples()[0];
        assert!(triple.subject.is_quoted_triple());
    }

    #[test]
    fn test_reification_roundtrip() {
        // Original RDF-star graph
        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );

        let outer = StarTriple::new(
            StarTerm::quoted_triple(inner),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );

        let mut original_graph = StarGraph::new();
        original_graph.insert(outer).unwrap();

        // Reify
        let mut reificator = Reificator::new(
            ReificationStrategy::StandardReification,
            Some("http://example.org/stmt/".to_string()),
        );
        let reified_graph = reificator.reify_graph(&original_graph).unwrap();

        // Dereify
        let mut dereificator = Reificator::new(
            ReificationStrategy::StandardReification,
            Some("http://example.org/stmt/".to_string()),
        );
        let recovered_graph = dereificator.dereify_graph(&reified_graph).unwrap();

        // Should have the same structure (though possibly different identifiers)
        assert_eq!(recovered_graph.len(), original_graph.len());

        let recovered_triple = &recovered_graph.triples()[0];
        assert!(recovered_triple.subject.is_quoted_triple());
    }

    #[test]
    fn test_utils() {
        let mut graph = StarGraph::new();

        // Add some reification triples
        graph
            .insert(StarTriple::new(
                StarTerm::iri("http://example.org/stmt1").unwrap(),
                StarTerm::iri(vocab::RDF_SUBJECT).unwrap(),
                StarTerm::iri("http://example.org/alice").unwrap(),
            ))
            .unwrap();

        assert!(utils::has_reifications(&graph));
        assert_eq!(utils::count_reifications(&graph), 1);

        // Incomplete reification should fail validation
        assert!(utils::validate_reifications(&graph).is_err());
    }
}

// ============================================================================
// EmbeddedTriple — type alias for a triple used in quoted/embedded context
// ============================================================================

/// A triple used as an embedded (quoted) subject or object of another triple.
///
/// In the W3C RDF-star specification quoted triples are structurally identical
/// to regular triples; this type alias documents the *semantic role* at the
/// call site and makes APIs self-documenting.
pub type EmbeddedTriple = StarTriple;

// ============================================================================
// AnnotationStyle
// ============================================================================

/// Controls which encoding strategy is used when converting RDF-star quoted
/// triples into standard RDF graphs.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum AnnotationStyle {
    /// Standard RDF reification: `rdf:Statement` + `rdf:subject /predicate /object`.
    #[default]
    Reification,
    /// Singleton properties: each statement gets a unique property IRI.
    Singleton,
    /// N-ary relation pattern: introduce an intermediate node linked via
    /// domain-specific predicates.
    NaryRelation,
}

// ============================================================================
// ReificationBridge
// ============================================================================

/// High-level bidirectional bridge between RDF-star quoted triples and
/// standard-RDF reification / annotation styles.
///
/// # Usage
///
/// ```
/// use oxirs_star::reification::{ReificationBridge, AnnotationStyle};
/// use oxirs_star::model::{StarTerm, StarTriple};
///
/// let bridge = ReificationBridge::new(AnnotationStyle::Reification);
///
/// let inner = StarTriple::new(
///     StarTerm::iri("http://example.org/alice").unwrap(),
///     StarTerm::iri("http://example.org/age").unwrap(),
///     StarTerm::literal("30").unwrap(),
/// );
///
/// let reified = bridge.star_to_reification(&inner);
/// assert!(!reified.is_empty());
/// ```
pub struct ReificationBridge {
    style: AnnotationStyle,
    base_iri: String,
    counter: std::sync::atomic::AtomicUsize,
}

impl ReificationBridge {
    /// Create a new bridge using the given annotation style and default base IRI.
    pub fn new(style: AnnotationStyle) -> Self {
        Self {
            style,
            base_iri: "http://reification.example/stmt/".to_string(),
            counter: std::sync::atomic::AtomicUsize::new(1),
        }
    }

    /// Create a bridge with a custom base IRI for generated statement nodes.
    pub fn with_base_iri(style: AnnotationStyle, base_iri: impl Into<String>) -> Self {
        Self {
            style,
            base_iri: base_iri.into(),
            counter: std::sync::atomic::AtomicUsize::new(1),
        }
    }

    /// Return the configured annotation style.
    pub fn style(&self) -> &AnnotationStyle {
        &self.style
    }

    // ------------------------------------------------------------------
    // star_to_reification
    // ------------------------------------------------------------------

    /// Convert an embedded (quoted) triple into a set of standard-RDF triples
    /// that represent it according to the configured [`AnnotationStyle`].
    ///
    /// For [`AnnotationStyle::Reification`] this generates:
    /// - `<stmt> rdf:type rdf:Statement`
    /// - `<stmt> rdf:subject <s>`
    /// - `<stmt> rdf:predicate <p>`
    /// - `<stmt> rdf:object <o>`
    pub fn star_to_reification(&self, triple: &EmbeddedTriple) -> Vec<StarTriple> {
        match self.style {
            AnnotationStyle::Reification => self.to_standard_reification(triple),
            AnnotationStyle::Singleton => self.to_singleton(triple),
            AnnotationStyle::NaryRelation => self.to_nary_relation(triple),
        }
    }

    fn next_id(&self) -> String {
        let n = self
            .counter
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        format!("{}{}", self.base_iri, n)
    }

    fn to_standard_reification(&self, triple: &EmbeddedTriple) -> Vec<StarTriple> {
        let stmt_iri = self.next_id();
        let mut triples = Vec::with_capacity(4);

        let stmt_term = match StarTerm::iri(&stmt_iri) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let rdf_type = match StarTerm::iri(vocab::RDF_TYPE) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let rdf_statement = match StarTerm::iri(vocab::RDF_STATEMENT) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let rdf_subject = match StarTerm::iri(vocab::RDF_SUBJECT) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let rdf_predicate = match StarTerm::iri(vocab::RDF_PREDICATE) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let rdf_object = match StarTerm::iri(vocab::RDF_OBJECT) {
            Ok(t) => t,
            Err(_) => return triples,
        };

        triples.push(StarTriple::new(stmt_term.clone(), rdf_type, rdf_statement));
        triples.push(StarTriple::new(
            stmt_term.clone(),
            rdf_subject,
            triple.subject.clone(),
        ));
        triples.push(StarTriple::new(
            stmt_term.clone(),
            rdf_predicate,
            triple.predicate.clone(),
        ));
        triples.push(StarTriple::new(
            stmt_term,
            rdf_object,
            triple.object.clone(),
        ));
        triples
    }

    fn to_singleton(&self, triple: &EmbeddedTriple) -> Vec<StarTriple> {
        let prop_iri = self.next_id();
        let mut triples = Vec::with_capacity(2);

        let prop_term = match StarTerm::iri(&prop_iri) {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let singleton_of =
            match StarTerm::iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#singletonPropertyOf") {
                Ok(t) => t,
                Err(_) => return triples,
            };

        // subject <singleton-property> object
        triples.push(StarTriple::new(
            triple.subject.clone(),
            prop_term.clone(),
            triple.object.clone(),
        ));
        // <singleton-property> rdf:singletonPropertyOf original-predicate
        triples.push(StarTriple::new(
            prop_term,
            singleton_of,
            triple.predicate.clone(),
        ));
        triples
    }

    fn to_nary_relation(&self, triple: &EmbeddedTriple) -> Vec<StarTriple> {
        let node_iri = self.next_id();
        let mut triples = Vec::with_capacity(3);

        let node_term = match StarTerm::iri(&node_iri) {
            Ok(t) => t,
            Err(_) => return triples,
        };

        let nary_subject = match StarTerm::iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject")
        {
            Ok(t) => t,
            Err(_) => return triples,
        };
        let nary_predicate =
            match StarTerm::iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate") {
                Ok(t) => t,
                Err(_) => return triples,
            };
        let nary_object = match StarTerm::iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#object") {
            Ok(t) => t,
            Err(_) => return triples,
        };

        triples.push(StarTriple::new(
            node_term.clone(),
            nary_subject,
            triple.subject.clone(),
        ));
        triples.push(StarTriple::new(
            node_term.clone(),
            nary_predicate,
            triple.predicate.clone(),
        ));
        triples.push(StarTriple::new(
            node_term,
            nary_object,
            triple.object.clone(),
        ));
        triples
    }

    // ------------------------------------------------------------------
    // reification_to_star
    // ------------------------------------------------------------------

    /// Attempt to reconstruct an [`EmbeddedTriple`] from a set of
    /// `rdf:Statement` reification triples.
    ///
    /// Returns `Some(triple)` when all three components (`rdf:subject`,
    /// `rdf:predicate`, `rdf:object`) are found; `None` otherwise.
    pub fn reification_to_star(&self, stmts: &[StarTriple]) -> Option<EmbeddedTriple> {
        let mut subject = None;
        let mut predicate = None;
        let mut object = None;

        for triple in stmts {
            if let StarTerm::NamedNode(pred_node) = &triple.predicate {
                match pred_node.iri.as_str() {
                    s if s == vocab::RDF_SUBJECT => subject = Some(triple.object.clone()),
                    s if s == vocab::RDF_PREDICATE => predicate = Some(triple.object.clone()),
                    s if s == vocab::RDF_OBJECT => object = Some(triple.object.clone()),
                    _ => {}
                }
            }
        }

        if let (Some(s), Some(p), Some(o)) = (subject, predicate, object) {
            Some(StarTriple::new(s, p, o))
        } else {
            None
        }
    }

    // ------------------------------------------------------------------
    // convert_graph_to_reification
    // ------------------------------------------------------------------

    /// Convert every triple in `graph` that contains embedded (quoted) triples
    /// into standard-RDF reification triples, returning the expanded graph.
    ///
    /// Plain triples (without quoted-triple terms) are passed through unchanged.
    pub fn convert_graph_to_reification(&self, graph: &[StarTriple]) -> Vec<StarTriple> {
        let mut result = Vec::new();

        for triple in graph {
            let has_quoted = matches!(&triple.subject, StarTerm::QuotedTriple(_))
                || matches!(&triple.object, StarTerm::QuotedTriple(_));

            if has_quoted {
                // Expand quoted subject
                if let StarTerm::QuotedTriple(inner) = &triple.subject {
                    result.extend(self.star_to_reification(inner));
                }
                // Expand quoted object
                if let StarTerm::QuotedTriple(inner) = &triple.object {
                    result.extend(self.star_to_reification(inner));
                }
                // Also include the outer triple with IRIs substituted
                // (pass-through; caller can add annotations separately)
            } else {
                result.push(triple.clone());
            }
        }

        result
    }

    // ------------------------------------------------------------------
    // convert_reification_to_star
    // ------------------------------------------------------------------

    /// Scan `graph` for `rdf:Statement` patterns and convert each complete
    /// reification cluster back into an [`EmbeddedTriple`].
    ///
    /// Returns a `Vec` of reconstructed embedded triples. Incomplete clusters
    /// are silently skipped.
    pub fn convert_reification_to_star(&self, graph: &[StarTriple]) -> Vec<EmbeddedTriple> {
        use std::collections::{HashMap, HashSet};

        // Collect all statement nodes (subjects of rdf:type rdf:Statement)
        let mut stmt_nodes: HashSet<String> = HashSet::new();
        for triple in graph {
            if let (StarTerm::NamedNode(pred), StarTerm::NamedNode(obj)) =
                (&triple.predicate, &triple.object)
            {
                if pred.iri == vocab::RDF_TYPE && obj.iri == vocab::RDF_STATEMENT {
                    if let StarTerm::NamedNode(subj) = &triple.subject {
                        stmt_nodes.insert(subj.iri.clone());
                    }
                }
            }
        }

        // For each statement node collect its rdf:subject / rdf:predicate / rdf:object
        let mut clusters: HashMap<String, Vec<StarTriple>> = HashMap::new();
        for triple in graph {
            if let StarTerm::NamedNode(subj) = &triple.subject {
                if stmt_nodes.contains(&subj.iri) {
                    clusters
                        .entry(subj.iri.clone())
                        .or_default()
                        .push(triple.clone());
                }
            }
        }

        let mut embedded_triples = Vec::new();
        for cluster_triples in clusters.values() {
            if let Some(et) = self.reification_to_star(cluster_triples) {
                embedded_triples.push(et);
            }
        }
        embedded_triples
    }
}

// ============================================================================
// Tests for the new ReificationBridge API
// ============================================================================

#[cfg(test)]
mod bridge_tests {
    use super::*;

    fn iri(s: &str) -> StarTerm {
        StarTerm::iri(s).expect("iri")
    }
    fn lit(s: &str) -> StarTerm {
        StarTerm::literal(s).expect("lit")
    }

    fn sample_triple() -> StarTriple {
        StarTriple::new(
            iri("http://example.org/alice"),
            iri("http://example.org/age"),
            lit("30"),
        )
    }

    // ------------------------------------------------------------------
    // star_to_reification
    // ------------------------------------------------------------------

    #[test]
    fn test_bridge_reification_style_generates_four_triples() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let triples = bridge.star_to_reification(&sample_triple());
        assert_eq!(
            triples.len(),
            4,
            "rdf:Statement reification needs 4 triples"
        );
    }

    #[test]
    fn test_bridge_reification_contains_rdf_type() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let triples = bridge.star_to_reification(&sample_triple());
        let has_type = triples.iter().any(|t| {
            if let (StarTerm::NamedNode(p), StarTerm::NamedNode(o)) = (&t.predicate, &t.object) {
                p.iri == vocab::RDF_TYPE && o.iri == vocab::RDF_STATEMENT
            } else {
                false
            }
        });
        assert!(has_type, "must include rdf:type rdf:Statement triple");
    }

    #[test]
    fn test_bridge_reification_contains_rdf_subject() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let triples = bridge.star_to_reification(&sample_triple());
        let has_subject = triples.iter().any(|t| {
            if let StarTerm::NamedNode(p) = &t.predicate {
                p.iri == vocab::RDF_SUBJECT
            } else {
                false
            }
        });
        assert!(has_subject);
    }

    #[test]
    fn test_bridge_reification_contains_rdf_predicate() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let triples = bridge.star_to_reification(&sample_triple());
        let has_predicate = triples.iter().any(|t| {
            if let StarTerm::NamedNode(p) = &t.predicate {
                p.iri == vocab::RDF_PREDICATE
            } else {
                false
            }
        });
        assert!(has_predicate);
    }

    #[test]
    fn test_bridge_reification_contains_rdf_object() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let triples = bridge.star_to_reification(&sample_triple());
        let has_object = triples.iter().any(|t| {
            if let StarTerm::NamedNode(p) = &t.predicate {
                p.iri == vocab::RDF_OBJECT
            } else {
                false
            }
        });
        assert!(has_object);
    }

    #[test]
    fn test_bridge_singleton_style_generates_two_triples() {
        let bridge = ReificationBridge::new(AnnotationStyle::Singleton);
        let triples = bridge.star_to_reification(&sample_triple());
        assert_eq!(triples.len(), 2, "singleton style needs 2 triples");
    }

    #[test]
    fn test_bridge_nary_relation_style_generates_three_triples() {
        let bridge = ReificationBridge::new(AnnotationStyle::NaryRelation);
        let triples = bridge.star_to_reification(&sample_triple());
        assert_eq!(triples.len(), 3, "nary relation style needs 3 triples");
    }

    // ------------------------------------------------------------------
    // reification_to_star
    // ------------------------------------------------------------------

    #[test]
    fn test_bridge_reification_roundtrip() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let original = sample_triple();
        let reified = bridge.star_to_reification(&original);
        let recovered = bridge.reification_to_star(&reified);
        assert!(recovered.is_some(), "should recover the embedded triple");
        let recovered = recovered.unwrap();
        assert_eq!(recovered.subject, original.subject);
        assert_eq!(recovered.predicate, original.predicate);
        assert_eq!(recovered.object, original.object);
    }

    #[test]
    fn test_bridge_reification_to_star_incomplete_returns_none() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        // Only provide rdf:subject, missing predicate and object
        let partial = vec![StarTriple::new(
            iri("http://example.org/stmt1"),
            iri(vocab::RDF_SUBJECT),
            iri("http://example.org/alice"),
        )];
        let recovered = bridge.reification_to_star(&partial);
        assert!(
            recovered.is_none(),
            "incomplete reification should return None"
        );
    }

    #[test]
    fn test_bridge_reification_to_star_empty_returns_none() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let recovered = bridge.reification_to_star(&[]);
        assert!(recovered.is_none());
    }

    // ------------------------------------------------------------------
    // convert_graph_to_reification
    // ------------------------------------------------------------------

    #[test]
    fn test_convert_graph_to_reification_expands_quoted_subjects() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let inner = sample_triple();
        let outer = StarTriple::new(
            StarTerm::quoted_triple(inner),
            iri("http://example.org/certainty"),
            lit("high"),
        );
        let expanded = bridge.convert_graph_to_reification(&[outer]);
        // Should contain the 4 reification triples for the inner triple
        assert!(expanded.len() >= 4);
    }

    #[test]
    fn test_convert_graph_plain_triples_pass_through() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let plain = sample_triple();
        let expanded = bridge.convert_graph_to_reification(std::slice::from_ref(&plain));
        assert_eq!(expanded.len(), 1);
        assert_eq!(expanded[0], plain);
    }

    // ------------------------------------------------------------------
    // convert_reification_to_star
    // ------------------------------------------------------------------

    #[test]
    fn test_convert_reification_to_star_roundtrip() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let inner = sample_triple();
        let reified = bridge.star_to_reification(&inner);
        let recovered = bridge.convert_reification_to_star(&reified);
        assert_eq!(recovered.len(), 1);
        assert_eq!(recovered[0].subject, inner.subject);
        assert_eq!(recovered[0].predicate, inner.predicate);
        assert_eq!(recovered[0].object, inner.object);
    }

    #[test]
    fn test_convert_reification_to_star_multiple_clusters() {
        let bridge = ReificationBridge::new(AnnotationStyle::Reification);
        let t1 = sample_triple();
        let t2 = StarTriple::new(
            iri("http://example.org/bob"),
            iri("http://example.org/age"),
            lit("25"),
        );
        let mut all_reified = bridge.star_to_reification(&t1);
        all_reified.extend(bridge.star_to_reification(&t2));
        let recovered = bridge.convert_reification_to_star(&all_reified);
        assert_eq!(recovered.len(), 2, "should recover both embedded triples");
    }

    #[test]
    fn test_annotation_style_default_is_reification() {
        assert_eq!(AnnotationStyle::default(), AnnotationStyle::Reification);
    }

    #[test]
    fn test_bridge_with_base_iri() {
        let bridge =
            ReificationBridge::with_base_iri(AnnotationStyle::Reification, "http://my.org/stmts/");
        let triples = bridge.star_to_reification(&sample_triple());
        // Statement node IRI should use the custom base
        let stmt_node = triples
            .iter()
            .filter_map(|t| {
                if let StarTerm::NamedNode(n) = &t.subject {
                    Some(n.iri.clone())
                } else {
                    None
                }
            })
            .next();
        assert!(stmt_node.is_some());
        assert!(
            stmt_node.unwrap().starts_with("http://my.org/stmts/"),
            "statement node should use custom base IRI"
        );
    }

    #[test]
    fn test_embedded_triple_type_alias() {
        // EmbeddedTriple is just StarTriple — verify it compiles and works
        let et: EmbeddedTriple = sample_triple();
        assert!(et.validate().is_ok());
    }
}