oxirs-arq 0.2.4

Jena-style SPARQL algebra with extension points and query optimization
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
//! SPARQL-star (RDF-star) Completeness Module
//!
//! Implements the complete SPARQL 1.2 / SPARQL-star specification for quoted triples,
//! annotation queries, pattern matching, and CONSTRUCT support.
//!
//! # Overview
//!
//! RDF-star (W3C spec) allows triples as subjects or objects — called *quoted triples*:
//!
//! ```text
//! <<  <http://s>  <http://p>  <http://o>  >>  <http://certainty>  "0.9"
//! ```
//!
//! SPARQL-star introduces corresponding query syntax:
//!
//! ```sparql
//! SELECT ?s ?p ?o ?c WHERE {
//!     << ?s ?p ?o >> <http://certainty> ?c .
//! }
//! ```
//!
//! # References
//! - <https://www.w3.org/2021/12/rdf-star.html>
//! - <https://w3c.github.io/sparql-star/>

use crate::algebra::{Literal, Term, TriplePattern};
use anyhow::{anyhow, Context};
use oxirs_core::model::{NamedNode, Variable};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

// ─── Types ───────────────────────────────────────────────────────────────────

/// A *quoted triple* — an RDF-star triple usable as a subject or object.
///
/// Subjects and objects may themselves be quoted triples, enabling arbitrary nesting.
///
/// ```text
/// <<  <<  <s1>  <p1>  <o1>  >>  <certainty>  "0.9"  >>
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct QuotedTriple {
    /// Subject: a named node, blank node, variable, or recursively nested quoted triple
    pub subject: StarSubject,
    /// Predicate: always a named node or a variable
    pub predicate: StarPredicate,
    /// Object: any RDF term, or a recursively nested quoted triple
    pub object: StarObject,
}

impl QuotedTriple {
    /// Construct a new quoted triple
    pub fn new(subject: StarSubject, predicate: StarPredicate, object: StarObject) -> Self {
        Self {
            subject,
            predicate,
            object,
        }
    }

    /// Return the nesting depth of this quoted triple (1 for a plain quoted triple,
    /// 2+ for nested quoted triples)
    pub fn nesting_depth(&self) -> usize {
        let s_depth = self.subject.nesting_depth();
        let o_depth = self.object.nesting_depth();
        1 + s_depth.max(o_depth)
    }

    /// Return `true` if the quoted triple contains any variable (it is a pattern)
    pub fn is_pattern(&self) -> bool {
        self.subject.is_variable()
            || self.predicate.is_variable()
            || self.object.is_variable()
            || self.subject.contains_variable()
            || self.object.contains_variable()
    }

    /// Collect all variables used in this quoted triple (recursive)
    pub fn variables(&self) -> Vec<Variable> {
        let mut vars = Vec::new();
        self.subject.collect_variables(&mut vars);
        self.predicate.collect_variables(&mut vars);
        self.object.collect_variables(&mut vars);
        vars
    }
}

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

// ─── StarSubject ─────────────────────────────────────────────────────────────

/// A term that can appear as the subject of a quoted triple.
/// (Subjects cannot be literals per the RDF-star spec.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StarSubject {
    /// An IRI
    NamedNode(NamedNode),
    /// A blank node identified by a string
    BlankNode(String),
    /// A variable (for SPARQL-star patterns)
    Variable(Variable),
    /// A recursively nested quoted triple
    Quoted(Box<QuotedTriple>),
}

impl StarSubject {
    /// Return `true` if this is a variable
    pub fn is_variable(&self) -> bool {
        matches!(self, StarSubject::Variable(_))
    }

    /// Return `true` if any nested element is a variable
    pub fn contains_variable(&self) -> bool {
        match self {
            StarSubject::Quoted(qt) => qt.is_pattern(),
            _ => self.is_variable(),
        }
    }

    /// Recursively collect variable names
    pub fn collect_variables(&self, out: &mut Vec<Variable>) {
        match self {
            StarSubject::Variable(v) => out.push(v.clone()),
            StarSubject::Quoted(qt) => {
                qt.subject.collect_variables(out);
                qt.predicate.collect_variables(out);
                qt.object.collect_variables(out);
            }
            _ => {}
        }
    }

    /// Return the nesting depth contributed by this subject
    pub fn nesting_depth(&self) -> usize {
        match self {
            StarSubject::Quoted(qt) => qt.nesting_depth(),
            _ => 0,
        }
    }

    /// Convert to an ARQ [`Term`]
    pub fn to_term(&self) -> Term {
        match self {
            StarSubject::NamedNode(n) => Term::Iri(n.clone()),
            StarSubject::BlankNode(id) => Term::BlankNode(id.clone()),
            StarSubject::Variable(v) => Term::Variable(v.clone()),
            StarSubject::Quoted(qt) => Term::QuotedTriple(Box::new(qt.to_triple_pattern())),
        }
    }

    /// Try to construct from an ARQ [`Term`]
    pub fn from_term(term: &Term) -> anyhow::Result<Self> {
        match term {
            Term::Iri(n) => Ok(StarSubject::NamedNode(n.clone())),
            Term::BlankNode(id) => Ok(StarSubject::BlankNode(id.clone())),
            Term::Variable(v) => Ok(StarSubject::Variable(v.clone())),
            Term::QuotedTriple(tp) => Ok(StarSubject::Quoted(Box::new(
                QuotedTriple::from_triple_pattern(tp)?,
            ))),
            Term::Literal(_) => Err(anyhow!("literals cannot be used as RDF-star subjects")),
            Term::PropertyPath(_) => Err(anyhow!("property paths cannot be RDF-star subjects")),
        }
    }
}

impl fmt::Display for StarSubject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StarSubject::NamedNode(n) => write!(f, "{n}"),
            StarSubject::BlankNode(id) => write!(f, "_:{id}"),
            StarSubject::Variable(v) => write!(f, "?{}", v.name()),
            StarSubject::Quoted(qt) => write!(f, "{qt}"),
        }
    }
}

// ─── StarPredicate ────────────────────────────────────────────────────────────

/// A term that can appear as the predicate of a quoted triple.
/// (Only named nodes and variables are permitted.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StarPredicate {
    /// An IRI predicate
    NamedNode(NamedNode),
    /// A variable predicate (for SPARQL-star patterns)
    Variable(Variable),
}

impl StarPredicate {
    /// Return `true` if this is a variable
    pub fn is_variable(&self) -> bool {
        matches!(self, StarPredicate::Variable(_))
    }

    /// Collect variables into `out`
    pub fn collect_variables(&self, out: &mut Vec<Variable>) {
        if let StarPredicate::Variable(v) = self {
            out.push(v.clone());
        }
    }

    /// Convert to an ARQ [`Term`]
    pub fn to_term(&self) -> Term {
        match self {
            StarPredicate::NamedNode(n) => Term::Iri(n.clone()),
            StarPredicate::Variable(v) => Term::Variable(v.clone()),
        }
    }

    /// Try to construct from an ARQ [`Term`]
    pub fn from_term(term: &Term) -> anyhow::Result<Self> {
        match term {
            Term::Iri(n) => Ok(StarPredicate::NamedNode(n.clone())),
            Term::Variable(v) => Ok(StarPredicate::Variable(v.clone())),
            other => Err(anyhow!("term {other} cannot be a predicate")),
        }
    }
}

impl fmt::Display for StarPredicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StarPredicate::NamedNode(n) => write!(f, "{n}"),
            StarPredicate::Variable(v) => write!(f, "?{}", v.name()),
        }
    }
}

// ─── StarObject ───────────────────────────────────────────────────────────────

/// A term that can appear as the object of a quoted triple.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StarObject {
    /// An IRI
    NamedNode(NamedNode),
    /// A blank node
    BlankNode(String),
    /// A literal value
    Literal(Literal),
    /// A variable (for SPARQL-star patterns)
    Variable(Variable),
    /// A recursively nested quoted triple
    Quoted(Box<QuotedTriple>),
}

impl StarObject {
    /// Return `true` if this is a variable
    pub fn is_variable(&self) -> bool {
        matches!(self, StarObject::Variable(_))
    }

    /// Return `true` if any nested element is a variable
    pub fn contains_variable(&self) -> bool {
        match self {
            StarObject::Quoted(qt) => qt.is_pattern(),
            _ => self.is_variable(),
        }
    }

    /// Collect variables into `out`
    pub fn collect_variables(&self, out: &mut Vec<Variable>) {
        match self {
            StarObject::Variable(v) => out.push(v.clone()),
            StarObject::Quoted(qt) => {
                qt.subject.collect_variables(out);
                qt.predicate.collect_variables(out);
                qt.object.collect_variables(out);
            }
            _ => {}
        }
    }

    /// Return the nesting depth contributed by this object
    pub fn nesting_depth(&self) -> usize {
        match self {
            StarObject::Quoted(qt) => qt.nesting_depth(),
            _ => 0,
        }
    }

    /// Convert to an ARQ [`Term`]
    pub fn to_term(&self) -> Term {
        match self {
            StarObject::NamedNode(n) => Term::Iri(n.clone()),
            StarObject::BlankNode(id) => Term::BlankNode(id.clone()),
            StarObject::Literal(l) => Term::Literal(l.clone()),
            StarObject::Variable(v) => Term::Variable(v.clone()),
            StarObject::Quoted(qt) => Term::QuotedTriple(Box::new(qt.to_triple_pattern())),
        }
    }

    /// Try to construct from an ARQ [`Term`]
    pub fn from_term(term: &Term) -> anyhow::Result<Self> {
        match term {
            Term::Iri(n) => Ok(StarObject::NamedNode(n.clone())),
            Term::BlankNode(id) => Ok(StarObject::BlankNode(id.clone())),
            Term::Literal(l) => Ok(StarObject::Literal(l.clone())),
            Term::Variable(v) => Ok(StarObject::Variable(v.clone())),
            Term::QuotedTriple(tp) => Ok(StarObject::Quoted(Box::new(
                QuotedTriple::from_triple_pattern(tp)?,
            ))),
            Term::PropertyPath(_) => Err(anyhow!("property paths cannot be RDF-star objects")),
        }
    }
}

impl fmt::Display for StarObject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StarObject::NamedNode(n) => write!(f, "{n}"),
            StarObject::BlankNode(id) => write!(f, "_:{id}"),
            StarObject::Literal(l) => write!(f, "{l}"),
            StarObject::Variable(v) => write!(f, "?{}", v.name()),
            StarObject::Quoted(qt) => write!(f, "{qt}"),
        }
    }
}

// ─── QuotedTriple helpers ─────────────────────────────────────────────────────

impl QuotedTriple {
    /// Convert to an ARQ [`TriplePattern`]
    pub fn to_triple_pattern(&self) -> TriplePattern {
        TriplePattern::new(
            self.subject.to_term(),
            self.predicate.to_term(),
            self.object.to_term(),
        )
    }

    /// Try to construct from an ARQ [`TriplePattern`]
    pub fn from_triple_pattern(pattern: &TriplePattern) -> anyhow::Result<Self> {
        let subject =
            StarSubject::from_term(&pattern.subject).context("converting quoted triple subject")?;
        let predicate = StarPredicate::from_term(&pattern.predicate)
            .context("converting quoted triple predicate")?;
        let object =
            StarObject::from_term(&pattern.object).context("converting quoted triple object")?;
        Ok(QuotedTriple::new(subject, predicate, object))
    }

    /// Build a quoted triple from raw IRI strings (convenience for tests)
    pub fn from_iris(s: &str, p: &str, o: &str) -> anyhow::Result<Self> {
        Ok(QuotedTriple::new(
            StarSubject::NamedNode(NamedNode::new(s)?),
            StarPredicate::NamedNode(NamedNode::new(p)?),
            StarObject::NamedNode(NamedNode::new(o)?),
        ))
    }
}

// ─── StarPattern ─────────────────────────────────────────────────────────────

/// A SPARQL-star *annotation pattern*:
///
/// ```sparql
/// << <s> <p> <o> >>  <anno_pred>  <anno_obj>
/// ```
///
/// This matches all annotation triples attached to the quoted triple `<< s p o >>`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StarPattern {
    /// The quoted triple being annotated
    pub quoted: QuotedTriple,
    /// The annotation predicate (may be a variable)
    pub predicate: StarPredicate,
    /// The annotation object (any RDF-star object term)
    pub object: StarObject,
}

impl StarPattern {
    /// Construct a new annotation pattern
    pub fn new(quoted: QuotedTriple, predicate: StarPredicate, object: StarObject) -> Self {
        Self {
            quoted,
            predicate,
            object,
        }
    }

    /// Collect all variables in this pattern (including inside the quoted triple)
    pub fn variables(&self) -> Vec<Variable> {
        let mut vars = self.quoted.variables();
        self.predicate.collect_variables(&mut vars);
        self.object.collect_variables(&mut vars);
        vars
    }

    /// Return `true` if this pattern contains at least one variable
    pub fn is_pattern(&self) -> bool {
        !self.variables().is_empty()
    }
}

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

// ─── Annotation ──────────────────────────────────────────────────────────────

/// A concrete annotation: a (predicate, object) pair attached to a quoted triple
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Annotation {
    /// Annotation predicate
    pub predicate: NamedNode,
    /// Annotation object
    pub object: StarObject,
}

impl Annotation {
    /// Construct a new annotation
    pub fn new(predicate: NamedNode, object: StarObject) -> Self {
        Self { predicate, object }
    }
}

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

// ─── StarOperator ─────────────────────────────────────────────────────────────

/// High-level SPARQL-star operators that appear in query plans
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StarOperator {
    /// Find all annotation triples matching a [`StarPattern`]
    FindAnnotations {
        /// The annotation pattern to match
        pattern: StarPattern,
    },
    /// Add annotation triples to a quoted triple in the dataset
    AddAnnotation {
        /// The triple to annotate
        triple: QuotedTriple,
        /// The annotations to add
        annotations: Vec<Annotation>,
    },
    /// Remove a specific annotation predicate from a quoted triple
    RemoveAnnotation {
        /// The annotated triple
        triple: QuotedTriple,
        /// The predicate whose annotation should be removed
        predicate: NamedNode,
    },
    /// Asserta that a quoted triple exists (without annotation)
    AssertQuoted {
        /// The triple to assert
        triple: QuotedTriple,
    },
    /// Retract a quoted triple from the dataset
    RetractQuoted {
        /// The triple to retract
        triple: QuotedTriple,
    },
}

impl fmt::Display for StarOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StarOperator::FindAnnotations { pattern } => {
                write!(f, "FindAnnotations({pattern})")
            }
            StarOperator::AddAnnotation {
                triple,
                annotations,
            } => {
                write!(
                    f,
                    "AddAnnotation({triple}, [{} annotations])",
                    annotations.len()
                )
            }
            StarOperator::RemoveAnnotation { triple, predicate } => {
                write!(f, "RemoveAnnotation({triple}, <{predicate}>)")
            }
            StarOperator::AssertQuoted { triple } => {
                write!(f, "AssertQuoted({triple})")
            }
            StarOperator::RetractQuoted { triple } => {
                write!(f, "RetractQuoted({triple})")
            }
        }
    }
}

// ─── In-memory RDF-star store ─────────────────────────────────────────────────

/// A triple stored together with its annotations
#[derive(Debug, Clone)]
pub struct AnnotatedTriple {
    /// The quoted triple
    pub triple: QuotedTriple,
    /// Annotation (predicate → object) pairs
    pub annotations: HashMap<String, StarObject>,
}

impl AnnotatedTriple {
    /// Construct a new annotated triple without any annotations
    pub fn new(triple: QuotedTriple) -> Self {
        Self {
            triple,
            annotations: HashMap::new(),
        }
    }

    /// Add or overwrite an annotation
    pub fn annotate(&mut self, predicate: &NamedNode, object: StarObject) {
        self.annotations.insert(predicate.to_string(), object);
    }

    /// Remove an annotation; returns `true` if it was present
    pub fn remove_annotation(&mut self, predicate: &NamedNode) -> bool {
        self.annotations.remove(&predicate.to_string()).is_some()
    }

    /// Return the annotation for the given predicate, if any
    pub fn annotation(&self, predicate: &NamedNode) -> Option<&StarObject> {
        self.annotations.get(&predicate.to_string())
    }
}

/// In-memory store for RDF-star quoted triples and their annotations.
///
/// This is a self-contained store that does not depend on the optional `oxirs-star` crate.
/// It underpins the completeness tests below.
#[derive(Debug, Clone, Default)]
pub struct RdfStarStore {
    /// Annotated triples, keyed by the serialised form of the quoted triple
    triples: HashMap<String, AnnotatedTriple>,
}

impl RdfStarStore {
    /// Construct an empty store
    pub fn new() -> Self {
        Self::default()
    }

    /// Return the number of quoted triples (with or without annotations) in the store
    pub fn len(&self) -> usize {
        self.triples.len()
    }

    /// Return `true` if the store is empty
    pub fn is_empty(&self) -> bool {
        self.triples.is_empty()
    }

    /// Insert or retrieve the entry for a quoted triple
    fn key(triple: &QuotedTriple) -> String {
        triple.to_string()
    }

    /// Assert that a quoted triple exists in the store (idempotent)
    pub fn assert_triple(&mut self, triple: QuotedTriple) {
        self.triples
            .entry(Self::key(&triple))
            .or_insert_with(|| AnnotatedTriple::new(triple));
    }

    /// Retract a quoted triple and all its annotations
    pub fn retract_triple(&mut self, triple: &QuotedTriple) -> bool {
        self.triples.remove(&Self::key(triple)).is_some()
    }

    /// Add an annotation to an existing quoted triple.
    /// If the triple has not been asserted yet, it is created automatically.
    pub fn add_annotation(
        &mut self,
        triple: &QuotedTriple,
        predicate: &NamedNode,
        object: StarObject,
    ) {
        let entry = self
            .triples
            .entry(Self::key(triple))
            .or_insert_with(|| AnnotatedTriple::new(triple.clone()));
        entry.annotate(predicate, object);
    }

    /// Remove a single annotation from a quoted triple.
    /// Returns `true` if the annotation was present.
    pub fn remove_annotation(&mut self, triple: &QuotedTriple, predicate: &NamedNode) -> bool {
        if let Some(entry) = self.triples.get_mut(&Self::key(triple)) {
            entry.remove_annotation(predicate)
        } else {
            false
        }
    }

    /// Look up all annotations for a quoted triple
    pub fn annotations(&self, triple: &QuotedTriple) -> Option<&AnnotatedTriple> {
        self.triples.get(&Self::key(triple))
    }

    /// Return `true` if the quoted triple exists in the store
    pub fn contains(&self, triple: &QuotedTriple) -> bool {
        self.triples.contains_key(&Self::key(triple))
    }

    /// Iterate over all annotated triples
    pub fn iter(&self) -> impl Iterator<Item = &AnnotatedTriple> {
        self.triples.values()
    }

    /// Apply a [`StarOperator`] to this store.
    ///
    /// Returns the matching [`AnnotatedTriple`] entries for `FindAnnotations`,
    /// or an empty vec for mutating operators.
    pub fn apply_operator(&mut self, op: StarOperator) -> Vec<AnnotatedTriple> {
        match op {
            StarOperator::AssertQuoted { triple } => {
                self.assert_triple(triple);
                Vec::new()
            }
            StarOperator::RetractQuoted { triple } => {
                self.retract_triple(&triple);
                Vec::new()
            }
            StarOperator::AddAnnotation {
                triple,
                annotations,
            } => {
                for ann in &annotations {
                    self.add_annotation(&triple, &ann.predicate, ann.object.clone());
                }
                Vec::new()
            }
            StarOperator::RemoveAnnotation { triple, predicate } => {
                self.remove_annotation(&triple, &predicate);
                Vec::new()
            }
            StarOperator::FindAnnotations { pattern } => self.find_annotations(&pattern),
        }
    }

    /// Match all annotation triples against the given [`StarPattern`]
    pub fn find_annotations(&self, pattern: &StarPattern) -> Vec<AnnotatedTriple> {
        self.triples
            .values()
            .filter(|entry| triple_matches_pattern(&entry.triple, &pattern.quoted))
            .filter(|entry| {
                // Filter annotation (pred, obj) pairs
                entry.annotations.iter().any(|(pred_key, obj)| {
                    predicate_matches(&pattern.predicate, pred_key)
                        && object_matches(&pattern.object, obj)
                })
            })
            .cloned()
            .collect()
    }
}

// ─── Pattern matching helpers ─────────────────────────────────────────────────

/// Return `true` if a quoted triple matches a pattern (variables bind to anything)
fn triple_matches_pattern(triple: &QuotedTriple, pattern: &QuotedTriple) -> bool {
    subject_matches(&pattern.subject, &triple.subject)
        && predicate_matches_terms(&pattern.predicate, &triple.predicate)
        && object_matches_object(&pattern.object, &triple.object)
}

fn subject_matches(pattern: &StarSubject, value: &StarSubject) -> bool {
    match pattern {
        StarSubject::Variable(_) => true,
        StarSubject::NamedNode(pn) => {
            matches!(value, StarSubject::NamedNode(vn) if vn == pn)
        }
        StarSubject::BlankNode(pb) => {
            matches!(value, StarSubject::BlankNode(vb) if vb == pb)
        }
        StarSubject::Quoted(pq) => {
            matches!(value, StarSubject::Quoted(vq) if triple_matches_pattern(vq, pq))
        }
    }
}

fn predicate_matches_terms(pattern: &StarPredicate, value: &StarPredicate) -> bool {
    match pattern {
        StarPredicate::Variable(_) => true,
        StarPredicate::NamedNode(pn) => {
            matches!(value, StarPredicate::NamedNode(vn) if vn == pn)
        }
    }
}

fn object_matches_object(pattern: &StarObject, value: &StarObject) -> bool {
    match pattern {
        StarObject::Variable(_) => true,
        StarObject::NamedNode(pn) => {
            matches!(value, StarObject::NamedNode(vn) if vn == pn)
        }
        StarObject::BlankNode(pb) => {
            matches!(value, StarObject::BlankNode(vb) if vb == pb)
        }
        StarObject::Literal(pl) => {
            matches!(value, StarObject::Literal(vl) if vl == pl)
        }
        StarObject::Quoted(pq) => {
            matches!(value, StarObject::Quoted(vq) if triple_matches_pattern(vq, pq))
        }
    }
}

/// Match a predicate pattern (may be variable) against a serialised predicate key
// The key is stored as `NamedNode::to_string()` (angle-bracket IRI), so the
// comparison must use the same Display formatting — suppressing cmp_owned.
#[allow(clippy::cmp_owned)]
fn predicate_matches(pattern: &StarPredicate, key: &str) -> bool {
    match pattern {
        StarPredicate::Variable(_) => true,
        StarPredicate::NamedNode(n) => n.to_string() == key,
    }
}

/// Match an object pattern against a concrete object value
fn object_matches(pattern: &StarObject, value: &StarObject) -> bool {
    object_matches_object(pattern, value)
}

// ─── Binding result ───────────────────────────────────────────────────────────

/// A variable binding produced by a SPARQL-star pattern match
pub type StarBinding = HashMap<String, StarObject>;

/// Bind variables in `pattern` to values in `triple` and push the result into `out`.
/// Returns `false` if the pattern does not match `triple`.
pub fn bind_pattern(triple: &QuotedTriple, pattern: &QuotedTriple, out: &mut StarBinding) -> bool {
    bind_subject(pattern, triple, out)
        && bind_predicate(pattern, triple, out)
        && bind_object(pattern, triple, out)
}

fn bind_subject(pattern: &QuotedTriple, triple: &QuotedTriple, out: &mut StarBinding) -> bool {
    match &pattern.subject {
        StarSubject::Variable(v) => {
            let obj = star_subject_to_object(&triple.subject);
            out.insert(v.as_str().to_string(), obj);
            true
        }
        StarSubject::NamedNode(pn) => {
            matches!(&triple.subject, StarSubject::NamedNode(vn) if vn == pn)
        }
        StarSubject::BlankNode(pb) => {
            matches!(&triple.subject, StarSubject::BlankNode(vb) if vb == pb)
        }
        StarSubject::Quoted(pq) => {
            if let StarSubject::Quoted(vq) = &triple.subject {
                bind_pattern(vq, pq, out)
            } else {
                false
            }
        }
    }
}

fn bind_predicate(pattern: &QuotedTriple, triple: &QuotedTriple, out: &mut StarBinding) -> bool {
    match &pattern.predicate {
        StarPredicate::Variable(v) => {
            if let StarPredicate::NamedNode(n) = &triple.predicate {
                out.insert(v.as_str().to_string(), StarObject::NamedNode(n.clone()));
            }
            true
        }
        StarPredicate::NamedNode(pn) => {
            matches!(&triple.predicate, StarPredicate::NamedNode(vn) if vn == pn)
        }
    }
}

fn bind_object(pattern: &QuotedTriple, triple: &QuotedTriple, out: &mut StarBinding) -> bool {
    match &pattern.object {
        StarObject::Variable(v) => {
            out.insert(v.as_str().to_string(), triple.object.clone());
            true
        }
        StarObject::NamedNode(pn) => {
            matches!(&triple.object, StarObject::NamedNode(vn) if vn == pn)
        }
        StarObject::BlankNode(pb) => {
            matches!(&triple.object, StarObject::BlankNode(vb) if vb == pb)
        }
        StarObject::Literal(pl) => {
            matches!(&triple.object, StarObject::Literal(vl) if vl == pl)
        }
        StarObject::Quoted(pq) => {
            if let StarObject::Quoted(vq) = &triple.object {
                bind_pattern(vq, pq, out)
            } else {
                false
            }
        }
    }
}

/// Convert a [`StarSubject`] to a [`StarObject`] for binding
fn star_subject_to_object(subject: &StarSubject) -> StarObject {
    match subject {
        StarSubject::NamedNode(n) => StarObject::NamedNode(n.clone()),
        StarSubject::BlankNode(id) => StarObject::BlankNode(id.clone()),
        StarSubject::Variable(v) => StarObject::Variable(v.clone()),
        StarSubject::Quoted(qt) => StarObject::Quoted(qt.clone()),
    }
}

// ─── CONSTRUCT helpers ────────────────────────────────────────────────────────

/// Apply a [`StarBinding`] to a [`QuotedTriple`] template, substituting variables
pub fn instantiate_quoted_triple(
    template: &QuotedTriple,
    binding: &StarBinding,
) -> anyhow::Result<QuotedTriple> {
    let subject = instantiate_subject(&template.subject, binding)?;
    let predicate = instantiate_predicate(&template.predicate, binding)?;
    let object = instantiate_object(&template.object, binding)?;
    Ok(QuotedTriple::new(subject, predicate, object))
}

fn instantiate_subject(s: &StarSubject, binding: &StarBinding) -> anyhow::Result<StarSubject> {
    match s {
        StarSubject::Variable(v) => {
            let val = binding
                .get(v.as_str())
                .ok_or_else(|| anyhow!("unbound variable ?{}", v.as_str()))?;
            // Attempt to convert the bound StarObject back to StarSubject
            object_to_subject(val)
        }
        StarSubject::Quoted(qt) => Ok(StarSubject::Quoted(Box::new(instantiate_quoted_triple(
            qt, binding,
        )?))),
        other => Ok(other.clone()),
    }
}

fn instantiate_predicate(
    p: &StarPredicate,
    binding: &StarBinding,
) -> anyhow::Result<StarPredicate> {
    match p {
        StarPredicate::Variable(v) => {
            let val = binding
                .get(v.as_str())
                .ok_or_else(|| anyhow!("unbound predicate variable ?{}", v.as_str()))?;
            match val {
                StarObject::NamedNode(n) => Ok(StarPredicate::NamedNode(n.clone())),
                other => Err(anyhow!("predicate must be a named node, got {other}")),
            }
        }
        other => Ok(other.clone()),
    }
}

fn instantiate_object(o: &StarObject, binding: &StarBinding) -> anyhow::Result<StarObject> {
    match o {
        StarObject::Variable(v) => binding
            .get(v.as_str())
            .cloned()
            .ok_or_else(|| anyhow!("unbound variable ?{}", v.as_str())),
        StarObject::Quoted(qt) => Ok(StarObject::Quoted(Box::new(instantiate_quoted_triple(
            qt, binding,
        )?))),
        other => Ok(other.clone()),
    }
}

fn object_to_subject(obj: &StarObject) -> anyhow::Result<StarSubject> {
    match obj {
        StarObject::NamedNode(n) => Ok(StarSubject::NamedNode(n.clone())),
        StarObject::BlankNode(id) => Ok(StarSubject::BlankNode(id.clone())),
        StarObject::Quoted(qt) => Ok(StarSubject::Quoted(qt.clone())),
        StarObject::Literal(_) => Err(anyhow!("literals cannot be subjects")),
        StarObject::Variable(v) => Ok(StarSubject::Variable(v.clone())),
    }
}

// ─── SPARQL-star functions ────────────────────────────────────────────────────

/// SPARQL-star built-in functions: `TRIPLE()`, `isTRIPLE()`, `SUBJECT()`,
/// `PREDICATE()`, `OBJECT()`
pub mod sparql_star_builtins {
    use super::*;

    /// `TRIPLE(s, p, o)` — construct a quoted triple from three terms
    pub fn triple_fn(
        subject: StarSubject,
        predicate: StarPredicate,
        object: StarObject,
    ) -> QuotedTriple {
        QuotedTriple::new(subject, predicate, object)
    }

    /// `isTRIPLE(term)` — return `true` if the term is a quoted triple
    pub fn is_triple(obj: &StarObject) -> bool {
        matches!(obj, StarObject::Quoted(_))
    }

    /// `SUBJECT(triple)` — extract the subject of a quoted triple
    pub fn subject_of(qt: &QuotedTriple) -> &StarSubject {
        &qt.subject
    }

    /// `PREDICATE(triple)` — extract the predicate of a quoted triple
    pub fn predicate_of(qt: &QuotedTriple) -> &StarPredicate {
        &qt.predicate
    }

    /// `OBJECT(triple)` — extract the object of a quoted triple
    pub fn object_of(qt: &QuotedTriple) -> &StarObject {
        &qt.object
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    // ── Helpers ───────────────────────────────────────────────────────────

    fn iri(s: &str) -> NamedNode {
        NamedNode::new(s).unwrap()
    }

    fn var(name: &str) -> Variable {
        Variable::new(name).unwrap()
    }

    fn qt(s: &str, p: &str, o: &str) -> QuotedTriple {
        QuotedTriple::new(
            StarSubject::NamedNode(iri(s)),
            StarPredicate::NamedNode(iri(p)),
            StarObject::NamedNode(iri(o)),
        )
    }

    fn qt_lit(s: &str, p: &str, o: &str) -> QuotedTriple {
        QuotedTriple::new(
            StarSubject::NamedNode(iri(s)),
            StarPredicate::NamedNode(iri(p)),
            StarObject::Literal(Literal::new(o.to_string(), None, None)),
        )
    }

    fn ann(p: &str, o: &str) -> Annotation {
        Annotation::new(iri(p), StarObject::NamedNode(iri(o)))
    }

    // ── QuotedTriple construction ─────────────────────────────────────────

    #[test]
    fn test_quoted_triple_new() {
        let qt = qt("http://s", "http://p", "http://o");
        assert_eq!(qt.to_string(), "<< <http://s> <http://p> <http://o> >>");
    }

    #[test]
    fn test_quoted_triple_from_iris() {
        let qt = QuotedTriple::from_iris("http://s", "http://p", "http://o").unwrap();
        assert!(matches!(&qt.subject, StarSubject::NamedNode(_)));
        assert!(matches!(&qt.predicate, StarPredicate::NamedNode(_)));
        assert!(matches!(&qt.object, StarObject::NamedNode(_)));
    }

    #[test]
    fn test_quoted_triple_nesting_depth_simple() {
        let qt = qt("http://s", "http://p", "http://o");
        assert_eq!(qt.nesting_depth(), 1);
    }

    #[test]
    fn test_quoted_triple_nesting_depth_nested() {
        let inner = qt("http://s", "http://p", "http://o");
        let outer = QuotedTriple::new(
            StarSubject::Quoted(Box::new(inner)),
            StarPredicate::NamedNode(iri("http://certainty")),
            StarObject::Literal(Literal::new("0.9".into(), None, None)),
        );
        assert_eq!(outer.nesting_depth(), 2);
    }

    #[test]
    fn test_quoted_triple_triple_nesting() {
        let inner = qt("http://s", "http://p", "http://o");
        let mid = QuotedTriple::new(
            StarSubject::Quoted(Box::new(inner)),
            StarPredicate::NamedNode(iri("http://cert")),
            StarObject::NamedNode(iri("http://v")),
        );
        let outer = QuotedTriple::new(
            StarSubject::Quoted(Box::new(mid)),
            StarPredicate::NamedNode(iri("http://source")),
            StarObject::NamedNode(iri("http://paper")),
        );
        assert_eq!(outer.nesting_depth(), 3);
    }

    // ── is_pattern / variables ────────────────────────────────────────────

    #[test]
    fn test_quoted_triple_no_variables_is_not_pattern() {
        let qt = qt("http://s", "http://p", "http://o");
        assert!(!qt.is_pattern());
        assert!(qt.variables().is_empty());
    }

    #[test]
    fn test_quoted_triple_with_variable_subject() {
        let qt_var = QuotedTriple::new(
            StarSubject::Variable(var("s")),
            StarPredicate::NamedNode(iri("http://p")),
            StarObject::NamedNode(iri("http://o")),
        );
        assert!(qt_var.is_pattern());
        let vars = qt_var.variables();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].as_str(), "s");
    }

    #[test]
    fn test_quoted_triple_with_variable_predicate_and_object() {
        let qt_vars = QuotedTriple::new(
            StarSubject::NamedNode(iri("http://s")),
            StarPredicate::Variable(var("p")),
            StarObject::Variable(var("o")),
        );
        let vars = qt_vars.variables();
        assert_eq!(vars.len(), 2);
    }

    // ── Triple pattern conversion ─────────────────────────────────────────

    #[test]
    fn test_to_triple_pattern() {
        let quoted = qt("http://s", "http://p", "http://o");
        let tp = quoted.to_triple_pattern();
        assert!(matches!(tp.subject, Term::Iri(_)));
        assert!(matches!(tp.predicate, Term::Iri(_)));
        assert!(matches!(tp.object, Term::Iri(_)));
    }

    #[test]
    fn test_from_triple_pattern() {
        let tp = TriplePattern::new(
            Term::Iri(iri("http://s")),
            Term::Iri(iri("http://p")),
            Term::Iri(iri("http://o")),
        );
        let qt = QuotedTriple::from_triple_pattern(&tp).unwrap();
        assert!(matches!(qt.subject, StarSubject::NamedNode(_)));
    }

    #[test]
    fn test_round_trip_triple_pattern() {
        let original = qt("http://s", "http://p", "http://o");
        let tp = original.to_triple_pattern();
        let back = QuotedTriple::from_triple_pattern(&tp).unwrap();
        assert_eq!(original, back);
    }

    // ── StarPredicate / StarSubject / StarObject ──────────────────────────

    #[test]
    fn test_star_subject_from_term_iri() {
        let term = Term::Iri(iri("http://s"));
        let subject = StarSubject::from_term(&term).unwrap();
        assert!(matches!(subject, StarSubject::NamedNode(_)));
    }

    #[test]
    fn test_star_subject_from_term_blank_node() {
        let term = Term::BlankNode("b0".to_string());
        let subject = StarSubject::from_term(&term).unwrap();
        assert!(matches!(subject, StarSubject::BlankNode(_)));
    }

    #[test]
    fn test_star_subject_from_literal_fails() {
        let term = Term::Literal(Literal::new("x".into(), None, None));
        assert!(StarSubject::from_term(&term).is_err());
    }

    #[test]
    fn test_star_object_from_literal() {
        let term = Term::Literal(Literal::new("hello".into(), None, None));
        let obj = StarObject::from_term(&term).unwrap();
        assert!(matches!(obj, StarObject::Literal(_)));
    }

    #[test]
    fn test_star_predicate_from_iri() {
        let term = Term::Iri(iri("http://p"));
        let pred = StarPredicate::from_term(&term).unwrap();
        assert!(matches!(pred, StarPredicate::NamedNode(_)));
    }

    #[test]
    fn test_star_predicate_from_variable() {
        let term = Term::Variable(var("p"));
        let pred = StarPredicate::from_term(&term).unwrap();
        assert!(matches!(pred, StarPredicate::Variable(_)));
    }

    // ── RdfStarStore operations ───────────────────────────────────────────

    #[test]
    fn test_store_assert_and_contains() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        assert!(!store.contains(&triple));
        store.assert_triple(triple.clone());
        assert!(store.contains(&triple));
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn test_store_retract() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.assert_triple(triple.clone());
        assert!(store.retract_triple(&triple));
        assert!(!store.contains(&triple));
        assert_eq!(store.len(), 0);
    }

    #[test]
    fn test_store_add_annotation() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        let pred = iri("http://certainty");
        store.add_annotation(
            &triple,
            &pred,
            StarObject::Literal(Literal::new("0.9".into(), None, None)),
        );
        let entry = store.annotations(&triple).unwrap();
        assert!(entry.annotation(&pred).is_some());
    }

    #[test]
    fn test_store_remove_annotation() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        let pred = iri("http://certainty");
        store.add_annotation(&triple, &pred, StarObject::NamedNode(iri("http://high")));
        assert!(store.remove_annotation(&triple, &pred));
        let entry = store.annotations(&triple).unwrap();
        assert!(entry.annotation(&pred).is_none());
    }

    #[test]
    fn test_store_multiple_triples() {
        let mut store = RdfStarStore::new();
        store.assert_triple(qt("http://s1", "http://p", "http://o1"));
        store.assert_triple(qt("http://s2", "http://p", "http://o2"));
        assert_eq!(store.len(), 2);
    }

    // ── StarOperator ──────────────────────────────────────────────────────

    #[test]
    fn test_assert_quoted_operator() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.apply_operator(StarOperator::AssertQuoted {
            triple: triple.clone(),
        });
        assert!(store.contains(&triple));
    }

    #[test]
    fn test_retract_quoted_operator() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.assert_triple(triple.clone());
        store.apply_operator(StarOperator::RetractQuoted {
            triple: triple.clone(),
        });
        assert!(!store.contains(&triple));
    }

    #[test]
    fn test_add_annotation_operator() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.apply_operator(StarOperator::AddAnnotation {
            triple: triple.clone(),
            annotations: vec![ann("http://cert", "http://high")],
        });
        assert!(store.annotations(&triple).is_some());
    }

    #[test]
    fn test_remove_annotation_operator() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        let pred = iri("http://cert");
        store.add_annotation(&triple, &pred, StarObject::NamedNode(iri("http://high")));
        store.apply_operator(StarOperator::RemoveAnnotation {
            triple: triple.clone(),
            predicate: pred.clone(),
        });
        let entry = store.annotations(&triple).unwrap();
        assert!(entry.annotation(&pred).is_none());
    }

    // ── FindAnnotations / pattern matching ───────────────────────────────

    #[test]
    fn test_find_annotations_exact_match() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        let cert = iri("http://certainty");
        store.add_annotation(&triple, &cert, StarObject::NamedNode(iri("http://high")));

        let pattern = StarPattern::new(
            triple.clone(),
            StarPredicate::NamedNode(cert),
            StarObject::NamedNode(iri("http://high")),
        );
        let results = store.find_annotations(&pattern);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_find_annotations_variable_predicate() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.add_annotation(
            &triple,
            &iri("http://cert"),
            StarObject::NamedNode(iri("http://high")),
        );

        let pattern = StarPattern::new(
            triple.clone(),
            StarPredicate::Variable(var("pred")),
            StarObject::Variable(var("obj")),
        );
        let results = store.find_annotations(&pattern);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_find_annotations_no_match() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.add_annotation(
            &triple,
            &iri("http://cert"),
            StarObject::NamedNode(iri("http://high")),
        );

        let other_triple = qt("http://other", "http://p", "http://o");
        let pattern = StarPattern::new(
            other_triple,
            StarPredicate::Variable(var("pred")),
            StarObject::Variable(var("obj")),
        );
        let results = store.find_annotations(&pattern);
        assert!(results.is_empty());
    }

    // ── Pattern matching / binding ─────────────────────────────────────

    #[test]
    fn test_bind_pattern_all_variables() {
        let triple = qt("http://s", "http://p", "http://o");
        let pattern = QuotedTriple::new(
            StarSubject::Variable(var("s")),
            StarPredicate::Variable(var("p")),
            StarObject::Variable(var("o")),
        );
        let mut binding = StarBinding::new();
        assert!(bind_pattern(&triple, &pattern, &mut binding));
        assert!(binding.contains_key("s"));
        assert!(binding.contains_key("p"));
        assert!(binding.contains_key("o"));
    }

    #[test]
    fn test_bind_pattern_partial_variables() {
        let triple = qt("http://s", "http://p", "http://o");
        let pattern = QuotedTriple::new(
            StarSubject::NamedNode(iri("http://s")),
            StarPredicate::Variable(var("p")),
            StarObject::Variable(var("o")),
        );
        let mut binding = StarBinding::new();
        assert!(bind_pattern(&triple, &pattern, &mut binding));
        assert!(binding.contains_key("p"));
        assert!(binding.contains_key("o"));
    }

    #[test]
    fn test_bind_pattern_mismatch() {
        let triple = qt("http://s", "http://p", "http://o");
        let pattern = QuotedTriple::new(
            StarSubject::NamedNode(iri("http://DIFFERENT")),
            StarPredicate::Variable(var("p")),
            StarObject::Variable(var("o")),
        );
        let mut binding = StarBinding::new();
        assert!(!bind_pattern(&triple, &pattern, &mut binding));
    }

    // ── CONSTRUCT (instantiation) ─────────────────────────────────────────

    #[test]
    fn test_instantiate_quoted_triple() {
        let template = QuotedTriple::new(
            StarSubject::Variable(var("s")),
            StarPredicate::NamedNode(iri("http://p")),
            StarObject::Variable(var("o")),
        );
        let mut binding = StarBinding::new();
        binding.insert("s".to_string(), StarObject::NamedNode(iri("http://alice")));
        binding.insert(
            "o".to_string(),
            StarObject::Literal(Literal::new("42".into(), None, None)),
        );

        let result = instantiate_quoted_triple(&template, &binding).unwrap();
        assert!(
            matches!(result.subject, StarSubject::NamedNode(n) if n.to_string().contains("alice"))
        );
        assert!(matches!(result.object, StarObject::Literal(_)));
    }

    #[test]
    fn test_instantiate_unbound_variable_fails() {
        let template = QuotedTriple::new(
            StarSubject::Variable(var("missing")),
            StarPredicate::NamedNode(iri("http://p")),
            StarObject::NamedNode(iri("http://o")),
        );
        let binding = StarBinding::new();
        assert!(instantiate_quoted_triple(&template, &binding).is_err());
    }

    // ── SPARQL-star builtins ─────────────────────────────────────────────

    #[test]
    fn test_is_triple_function() {
        let obj = StarObject::Quoted(Box::new(qt("http://s", "http://p", "http://o")));
        assert!(is_triple(&obj));
        let not_triple = StarObject::NamedNode(iri("http://x"));
        assert!(!is_triple(&not_triple));
    }

    #[test]
    fn test_subject_of() {
        let triple = qt("http://alice", "http://p", "http://o");
        let s = subject_of(&triple);
        assert!(matches!(s, StarSubject::NamedNode(n) if n.to_string().contains("alice")));
    }

    #[test]
    fn test_predicate_of() {
        let triple = qt("http://s", "http://predicate", "http://o");
        let p = predicate_of(&triple);
        assert!(matches!(p, StarPredicate::NamedNode(n) if n.to_string().contains("predicate")));
    }

    #[test]
    fn test_object_of() {
        let triple = qt("http://s", "http://p", "http://target");
        let o = object_of(&triple);
        assert!(matches!(o, StarObject::NamedNode(n) if n.to_string().contains("target")));
    }

    #[test]
    fn test_triple_fn_builtin() {
        let s = StarSubject::NamedNode(iri("http://s"));
        let p = StarPredicate::NamedNode(iri("http://p"));
        let o = StarObject::NamedNode(iri("http://o"));
        let qt = triple_fn(s, p, o);
        assert_eq!(qt.nesting_depth(), 1);
    }

    // ── Mixed standard + star patterns ───────────────────────────────────

    #[test]
    fn test_mixed_star_and_standard_patterns() {
        let mut store = RdfStarStore::new();
        // Add a plain triple annotation
        let t1 = qt("http://alice", "http://knows", "http://bob");
        store.add_annotation(
            &t1,
            &iri("http://since"),
            StarObject::Literal(Literal::new("2020".into(), None, None)),
        );
        // Add a second triple with different annotation
        let t2 = qt("http://bob", "http://knows", "http://carol");
        store.add_annotation(
            &t2,
            &iri("http://since"),
            StarObject::Literal(Literal::new("2021".into(), None, None)),
        );

        // Find all "knows" triples with "since" annotation
        let pattern_triple = QuotedTriple::new(
            StarSubject::Variable(var("s")),
            StarPredicate::NamedNode(iri("http://knows")),
            StarObject::Variable(var("o")),
        );
        let pattern = StarPattern::new(
            pattern_triple,
            StarPredicate::NamedNode(iri("http://since")),
            StarObject::Variable(var("when")),
        );
        let results = store.find_annotations(&pattern);
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_star_pattern_variables() {
        let pattern = StarPattern::new(
            QuotedTriple::new(
                StarSubject::Variable(var("s")),
                StarPredicate::Variable(var("p")),
                StarObject::Variable(var("o")),
            ),
            StarPredicate::Variable(var("ap")),
            StarObject::Variable(var("ao")),
        );
        let vars = pattern.variables();
        assert_eq!(vars.len(), 5);
    }

    // ── Display / formatting ──────────────────────────────────────────────

    #[test]
    fn test_star_operator_display() {
        let triple = qt("http://s", "http://p", "http://o");
        let op = StarOperator::AssertQuoted { triple };
        assert!(op.to_string().contains("AssertQuoted"));
    }

    #[test]
    fn test_quoted_triple_display_nested() {
        let inner = qt("http://s", "http://p", "http://o");
        let outer = QuotedTriple::new(
            StarSubject::Quoted(Box::new(inner)),
            StarPredicate::NamedNode(iri("http://cert")),
            StarObject::Literal(Literal::new("high".into(), None, None)),
        );
        let s = outer.to_string();
        assert!(s.contains("<<"));
        // Nested << inside outer <<
        assert!(s.matches("<<").count() >= 2);
    }

    // ── Annotation store operations ───────────────────────────────────────

    #[test]
    fn test_multiple_annotations_on_same_triple() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.add_annotation(
            &triple,
            &iri("http://cert"),
            StarObject::NamedNode(iri("http://high")),
        );
        store.add_annotation(
            &triple,
            &iri("http://source"),
            StarObject::NamedNode(iri("http://paper1")),
        );

        let entry = store.annotations(&triple).unwrap();
        assert_eq!(entry.annotations.len(), 2);
    }

    #[test]
    fn test_annotation_overwrite() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        let pred = iri("http://cert");
        store.add_annotation(&triple, &pred, StarObject::NamedNode(iri("http://low")));
        store.add_annotation(&triple, &pred, StarObject::NamedNode(iri("http://high")));

        let entry = store.annotations(&triple).unwrap();
        // Overwritten — still just 1 annotation for this predicate
        assert_eq!(entry.annotations.len(), 1);
        if let Some(StarObject::NamedNode(n)) = entry.annotation(&pred) {
            assert!(n.to_string().contains("high"));
        } else {
            panic!("expected NamedNode annotation");
        }
    }

    #[test]
    fn test_store_iter() {
        let mut store = RdfStarStore::new();
        store.assert_triple(qt("http://s1", "http://p", "http://o1"));
        store.assert_triple(qt("http://s2", "http://p", "http://o2"));
        assert_eq!(store.iter().count(), 2);
    }

    #[test]
    fn test_find_annotations_with_literal_object_value() {
        let mut store = RdfStarStore::new();
        let triple = qt_lit("http://s", "http://p", "42");
        store.add_annotation(
            &triple,
            &iri("http://source"),
            StarObject::NamedNode(iri("http://db")),
        );
        let pattern = StarPattern::new(
            triple.clone(),
            StarPredicate::Variable(var("pred")),
            StarObject::Variable(var("obj")),
        );
        let results = store.find_annotations(&pattern);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_apply_operator_find_annotations() {
        let mut store = RdfStarStore::new();
        let triple = qt("http://s", "http://p", "http://o");
        store.add_annotation(
            &triple,
            &iri("http://cert"),
            StarObject::NamedNode(iri("http://high")),
        );

        let pattern = StarPattern::new(
            triple.clone(),
            StarPredicate::NamedNode(iri("http://cert")),
            StarObject::Variable(var("v")),
        );
        let results = store.apply_operator(StarOperator::FindAnnotations { pattern });
        assert_eq!(results.len(), 1);
    }
}