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
//! # HDT-star Format Support
//!
//! Efficient binary serialization for RDF-star data using Header-Dictionary-Triples (HDT) format
//! with extensions for quoted triples.
//!
//! HDT-star provides:
//! - **Compact Storage**: Dictionary-based compression for repeated terms
//! - **Fast Queries**: Bitmap-indexed structure for O(log n) lookups
//! - **Memory Mapping**: Supports datasets larger than RAM
//! - **RDF-star Extension**: Native quoted triple support with nested dictionary entries
//!
//! ## Overview
//!
//! HDT (Header-Dictionary-Triples) is a compact data structure and binary serialization format
//! for RDF. This module extends HDT to support RDF-star quoted triples:
//!
//! 1. **Header**: Metadata about the dataset (format, statistics, configuration)
//! 2. **Dictionary**: Compressed string dictionary for subjects, predicates, objects
//!    - Extended with a Quoted Triple Dictionary for nested triples
//! 3. **Triples**: Bitmap-based triple storage with SPO/POS/OSP indices
//!
//! ## Example
//!
//! ```rust,ignore
//! use oxirs_star::hdt_star::{HdtStarBuilder, HdtStarReader, HdtStarConfig};
//! use oxirs_star::{StarTriple, StarTerm, StarStore};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Build HDT-star from a store
//! let mut store = StarStore::new();
//! // ... populate store with data
//!
//! let config = HdtStarConfig::default();
//! let mut builder = HdtStarBuilder::new(config);
//! builder.add_store(&store)?;
//!
//! // Write to file
//! let mut file = std::fs::File::create("output.hdt")?;
//! builder.write(&mut file)?;
//!
//! // Read HDT-star file
//! let reader = HdtStarReader::open("output.hdt")?;
//! for triple in reader.iter_triples() {
//!     println!("{}", triple);
//! }
//! # Ok(())
//! # }
//! ```

use crate::{StarError, StarResult, StarStore, StarTerm, StarTriple};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
use tracing::{info, instrument, warn};

// Import SciRS2 components (SCIRS2 POLICY)
use scirs2_core::profiling::Profiler;

// SIMD-accelerated compression module (v0.4.0 Phase 1)
#[path = "hdt_star/simd_compression.rs"]
pub mod simd_compression;

pub use simd_compression::{SimdBitmapOps, SimdCompressionAnalyzer, SimdStringComparator};

/// HDT-star file format version
pub const HDT_STAR_VERSION: u8 = 1;

/// Magic bytes for HDT-star format identification
pub const HDT_STAR_MAGIC: [u8; 8] = *b"HDT*RDF\0";

/// Configuration for HDT-star encoding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HdtStarConfig {
    /// Enable dictionary compression
    pub enable_compression: bool,
    /// Compression level (1-9, higher = smaller but slower)
    pub compression_level: u8,
    /// Enable quoted triple dictionary
    pub enable_quoted_dict: bool,
    /// Maximum quoted triple nesting depth
    pub max_nesting_depth: usize,
    /// Block size for bitmap indices (power of 2)
    pub block_size: usize,
    /// Enable memory mapping for large files
    pub enable_mmap: bool,
    /// Index strategy: SPO, POS, OSP, or ALL
    pub index_strategy: IndexStrategy,
}

impl Default for HdtStarConfig {
    fn default() -> Self {
        Self {
            enable_compression: true,
            compression_level: 6,
            enable_quoted_dict: true,
            max_nesting_depth: 10,
            block_size: 1024,
            enable_mmap: true,
            index_strategy: IndexStrategy::All,
        }
    }
}

/// Index strategy for triple storage
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IndexStrategy {
    /// Subject-Predicate-Object index only
    Spo,
    /// Predicate-Object-Subject index only
    Pos,
    /// Object-Subject-Predicate index only
    Osp,
    /// All three indices (larger but faster queries)
    All,
}

/// HDT-star header section
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HdtStarHeader {
    /// Format version
    pub version: u8,
    /// Base URI for the dataset
    pub base_uri: Option<String>,
    /// Total number of triples
    pub triple_count: u64,
    /// Number of unique subjects
    pub subject_count: u64,
    /// Number of unique predicates
    pub predicate_count: u64,
    /// Number of unique objects
    pub object_count: u64,
    /// Number of quoted triples
    pub quoted_triple_count: u64,
    /// Maximum nesting depth encountered
    pub max_nesting_depth: u8,
    /// Configuration used for encoding
    pub config: HdtStarConfig,
    /// Custom metadata
    pub metadata: HashMap<String, String>,
    /// Creation timestamp (Unix epoch)
    pub created_at: u64,
}

impl HdtStarHeader {
    /// Create a new header
    pub fn new(config: HdtStarConfig) -> Self {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        Self {
            version: HDT_STAR_VERSION,
            base_uri: None,
            triple_count: 0,
            subject_count: 0,
            predicate_count: 0,
            object_count: 0,
            quoted_triple_count: 0,
            max_nesting_depth: 0,
            config,
            metadata: HashMap::new(),
            created_at: timestamp,
        }
    }

    /// Serialize header to bytes
    pub fn to_bytes(&self) -> StarResult<Vec<u8>> {
        let encoded = oxicode::serde::encode_to_vec(self, oxicode::config::standard())
            .map_err(|e| StarError::serialization_error(format!("Header encoding failed: {e}")))?;
        Ok(encoded)
    }

    /// Deserialize header from bytes
    pub fn from_bytes(bytes: &[u8]) -> StarResult<Self> {
        let (decoded, _) = oxicode::serde::decode_from_slice(bytes, oxicode::config::standard())
            .map_err(|e| StarError::parse_error(format!("Header decoding failed: {e}")))?;
        Ok(decoded)
    }
}

/// Dictionary entry type
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DictionaryEntry {
    /// IRI entry
    Iri(String),
    /// Literal entry with optional datatype and language
    Literal {
        value: String,
        datatype: Option<String>,
        language: Option<String>,
    },
    /// Blank node entry
    BlankNode(String),
    /// Variable entry (for patterns)
    Variable(String),
    /// Quoted triple reference (index into quoted triple dictionary)
    QuotedTripleRef(u64),
}

impl DictionaryEntry {
    /// Convert from StarTerm
    pub fn from_star_term(term: &StarTerm) -> Self {
        match term {
            StarTerm::NamedNode(nn) => DictionaryEntry::Iri(nn.iri.clone()),
            StarTerm::Literal(lit) => DictionaryEntry::Literal {
                value: lit.value.clone(),
                datatype: lit.datatype.as_ref().map(|d| d.iri.clone()),
                language: lit.language.clone(),
            },
            StarTerm::BlankNode(bn) => DictionaryEntry::BlankNode(bn.id.clone()),
            StarTerm::Variable(var) => DictionaryEntry::Variable(var.name.clone()),
            StarTerm::QuotedTriple(_) => {
                // This is a placeholder; actual index is set during encoding
                DictionaryEntry::QuotedTripleRef(0)
            }
        }
    }

    /// Convert to StarTerm (except QuotedTripleRef which needs special handling)
    pub fn to_star_term(&self) -> StarResult<StarTerm> {
        match self {
            DictionaryEntry::Iri(iri) => StarTerm::iri(iri),
            DictionaryEntry::Literal {
                value,
                datatype,
                language,
            } => {
                let term = StarTerm::literal(value)?;
                // Apply datatype or language if present
                if let Some(lang) = language {
                    if let StarTerm::Literal(lit) = &term {
                        let mut new_lit = lit.clone();
                        new_lit.language = Some(lang.clone());
                        return Ok(StarTerm::Literal(new_lit));
                    }
                }
                if let Some(dt) = datatype {
                    if let StarTerm::Literal(lit) = &term {
                        let mut new_lit = lit.clone();
                        new_lit.datatype = Some(crate::model::NamedNode { iri: dt.clone() });
                        return Ok(StarTerm::Literal(new_lit));
                    }
                }
                Ok(term)
            }
            DictionaryEntry::BlankNode(bn) => Ok(StarTerm::BlankNode(crate::model::BlankNode {
                id: bn.clone(),
            })),
            DictionaryEntry::Variable(var) => Ok(StarTerm::Variable(crate::model::Variable {
                name: var.clone(),
            })),
            DictionaryEntry::QuotedTripleRef(_) => Err(StarError::invalid_term_type(
                "Cannot convert QuotedTripleRef directly to StarTerm",
            )),
        }
    }
}

/// Dictionary section for term compression
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HdtStarDictionary {
    /// Subject dictionary (strings to IDs)
    subjects: HashMap<DictionaryEntry, u64>,
    /// Predicate dictionary
    predicates: HashMap<DictionaryEntry, u64>,
    /// Object dictionary
    objects: HashMap<DictionaryEntry, u64>,
    /// Shared dictionary (terms appearing as both subject and object)
    shared: HashMap<DictionaryEntry, u64>,
    /// Quoted triple dictionary
    quoted_triples: HashMap<u64, EncodedTriple>,
    /// Reverse lookup for subjects
    subject_reverse: Vec<DictionaryEntry>,
    /// Reverse lookup for predicates
    predicate_reverse: Vec<DictionaryEntry>,
    /// Reverse lookup for objects
    object_reverse: Vec<DictionaryEntry>,
    /// Reverse lookup for quoted triples
    quoted_triple_reverse: Vec<EncodedTriple>,
    /// Next available ID for subjects
    next_subject_id: u64,
    /// Next available ID for predicates
    next_predicate_id: u64,
    /// Next available ID for objects
    next_object_id: u64,
    /// Next available ID for quoted triples
    next_quoted_id: u64,
}

impl HdtStarDictionary {
    /// Create a new empty dictionary
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a subject term and return its ID
    pub fn add_subject(&mut self, entry: DictionaryEntry) -> u64 {
        if let Some(&id) = self.subjects.get(&entry) {
            return id;
        }
        let id = self.next_subject_id;
        self.next_subject_id += 1;
        self.subjects.insert(entry.clone(), id);
        self.subject_reverse.push(entry);
        id
    }

    /// Add a predicate term and return its ID
    pub fn add_predicate(&mut self, entry: DictionaryEntry) -> u64 {
        if let Some(&id) = self.predicates.get(&entry) {
            return id;
        }
        let id = self.next_predicate_id;
        self.next_predicate_id += 1;
        self.predicates.insert(entry.clone(), id);
        self.predicate_reverse.push(entry);
        id
    }

    /// Add an object term and return its ID
    pub fn add_object(&mut self, entry: DictionaryEntry) -> u64 {
        if let Some(&id) = self.objects.get(&entry) {
            return id;
        }
        let id = self.next_object_id;
        self.next_object_id += 1;
        self.objects.insert(entry.clone(), id);
        self.object_reverse.push(entry);
        id
    }

    /// Add a quoted triple and return its ID
    pub fn add_quoted_triple(&mut self, triple: EncodedTriple) -> u64 {
        // Check if we already have this exact encoded triple
        for (id, existing) in &self.quoted_triples {
            if existing == &triple {
                return *id;
            }
        }
        let id = self.next_quoted_id;
        self.next_quoted_id += 1;
        self.quoted_triples.insert(id, triple.clone());
        self.quoted_triple_reverse.push(triple);
        id
    }

    /// Get subject by ID
    pub fn get_subject(&self, id: u64) -> Option<&DictionaryEntry> {
        self.subject_reverse.get(id as usize)
    }

    /// Get predicate by ID
    pub fn get_predicate(&self, id: u64) -> Option<&DictionaryEntry> {
        self.predicate_reverse.get(id as usize)
    }

    /// Get object by ID
    pub fn get_object(&self, id: u64) -> Option<&DictionaryEntry> {
        self.object_reverse.get(id as usize)
    }

    /// Get quoted triple by ID
    pub fn get_quoted_triple(&self, id: u64) -> Option<&EncodedTriple> {
        self.quoted_triples.get(&id)
    }

    /// Get dictionary statistics
    pub fn statistics(&self) -> DictionaryStats {
        DictionaryStats {
            subject_count: self.subjects.len(),
            predicate_count: self.predicates.len(),
            object_count: self.objects.len(),
            shared_count: self.shared.len(),
            quoted_triple_count: self.quoted_triples.len(),
        }
    }

    /// Serialize dictionary to bytes
    pub fn to_bytes(&self) -> StarResult<Vec<u8>> {
        let encoded =
            oxicode::serde::encode_to_vec(self, oxicode::config::standard()).map_err(|e| {
                StarError::serialization_error(format!("Dictionary encoding failed: {e}"))
            })?;
        Ok(encoded)
    }

    /// Deserialize dictionary from bytes
    pub fn from_bytes(bytes: &[u8]) -> StarResult<Self> {
        let (decoded, _) = oxicode::serde::decode_from_slice(bytes, oxicode::config::standard())
            .map_err(|e| StarError::parse_error(format!("Dictionary decoding failed: {e}")))?;
        Ok(decoded)
    }
}

/// Dictionary statistics
#[derive(Debug, Clone, Default)]
pub struct DictionaryStats {
    pub subject_count: usize,
    pub predicate_count: usize,
    pub object_count: usize,
    pub shared_count: usize,
    pub quoted_triple_count: usize,
}

/// Encoded triple with dictionary IDs
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EncodedTriple {
    /// Subject ID (or quoted triple marker + ID)
    pub subject: EncodedTerm,
    /// Predicate ID
    pub predicate: u64,
    /// Object ID (or quoted triple marker + ID)
    pub object: EncodedTerm,
}

/// Encoded term that can be a regular ID or a quoted triple reference
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
pub enum EncodedTerm {
    /// Regular dictionary ID
    Regular(u64),
    /// Quoted triple ID
    QuotedTriple(u64),
}

/// Triple section with bitmap-based storage
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HdtStarTriples {
    /// SPO-ordered triples for efficient subject lookups
    spo_index: Vec<EncodedTriple>,
    /// POS-ordered triples for efficient predicate lookups
    pos_index: Vec<EncodedTriple>,
    /// OSP-ordered triples for efficient object lookups
    osp_index: Vec<EncodedTriple>,
    /// Bitmap for efficient existence checks
    bitmap: Vec<u64>,
    /// Block size for bitmap operations
    block_size: usize,
}

impl HdtStarTriples {
    /// Create new triple section
    pub fn new(block_size: usize) -> Self {
        Self {
            spo_index: Vec::new(),
            pos_index: Vec::new(),
            osp_index: Vec::new(),
            bitmap: Vec::new(),
            block_size,
        }
    }

    /// Add an encoded triple
    pub fn add(&mut self, triple: EncodedTriple) {
        self.spo_index.push(triple.clone());
        self.pos_index.push(triple.clone());
        self.osp_index.push(triple);
    }

    /// Sort and build indices
    pub fn build_indices(&mut self, strategy: IndexStrategy) {
        // Sort SPO index
        if matches!(strategy, IndexStrategy::Spo | IndexStrategy::All) {
            self.spo_index.sort_by(|a, b| {
                (&a.subject, a.predicate, &a.object).cmp(&(&b.subject, b.predicate, &b.object))
            });
        }

        // Sort POS index
        if matches!(strategy, IndexStrategy::Pos | IndexStrategy::All) {
            self.pos_index.sort_by(|a, b| {
                (a.predicate, &a.object, &a.subject).cmp(&(b.predicate, &b.object, &b.subject))
            });
        }

        // Sort OSP index
        if matches!(strategy, IndexStrategy::Osp | IndexStrategy::All) {
            self.osp_index.sort_by(|a, b| {
                (&a.object, &a.subject, a.predicate).cmp(&(&b.object, &b.subject, b.predicate))
            });
        }

        // Build bitmap
        self.build_bitmap();
    }

    /// Build bitmap for fast existence checks
    fn build_bitmap(&mut self) {
        let num_blocks = (self.spo_index.len() + 63) / 64;
        self.bitmap = vec![0u64; num_blocks];

        // Set bits for all existing triples
        for i in 0..self.spo_index.len() {
            let block = i / 64;
            let bit = i % 64;
            if block < self.bitmap.len() {
                self.bitmap[block] |= 1u64 << bit;
            }
        }
    }

    /// Get triple count
    pub fn len(&self) -> usize {
        self.spo_index.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.spo_index.is_empty()
    }

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

    /// Serialize triples to bytes
    pub fn to_bytes(&self) -> StarResult<Vec<u8>> {
        let encoded = oxicode::serde::encode_to_vec(self, oxicode::config::standard())
            .map_err(|e| StarError::serialization_error(format!("Triples encoding failed: {e}")))?;
        Ok(encoded)
    }

    /// Deserialize triples from bytes
    pub fn from_bytes(bytes: &[u8]) -> StarResult<Self> {
        let (decoded, _) = oxicode::serde::decode_from_slice(bytes, oxicode::config::standard())
            .map_err(|e| StarError::parse_error(format!("Triples decoding failed: {e}")))?;
        Ok(decoded)
    }
}

/// HDT-star builder for creating HDT files
pub struct HdtStarBuilder {
    config: HdtStarConfig,
    header: HdtStarHeader,
    dictionary: HdtStarDictionary,
    triples: HdtStarTriples,
    #[allow(dead_code)]
    profiler: Profiler,
}

impl HdtStarBuilder {
    /// Create a new HDT-star builder
    pub fn new(config: HdtStarConfig) -> Self {
        let header = HdtStarHeader::new(config.clone());
        let triples = HdtStarTriples::new(config.block_size);

        Self {
            config,
            header,
            dictionary: HdtStarDictionary::new(),
            triples,
            profiler: Profiler::new(),
        }
    }

    /// Set the base URI for the dataset
    pub fn set_base_uri(&mut self, base_uri: impl Into<String>) {
        self.header.base_uri = Some(base_uri.into());
    }

    /// Add custom metadata
    pub fn add_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.header.metadata.insert(key.into(), value.into());
    }

    /// Add a StarStore to the builder
    #[instrument(skip(self, store), fields(store_size = store.len()))]
    pub fn add_store(&mut self, store: &StarStore) -> StarResult<()> {
        info!(
            "Adding store with {} triples to HDT-star builder",
            store.len()
        );

        for triple in store.iter() {
            self.add_triple(&triple)?;
        }

        Ok(())
    }

    /// Add a single triple
    pub fn add_triple(&mut self, triple: &StarTriple) -> StarResult<()> {
        let encoded = self.encode_triple(triple)?;
        self.triples.add(encoded);
        self.header.triple_count += 1;
        Ok(())
    }

    /// Encode a StarTriple to an EncodedTriple
    fn encode_triple(&mut self, triple: &StarTriple) -> StarResult<EncodedTriple> {
        let subject = self.encode_term(&triple.subject, TermPosition::Subject)?;
        let predicate = match &triple.predicate {
            StarTerm::NamedNode(_) => {
                let entry = DictionaryEntry::from_star_term(&triple.predicate);
                self.dictionary.add_predicate(entry)
            }
            _ => {
                return Err(StarError::invalid_term_type(
                    "Predicate must be a NamedNode",
                ))
            }
        };
        let object = self.encode_term(&triple.object, TermPosition::Object)?;

        Ok(EncodedTriple {
            subject,
            predicate,
            object,
        })
    }

    /// Encode a StarTerm to an EncodedTerm
    fn encode_term(&mut self, term: &StarTerm, position: TermPosition) -> StarResult<EncodedTerm> {
        match term {
            StarTerm::QuotedTriple(qt) => {
                // Recursively encode the quoted triple
                let encoded_qt = self.encode_triple(qt)?;
                let qt_id = self.dictionary.add_quoted_triple(encoded_qt);
                self.header.quoted_triple_count += 1;
                Ok(EncodedTerm::QuotedTriple(qt_id))
            }
            _ => {
                let entry = DictionaryEntry::from_star_term(term);
                let id = match position {
                    TermPosition::Subject => self.dictionary.add_subject(entry),
                    TermPosition::Object => self.dictionary.add_object(entry),
                };
                Ok(EncodedTerm::Regular(id))
            }
        }
    }

    /// Build and finalize the HDT structure
    #[instrument(skip(self))]
    pub fn build(&mut self) -> StarResult<()> {
        info!("Building HDT-star indices...");

        // Build triple indices
        self.triples.build_indices(self.config.index_strategy);

        // Update header statistics
        let dict_stats = self.dictionary.statistics();
        self.header.subject_count = dict_stats.subject_count as u64;
        self.header.predicate_count = dict_stats.predicate_count as u64;
        self.header.object_count = dict_stats.object_count as u64;

        info!(
            "HDT-star built: {} triples, {} subjects, {} predicates, {} objects, {} quoted",
            self.header.triple_count,
            self.header.subject_count,
            self.header.predicate_count,
            self.header.object_count,
            self.header.quoted_triple_count
        );

        Ok(())
    }

    /// Write HDT-star to a writer
    #[instrument(skip(self, writer))]
    pub fn write<W: Write>(&mut self, writer: &mut W) -> StarResult<()> {
        self.build()?;

        info!("Writing HDT-star to output...");

        // Write magic bytes
        writer.write_all(&HDT_STAR_MAGIC).map_err(|e| {
            StarError::serialization_error(format!("Failed to write magic bytes: {e}"))
        })?;

        // Write header
        let header_bytes = self.header.to_bytes()?;
        let header_len = (header_bytes.len() as u64).to_le_bytes();
        writer.write_all(&header_len).map_err(|e| {
            StarError::serialization_error(format!("Failed to write header length: {e}"))
        })?;
        writer
            .write_all(&header_bytes)
            .map_err(|e| StarError::serialization_error(format!("Failed to write header: {e}")))?;

        // Write dictionary
        let dict_bytes = self.dictionary.to_bytes()?;
        let dict_len = (dict_bytes.len() as u64).to_le_bytes();
        writer.write_all(&dict_len).map_err(|e| {
            StarError::serialization_error(format!("Failed to write dictionary length: {e}"))
        })?;

        // Optionally compress dictionary
        if self.config.enable_compression {
            let compressed = compress_data(&dict_bytes, self.config.compression_level)?;
            let compressed_len = (compressed.len() as u64).to_le_bytes();
            writer.write_all(&compressed_len).map_err(|e| {
                StarError::serialization_error(format!("Failed to write compressed length: {e}"))
            })?;
            writer.write_all(&compressed).map_err(|e| {
                StarError::serialization_error(format!("Failed to write dictionary: {e}"))
            })?;
        } else {
            writer.write_all(&dict_bytes).map_err(|e| {
                StarError::serialization_error(format!("Failed to write dictionary: {e}"))
            })?;
        }

        // Write triples
        let triples_bytes = self.triples.to_bytes()?;
        let triples_len = (triples_bytes.len() as u64).to_le_bytes();
        writer.write_all(&triples_len).map_err(|e| {
            StarError::serialization_error(format!("Failed to write triples length: {e}"))
        })?;

        if self.config.enable_compression {
            let compressed = compress_data(&triples_bytes, self.config.compression_level)?;
            let compressed_len = (compressed.len() as u64).to_le_bytes();
            writer.write_all(&compressed_len).map_err(|e| {
                StarError::serialization_error(format!("Failed to write compressed length: {e}"))
            })?;
            writer.write_all(&compressed).map_err(|e| {
                StarError::serialization_error(format!("Failed to write triples: {e}"))
            })?;
        } else {
            writer.write_all(&triples_bytes).map_err(|e| {
                StarError::serialization_error(format!("Failed to write triples: {e}"))
            })?;
        }

        info!("HDT-star write complete");
        Ok(())
    }

    /// Get build statistics
    pub fn statistics(&self) -> HdtStarBuildStats {
        let dict_stats = self.dictionary.statistics();
        HdtStarBuildStats {
            triple_count: self.header.triple_count,
            quoted_triple_count: self.header.quoted_triple_count,
            subject_count: dict_stats.subject_count as u64,
            predicate_count: dict_stats.predicate_count as u64,
            object_count: dict_stats.object_count as u64,
            build_time_us: 0, // Profiler doesn't expose total_time_us
        }
    }
}

/// Term position for dictionary placement
#[derive(Debug, Clone, Copy)]
enum TermPosition {
    Subject,
    Object,
}

/// HDT-star build statistics
#[derive(Debug, Clone)]
pub struct HdtStarBuildStats {
    pub triple_count: u64,
    pub quoted_triple_count: u64,
    pub subject_count: u64,
    pub predicate_count: u64,
    pub object_count: u64,
    pub build_time_us: u64,
}

/// HDT-star reader for loading and querying HDT files
pub struct HdtStarReader {
    header: HdtStarHeader,
    dictionary: HdtStarDictionary,
    triples: HdtStarTriples,
}

impl HdtStarReader {
    /// Open an HDT-star file
    #[instrument(skip(path))]
    pub fn open<P: AsRef<std::path::Path>>(path: P) -> StarResult<Self> {
        let mut file = std::fs::File::open(path.as_ref())
            .map_err(|e| StarError::resource_error(format!("Failed to open file: {e}")))?;

        Self::read(&mut file)
    }

    /// Read HDT-star from a reader
    pub fn read<R: Read>(reader: &mut R) -> StarResult<Self> {
        // Read and verify magic bytes
        let mut magic = [0u8; 8];
        reader
            .read_exact(&mut magic)
            .map_err(|e| StarError::parse_error(format!("Failed to read magic bytes: {e}")))?;

        if magic != HDT_STAR_MAGIC {
            return Err(StarError::parse_error(
                "Invalid HDT-star file: magic bytes mismatch",
            ));
        }

        // Read header
        let mut header_len_bytes = [0u8; 8];
        reader
            .read_exact(&mut header_len_bytes)
            .map_err(|e| StarError::parse_error(format!("Failed to read header length: {e}")))?;
        let header_len = u64::from_le_bytes(header_len_bytes) as usize;

        let mut header_bytes = vec![0u8; header_len];
        reader
            .read_exact(&mut header_bytes)
            .map_err(|e| StarError::parse_error(format!("Failed to read header: {e}")))?;
        let header = HdtStarHeader::from_bytes(&header_bytes)?;

        // Read dictionary length
        let mut dict_len_bytes = [0u8; 8];
        reader.read_exact(&mut dict_len_bytes).map_err(|e| {
            StarError::parse_error(format!("Failed to read dictionary length: {e}"))
        })?;
        let _dict_len = u64::from_le_bytes(dict_len_bytes) as usize;

        // Read dictionary (handle compression)
        let dict_bytes = if header.config.enable_compression {
            let mut compressed_len_bytes = [0u8; 8];
            reader.read_exact(&mut compressed_len_bytes).map_err(|e| {
                StarError::parse_error(format!("Failed to read compressed length: {e}"))
            })?;
            let compressed_len = u64::from_le_bytes(compressed_len_bytes) as usize;

            let mut compressed = vec![0u8; compressed_len];
            reader
                .read_exact(&mut compressed)
                .map_err(|e| StarError::parse_error(format!("Failed to read dictionary: {e}")))?;
            decompress_data(&compressed)?
        } else {
            let mut dict_bytes = vec![0u8; _dict_len];
            reader
                .read_exact(&mut dict_bytes)
                .map_err(|e| StarError::parse_error(format!("Failed to read dictionary: {e}")))?;
            dict_bytes
        };
        let dictionary = HdtStarDictionary::from_bytes(&dict_bytes)?;

        // Read triples length
        let mut triples_len_bytes = [0u8; 8];
        reader
            .read_exact(&mut triples_len_bytes)
            .map_err(|e| StarError::parse_error(format!("Failed to read triples length: {e}")))?;
        let _triples_len = u64::from_le_bytes(triples_len_bytes) as usize;

        // Read triples (handle compression)
        let triples_bytes = if header.config.enable_compression {
            let mut compressed_len_bytes = [0u8; 8];
            reader.read_exact(&mut compressed_len_bytes).map_err(|e| {
                StarError::parse_error(format!("Failed to read compressed length: {e}"))
            })?;
            let compressed_len = u64::from_le_bytes(compressed_len_bytes) as usize;

            let mut compressed = vec![0u8; compressed_len];
            reader
                .read_exact(&mut compressed)
                .map_err(|e| StarError::parse_error(format!("Failed to read triples: {e}")))?;
            decompress_data(&compressed)?
        } else {
            let mut triples_bytes = vec![0u8; _triples_len];
            reader
                .read_exact(&mut triples_bytes)
                .map_err(|e| StarError::parse_error(format!("Failed to read triples: {e}")))?;
            triples_bytes
        };
        let triples = HdtStarTriples::from_bytes(&triples_bytes)?;

        info!(
            "Loaded HDT-star file: {} triples, {} quoted triples",
            header.triple_count, header.quoted_triple_count
        );

        Ok(Self {
            header,
            dictionary,
            triples,
        })
    }

    /// Get the header
    pub fn header(&self) -> &HdtStarHeader {
        &self.header
    }

    /// Get the dictionary
    pub fn dictionary(&self) -> &HdtStarDictionary {
        &self.dictionary
    }

    /// Get triple count
    pub fn len(&self) -> usize {
        self.triples.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.triples.is_empty()
    }

    /// Iterate over all triples, decoding them
    pub fn iter_triples(&self) -> impl Iterator<Item = StarResult<StarTriple>> + '_ {
        self.triples
            .iter()
            .map(|encoded| self.decode_triple(encoded))
    }

    /// Decode an encoded triple back to a StarTriple
    fn decode_triple(&self, encoded: &EncodedTriple) -> StarResult<StarTriple> {
        let subject = self.decode_term(&encoded.subject, TermPosition::Subject)?;
        let predicate = self
            .dictionary
            .get_predicate(encoded.predicate)
            .ok_or_else(|| StarError::parse_error("Invalid predicate ID"))?
            .to_star_term()?;
        let object = self.decode_term(&encoded.object, TermPosition::Object)?;

        Ok(StarTriple::new(subject, predicate, object))
    }

    /// Decode an encoded term back to a StarTerm
    fn decode_term(&self, encoded: &EncodedTerm, position: TermPosition) -> StarResult<StarTerm> {
        match encoded {
            EncodedTerm::Regular(id) => {
                let entry = match position {
                    TermPosition::Subject => self.dictionary.get_subject(*id),
                    TermPosition::Object => self.dictionary.get_object(*id),
                }
                .ok_or_else(|| StarError::parse_error("Invalid term ID"))?;
                entry.to_star_term()
            }
            EncodedTerm::QuotedTriple(qt_id) => {
                let encoded_qt = self
                    .dictionary
                    .get_quoted_triple(*qt_id)
                    .ok_or_else(|| StarError::parse_error("Invalid quoted triple ID"))?;
                let decoded_qt = self.decode_triple(encoded_qt)?;
                Ok(StarTerm::quoted_triple(decoded_qt))
            }
        }
    }

    /// Convert to StarStore
    pub fn to_store(&self) -> StarResult<StarStore> {
        let store = StarStore::new();
        for result in self.iter_triples() {
            let triple = result?;
            store.insert(&triple)?;
        }
        Ok(store)
    }

    /// Query by subject
    pub fn query_by_subject(&self, subject: &StarTerm) -> Vec<StarResult<StarTriple>> {
        let target_entry = DictionaryEntry::from_star_term(subject);

        // Find subject ID
        let subject_id = match self.dictionary.subjects.get(&target_entry) {
            Some(&id) => id,
            None => return Vec::new(),
        };

        self.triples
            .spo_index
            .iter()
            .filter(|t| matches!(&t.subject, EncodedTerm::Regular(id) if *id == subject_id))
            .map(|t| self.decode_triple(t))
            .collect()
    }

    /// Query by predicate
    pub fn query_by_predicate(&self, predicate: &StarTerm) -> Vec<StarResult<StarTriple>> {
        let target_entry = DictionaryEntry::from_star_term(predicate);

        // Find predicate ID
        let predicate_id = match self.dictionary.predicates.get(&target_entry) {
            Some(&id) => id,
            None => return Vec::new(),
        };

        self.triples
            .pos_index
            .iter()
            .filter(|t| t.predicate == predicate_id)
            .map(|t| self.decode_triple(t))
            .collect()
    }

    /// Query by object
    pub fn query_by_object(&self, object: &StarTerm) -> Vec<StarResult<StarTriple>> {
        let target_entry = DictionaryEntry::from_star_term(object);

        // Find object ID
        let object_id = match self.dictionary.objects.get(&target_entry) {
            Some(&id) => id,
            None => return Vec::new(),
        };

        self.triples
            .osp_index
            .iter()
            .filter(|t| matches!(&t.object, EncodedTerm::Regular(id) if *id == object_id))
            .map(|t| self.decode_triple(t))
            .collect()
    }
}

/// Compress data using zstd
fn compress_data(data: &[u8], level: u8) -> StarResult<Vec<u8>> {
    oxiarc_zstd::encode_all(data, level as i32)
        .map_err(|e| StarError::serialization_error(format!("Compression failed: {e}")))
}

/// Decompress data using zstd
fn decompress_data(data: &[u8]) -> StarResult<Vec<u8>> {
    oxiarc_zstd::decode_all(data)
        .map_err(|e| StarError::parse_error(format!("Decompression failed: {e}")))
}

/// HDT-star format converter
pub struct HdtStarConverter;

impl HdtStarConverter {
    /// Convert a StarStore to HDT-star bytes
    pub fn store_to_hdt(store: &StarStore, config: HdtStarConfig) -> StarResult<Vec<u8>> {
        let mut builder = HdtStarBuilder::new(config);
        builder.add_store(store)?;

        let mut buffer = Vec::new();
        builder.write(&mut buffer)?;
        Ok(buffer)
    }

    /// Convert HDT-star bytes to a StarStore
    pub fn hdt_to_store(data: &[u8]) -> StarResult<StarStore> {
        let reader = HdtStarReader::read(&mut std::io::Cursor::new(data))?;
        reader.to_store()
    }

    /// Get HDT-star file statistics without loading full data
    pub fn get_statistics<R: Read>(reader: &mut R) -> StarResult<HdtStarHeader> {
        // Read and verify magic bytes
        let mut magic = [0u8; 8];
        reader
            .read_exact(&mut magic)
            .map_err(|e| StarError::parse_error(format!("Failed to read magic bytes: {e}")))?;

        if magic != HDT_STAR_MAGIC {
            return Err(StarError::parse_error(
                "Invalid HDT-star file: magic bytes mismatch",
            ));
        }

        // Read header only
        let mut header_len_bytes = [0u8; 8];
        reader
            .read_exact(&mut header_len_bytes)
            .map_err(|e| StarError::parse_error(format!("Failed to read header length: {e}")))?;
        let header_len = u64::from_le_bytes(header_len_bytes) as usize;

        let mut header_bytes = vec![0u8; header_len];
        reader
            .read_exact(&mut header_bytes)
            .map_err(|e| StarError::parse_error(format!("Failed to read header: {e}")))?;

        HdtStarHeader::from_bytes(&header_bytes)
    }
}

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

    #[test]
    fn test_hdt_star_config_default() {
        let config = HdtStarConfig::default();
        assert!(config.enable_compression);
        assert_eq!(config.compression_level, 6);
        assert!(config.enable_quoted_dict);
        assert_eq!(config.max_nesting_depth, 10);
    }

    #[test]
    fn test_hdt_star_header_serialization() {
        let config = HdtStarConfig::default();
        let header = HdtStarHeader::new(config);

        let bytes = header.to_bytes().unwrap();
        let decoded = HdtStarHeader::from_bytes(&bytes).unwrap();

        assert_eq!(decoded.version, HDT_STAR_VERSION);
        assert_eq!(decoded.triple_count, 0);
    }

    #[test]
    fn test_dictionary_entry_conversion() {
        let iri = StarTerm::iri("http://example.org/test").unwrap();
        let entry = DictionaryEntry::from_star_term(&iri);

        assert!(matches!(entry, DictionaryEntry::Iri(_)));

        let back = entry.to_star_term().unwrap();
        assert!(matches!(back, StarTerm::NamedNode(_)));
    }

    #[test]
    fn test_dictionary_operations() {
        let mut dict = HdtStarDictionary::new();

        let entry1 = DictionaryEntry::Iri("http://example.org/s1".to_string());
        let entry2 = DictionaryEntry::Iri("http://example.org/s2".to_string());

        let id1 = dict.add_subject(entry1.clone());
        let id2 = dict.add_subject(entry2);
        let id1_again = dict.add_subject(entry1);

        assert_eq!(id1, id1_again); // Same entry should get same ID
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_hdt_star_builder_simple() {
        let config = HdtStarConfig::default();
        let mut builder = HdtStarBuilder::new(config);

        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/s").unwrap(),
            StarTerm::iri("http://example.org/p").unwrap(),
            StarTerm::iri("http://example.org/o").unwrap(),
        );

        builder.add_triple(&triple).unwrap();

        let stats = builder.statistics();
        assert_eq!(stats.triple_count, 1);
    }

    #[test]
    fn test_hdt_star_builder_with_quoted_triple() {
        let config = HdtStarConfig::default();
        let mut builder = HdtStarBuilder::new(config);

        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("30").unwrap(),
        );

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

        builder.add_triple(&outer).unwrap();

        let stats = builder.statistics();
        assert_eq!(stats.triple_count, 1);
        assert_eq!(stats.quoted_triple_count, 1);
    }

    #[test]
    fn test_hdt_star_roundtrip() {
        let config = HdtStarConfig::default();
        let mut builder = HdtStarBuilder::new(config);

        // Add regular triples
        for i in 0..10 {
            let s = format!("http://example.org/s{}", i);
            let v = format!("value{}", i);
            let triple = StarTriple::new(
                StarTerm::iri(&s).unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal(&v).unwrap(),
            );
            builder.add_triple(&triple).unwrap();
        }

        // Add quoted triple
        let quoted = StarTriple::new(
            StarTerm::iri("http://example.org/x").unwrap(),
            StarTerm::iri("http://example.org/y").unwrap(),
            StarTerm::iri("http://example.org/z").unwrap(),
        );
        let meta = StarTriple::new(
            StarTerm::quoted_triple(quoted),
            StarTerm::iri("http://example.org/meta").unwrap(),
            StarTerm::literal("test").unwrap(),
        );
        builder.add_triple(&meta).unwrap();

        // Write to buffer
        let mut buffer = Vec::new();
        builder.write(&mut buffer).unwrap();

        // Read back
        let reader = HdtStarReader::read(&mut std::io::Cursor::new(&buffer)).unwrap();

        assert_eq!(reader.len(), 11);
        assert_eq!(reader.header().quoted_triple_count, 1);

        // Verify all triples decode correctly
        let decoded: Vec<_> = reader.iter_triples().collect();
        assert_eq!(decoded.len(), 11);
        for result in decoded {
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_hdt_star_query_by_subject() {
        let config = HdtStarConfig::default();
        let mut builder = HdtStarBuilder::new(config);

        let subject = StarTerm::iri("http://example.org/alice").unwrap();

        for i in 0..5 {
            let p = format!("http://example.org/p{}", i);
            let v = format!("value{}", i);
            let triple = StarTriple::new(
                subject.clone(),
                StarTerm::iri(&p).unwrap(),
                StarTerm::literal(&v).unwrap(),
            );
            builder.add_triple(&triple).unwrap();
        }

        // Add some other triples
        for i in 0..3 {
            let p = format!("http://example.org/p{}", i);
            let triple = StarTriple::new(
                StarTerm::iri("http://example.org/bob").unwrap(),
                StarTerm::iri(&p).unwrap(),
                StarTerm::literal("other").unwrap(),
            );
            builder.add_triple(&triple).unwrap();
        }

        let mut buffer = Vec::new();
        builder.write(&mut buffer).unwrap();

        let reader = HdtStarReader::read(&mut std::io::Cursor::new(&buffer)).unwrap();
        let results = reader.query_by_subject(&subject);

        assert_eq!(results.len(), 5);
    }

    #[test]
    fn test_hdt_star_converter() {
        let store = StarStore::new();

        for i in 0..10 {
            let s = format!("http://example.org/s{}", i);
            let v = format!("{}", i);
            let triple = StarTriple::new(
                StarTerm::iri(&s).unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal(&v).unwrap(),
            );
            store.insert(&triple).unwrap();
        }

        let config = HdtStarConfig::default();
        let hdt_bytes = HdtStarConverter::store_to_hdt(&store, config).unwrap();

        let restored = HdtStarConverter::hdt_to_store(&hdt_bytes).unwrap();

        assert_eq!(restored.len(), store.len());
    }

    #[test]
    fn test_hdt_star_compression() {
        let config = HdtStarConfig {
            enable_compression: true,
            compression_level: 9,
            ..HdtStarConfig::default()
        };

        let mut builder = HdtStarBuilder::new(config.clone());

        // Add many similar triples to test compression
        for i in 0..1000 {
            let s = format!("http://example.org/subject{}", i);
            let v = format!("This is a test value number {}", i);
            let triple = StarTriple::new(
                StarTerm::iri(&s).unwrap(),
                StarTerm::iri("http://example.org/predicate").unwrap(),
                StarTerm::literal(&v).unwrap(),
            );
            builder.add_triple(&triple).unwrap();
        }

        let mut compressed_buffer = Vec::new();
        builder.write(&mut compressed_buffer).unwrap();

        // Without compression
        let config_uncompressed = HdtStarConfig {
            enable_compression: false,
            ..config
        };
        let mut builder_uncompressed = HdtStarBuilder::new(config_uncompressed);
        for i in 0..1000 {
            let s = format!("http://example.org/subject{}", i);
            let v = format!("This is a test value number {}", i);
            let triple = StarTriple::new(
                StarTerm::iri(&s).unwrap(),
                StarTerm::iri("http://example.org/predicate").unwrap(),
                StarTerm::literal(&v).unwrap(),
            );
            builder_uncompressed.add_triple(&triple).unwrap();
        }

        let mut uncompressed_buffer = Vec::new();
        builder_uncompressed
            .write(&mut uncompressed_buffer)
            .unwrap();

        // Compressed should be significantly smaller
        assert!(
            compressed_buffer.len() < uncompressed_buffer.len(),
            "Compressed: {}, Uncompressed: {}",
            compressed_buffer.len(),
            uncompressed_buffer.len()
        );
    }

    #[test]
    fn test_hdt_star_nested_quoted_triples() {
        let config = HdtStarConfig::default();
        let mut builder = HdtStarBuilder::new(config);

        // Create nested quoted triple
        let level1 = StarTriple::new(
            StarTerm::iri("http://example.org/a").unwrap(),
            StarTerm::iri("http://example.org/b").unwrap(),
            StarTerm::iri("http://example.org/c").unwrap(),
        );

        let level2 = StarTriple::new(
            StarTerm::quoted_triple(level1),
            StarTerm::iri("http://example.org/meta1").unwrap(),
            StarTerm::literal("level2").unwrap(),
        );

        let level3 = StarTriple::new(
            StarTerm::quoted_triple(level2),
            StarTerm::iri("http://example.org/meta2").unwrap(),
            StarTerm::literal("level3").unwrap(),
        );

        builder.add_triple(&level3).unwrap();

        let stats = builder.statistics();
        assert_eq!(stats.triple_count, 1);
        assert_eq!(stats.quoted_triple_count, 2); // Two nested quoted triples

        // Roundtrip test
        let mut buffer = Vec::new();
        builder.write(&mut buffer).unwrap();

        let reader = HdtStarReader::read(&mut std::io::Cursor::new(&buffer)).unwrap();
        let triples: Vec<_> = reader.iter_triples().collect();

        assert_eq!(triples.len(), 1);
        assert!(triples[0].is_ok());
    }
}