oxirs-core 0.2.4

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
//! RDF serialization utilities for various formats
//!
//! **Stability**: ✅ **Stable** - Core serializer APIs are production-ready.
//!
//! This module provides serializers to export RDF data to various standard formats.
//! It supports both triple-based (graph) and quad-based (dataset) serialization.
//!
//! ## Supported Formats
//!
//! ### Triple Formats (Graphs)
//! - **Turtle** (.ttl) - Compact, human-readable with prefixes
//! - **N-Triples** (.nt) - Line-based, simple format
//! - **RDF/XML** (.rdf) - XML-based format
//! - **JSON-LD** (.jsonld) - JSON format for linked data
//!
//! ### Quad Formats (Datasets)
//! - **TriG** (.trig) - Turtle with named graph support
//! - **N-Quads** (.nq) - Line-based quad format
//!
//! ## Examples
//!
//! ### Basic Serialization
//!
//! ```rust
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::{Graph, NamedNode, Triple, Literal};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a graph with some data
//! let mut graph = Graph::new();
//! let triple = Triple::new(
//!     NamedNode::new("http://example.org/alice")?,
//!     NamedNode::new("http://xmlns.com/foaf/0.1/name")?,
//!     Literal::new("Alice"),
//! );
//! graph.insert(triple);
//!
//! // Serialize to Turtle format
//! let serializer = Serializer::new(RdfFormat::Turtle);
//! let turtle = serializer.serialize_graph(&graph)?;
//! println!("{}", turtle);
//! # Ok(())
//! # }
//! ```
//!
//! ### Serialize to N-Triples
//!
//! ```rust
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::{Graph, NamedNode, Triple};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let mut graph = Graph::new();
//! # let triple = Triple::new(
//! #     NamedNode::new("http://example.org/alice")?,
//! #     NamedNode::new("http://xmlns.com/foaf/0.1/knows")?,
//! #     NamedNode::new("http://example.org/bob")?,
//! # );
//! # graph.insert(triple);
//! // N-Triples: one triple per line, no prefixes
//! let serializer = Serializer::new(RdfFormat::NTriples);
//! let ntriples = serializer.serialize_graph(&graph)?;
//!
//! // Output:
//! // <http://example.org/alice> <http://xmlns.com/foaf/0.1/knows> <http://example.org/bob> .
//! # Ok(())
//! # }
//! ```
//!
//! ### Serialize Datasets with Named Graphs
//!
//! ```rust
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::{Dataset, NamedNode, Quad, GraphName, Literal};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a dataset with named graphs
//! let mut dataset = Dataset::new();
//!
//! let graph1 = GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?);
//! let quad1 = Quad::new(
//!     NamedNode::new("http://example.org/alice")?,
//!     NamedNode::new("http://xmlns.com/foaf/0.1/name")?,
//!     Literal::new("Alice"),
//!     graph1,
//! );
//! dataset.insert(quad1);
//!
//! // Serialize to N-Quads format
//! let serializer = Serializer::new(RdfFormat::NQuads);
//! let nquads = serializer.serialize_dataset(&dataset)?;
//! println!("{}", nquads);
//! # Ok(())
//! # }
//! ```
//!
//! ### Serialize to TriG (Turtle with Graphs)
//!
//! ```rust
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::{Dataset, NamedNode, Quad, GraphName, Literal};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let mut dataset = Dataset::new();
//! # let graph = GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?);
//! # dataset.insert(Quad::new(
//! #     NamedNode::new("http://example.org/alice")?,
//! #     NamedNode::new("http://xmlns.com/foaf/0.1/name")?,
//! #     Literal::new("Alice"),
//! #     graph,
//! # ));
//! // TriG: Turtle syntax with named graph blocks
//! let serializer = Serializer::new(RdfFormat::TriG);
//! let trig = serializer.serialize_dataset(&dataset)?;
//!
//! // Output includes graph blocks:
//! // <http://example.org/graph1> {
//! //     <http://example.org/alice> <http://xmlns.com/foaf/0.1/name> "Alice" .
//! // }
//! # Ok(())
//! # }
//! ```
//!
//! ### Writing to Files
//!
//! ```rust,no_run
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::Graph;
//! use std::fs;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let graph = Graph::new();
//! // Serialize and write to file
//! let serializer = Serializer::new(RdfFormat::Turtle);
//! let turtle = serializer.serialize_graph(&graph)?;
//! fs::write("output.ttl", turtle)?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Quad Serialization Helper
//!
//! ```rust
//! use oxirs_core::serializer::Serializer;
//! use oxirs_core::parser::RdfFormat;
//! use oxirs_core::model::{NamedNode, Quad, Literal, GraphName};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let quad = Quad::new(
//!     NamedNode::new("http://example.org/subject")?,
//!     NamedNode::new("http://example.org/predicate")?,
//!     Literal::new("value"),
//!     GraphName::DefaultGraph,
//! );
//!
//! let serializer = Serializer::new(RdfFormat::NQuads);
//! let nquad_line = serializer.serialize_quad_to_nquads(&quad)?;
//! println!("{}", nquad_line);
//! # Ok(())
//! # }
//! ```
//!
//! ## Format Capabilities
//!
//! | Format | Graphs | Quads | Prefixes | Compact | Human-Readable |
//! |--------|--------|-------|----------|---------|----------------|
//! | Turtle | ✅ | ❌ | ✅ | ✅ | ✅ |
//! | N-Triples | ✅ | ❌ | ❌ | ❌ | ⚠️ |
//! | TriG | ✅ | ✅ | ✅ | ✅ | ✅ |
//! | N-Quads | ✅ | ✅ | ❌ | ❌ | ⚠️ |
//! | RDF/XML | ✅ | ❌ | ✅ | ❌ | ⚠️ |
//! | JSON-LD | ✅ | ✅ | ✅ | ⚠️ | ⚠️ |
//!
//! ## Format Selection Guidelines
//!
//! - **For human readability**: Use Turtle or TriG
//! - **For machine processing**: Use N-Triples or N-Quads
//! - **For web APIs**: Use JSON-LD
//! - **For XML systems**: Use RDF/XML
//! - **For named graphs**: Use TriG or N-Quads
//!
//! ## Performance Tips
//!
//! 1. **N-Triples/N-Quads** - Fastest to serialize (line-based)
//! 2. **Large datasets** - Use N-Quads for streaming serialization
//! 3. **Prefixes** - Turtle/TriG reduce output size with prefix declarations
//! 4. **Human review** - Turtle/TriG are most readable
//!
//! ## Error Handling
//!
//! Serialization can fail in these cases:
//! - **Format mismatch** - Using quad-only format for graphs (e.g., TriG for a Graph)
//! - **Unsupported features** - Variables in concrete formats
//! - **Invalid data** - Malformed IRIs or literals
//!
//! ## Related Modules
//!
//! - [`crate::parser`] - Parse RDF from various formats
//! - [`crate::model`] - RDF data model types
//! - [`crate::rdf_store`] - Store RDF data

use crate::{
    model::{dataset::Dataset, graph::Graph, GraphName, Quad},
    parser::RdfFormat,
    Result,
};

/// RDF serializer interface
pub struct Serializer {
    format: RdfFormat,
}

impl Serializer {
    /// Create a new serializer for the specified format
    pub fn new(format: RdfFormat) -> Self {
        Serializer { format }
    }

    /// Serialize a graph to a string
    pub fn serialize_graph(&self, graph: &Graph) -> Result<String> {
        match self.format {
            RdfFormat::Turtle => self.serialize_turtle(graph),
            RdfFormat::NTriples => self.serialize_ntriples(graph),
            RdfFormat::TriG => self.serialize_trig_graph(graph),
            RdfFormat::NQuads => self.serialize_nquads_graph(graph),
            RdfFormat::RdfXml => self.serialize_rdfxml(graph),
            RdfFormat::JsonLd => self.serialize_jsonld(graph),
        }
    }

    /// Serialize a dataset to a string (supports quad-based formats)
    pub fn serialize_dataset(&self, dataset: &Dataset) -> Result<String> {
        match self.format {
            RdfFormat::Turtle => Err(crate::OxirsError::Serialize(
                "Turtle format does not support datasets (use TriG instead)".to_string(),
            )),
            RdfFormat::NTriples => Err(crate::OxirsError::Serialize(
                "N-Triples format does not support datasets (use N-Quads instead)".to_string(),
            )),
            RdfFormat::TriG => self.serialize_trig_dataset(dataset),
            RdfFormat::NQuads => self.serialize_nquads_dataset(dataset),
            RdfFormat::RdfXml => Err(crate::OxirsError::Serialize(
                "RDF/XML dataset serialization not yet implemented".to_string(),
            )),
            RdfFormat::JsonLd => Err(crate::OxirsError::Serialize(
                "JSON-LD dataset serialization not yet implemented".to_string(),
            )),
        }
    }

    /// Legacy method for backward compatibility
    pub fn serialize(&self, graph: &Graph) -> Result<String> {
        self.serialize_graph(graph)
    }

    fn serialize_turtle(&self, graph: &Graph) -> Result<String> {
        let mut serializer = TurtleSerializer::new();
        serializer.serialize_graph(graph)
    }

    fn serialize_ntriples(&self, graph: &Graph) -> Result<String> {
        let mut result = String::new();

        for triple in graph.iter() {
            // Serialize subject
            match triple.subject() {
                crate::model::Subject::NamedNode(node) => {
                    result.push_str(&format!("<{}>", node.as_str()));
                }
                crate::model::Subject::BlankNode(node) => {
                    result.push_str(&format!("{node}"));
                }
                crate::model::Subject::Variable(_) => {
                    return Err(crate::OxirsError::Serialize(
                        "Variables not supported in N-Triples serialization".to_string(),
                    ));
                }
                crate::model::Subject::QuotedTriple(_) => {
                    return Err(crate::OxirsError::Serialize(
                        "Quoted triples not supported in N-Triples serialization".to_string(),
                    ));
                }
            }

            result.push(' ');

            // Serialize predicate
            match triple.predicate() {
                crate::model::Predicate::NamedNode(node) => {
                    result.push_str(&format!("<{}>", node.as_str()));
                }
                crate::model::Predicate::Variable(_) => {
                    return Err(crate::OxirsError::Serialize(
                        "Variables not supported in N-Triples serialization".to_string(),
                    ));
                }
            }

            result.push(' ');

            // Serialize object
            match triple.object() {
                crate::model::Object::NamedNode(node) => {
                    result.push_str(&format!("<{}>", node.as_str()));
                }
                crate::model::Object::BlankNode(node) => {
                    result.push_str(&format!("{node}"));
                }
                crate::model::Object::Literal(literal) => {
                    result.push('"');
                    // Escape quotes and backslashes in literal value
                    for c in literal.value().chars() {
                        match c {
                            '"' => result.push_str("\\\""),
                            '\\' => result.push_str("\\\\"),
                            '\n' => result.push_str("\\n"),
                            '\r' => result.push_str("\\r"),
                            '\t' => result.push_str("\\t"),
                            _ => result.push(c),
                        }
                    }
                    result.push('"');

                    // Add language tag or datatype
                    if let Some(lang) = literal.language() {
                        result.push_str(&format!("@{lang}"));
                    } else {
                        let datatype = literal.datatype();
                        if datatype.as_str() != "http://www.w3.org/2001/XMLSchema#string" {
                            result.push_str(&format!("^^<{}>", datatype.as_str()));
                        }
                    }
                }
                crate::model::Object::Variable(_) => {
                    return Err(crate::OxirsError::Serialize(
                        "Variables not supported in N-Triples serialization".to_string(),
                    ));
                }
                crate::model::Object::QuotedTriple(_) => {
                    return Err(crate::OxirsError::Serialize(
                        "Quoted triples not supported in N-Triples serialization".to_string(),
                    ));
                }
            }

            result.push_str(" .\n");
        }

        Ok(result)
    }

    fn serialize_rdfxml(&self, graph: &Graph) -> Result<String> {
        use oxrdfxml::RdfXmlSerializer;

        let mut output = Vec::new();
        let mut serializer = RdfXmlSerializer::new().for_writer(&mut output);

        // Convert OxiRS triples to oxrdf triples and serialize
        for triple in graph.iter() {
            // Convert to oxrdf::Triple
            let oxrdf_triple = self.convert_triple_to_oxrdf(triple)?;
            serializer.serialize_triple(&oxrdf_triple).map_err(|e| {
                crate::OxirsError::Serialize(format!("RDF/XML serialization error: {e}"))
            })?;
        }

        serializer
            .finish()
            .map_err(|e| crate::OxirsError::Serialize(format!("RDF/XML finish error: {e}")))?;

        String::from_utf8(output)
            .map_err(|e| crate::OxirsError::Serialize(format!("UTF-8 conversion error: {e}")))
    }

    fn serialize_trig_graph(&self, graph: &Graph) -> Result<String> {
        use oxttl::TriGSerializer;

        let mut output = Vec::new();
        let mut serializer = TriGSerializer::new().for_writer(&mut output);

        // Serialize all triples as quads in the default graph
        for triple in graph.iter() {
            let oxrdf_quad = self.convert_triple_to_oxrdf_quad(triple, None)?;
            serializer.serialize_quad(&oxrdf_quad).map_err(|e| {
                crate::OxirsError::Serialize(format!("TriG serialization error: {e}"))
            })?;
        }

        serializer
            .finish()
            .map_err(|e| crate::OxirsError::Serialize(format!("TriG finish error: {e}")))?;

        String::from_utf8(output)
            .map_err(|e| crate::OxirsError::Serialize(format!("UTF-8 conversion error: {e}")))
    }

    fn serialize_trig_dataset(&self, dataset: &Dataset) -> Result<String> {
        use oxttl::TriGSerializer;

        let mut output = Vec::new();
        let mut serializer = TriGSerializer::new().for_writer(&mut output);

        // Serialize all quads
        for quad in dataset.iter() {
            let oxrdf_quad = self.convert_quad_to_oxrdf(&quad)?;
            serializer.serialize_quad(&oxrdf_quad).map_err(|e| {
                crate::OxirsError::Serialize(format!("TriG serialization error: {e}"))
            })?;
        }

        serializer
            .finish()
            .map_err(|e| crate::OxirsError::Serialize(format!("TriG finish error: {e}")))?;

        String::from_utf8(output)
            .map_err(|e| crate::OxirsError::Serialize(format!("UTF-8 conversion error: {e}")))
    }

    fn serialize_nquads_graph(&self, graph: &Graph) -> Result<String> {
        // For a graph, serialize all triples as quads in the default graph
        let mut result = String::new();

        for triple in graph.iter() {
            result.push_str(&self.serialize_quad_to_nquads(&Quad::from_triple(triple.clone()))?);
        }

        Ok(result)
    }

    fn serialize_nquads_dataset(&self, dataset: &Dataset) -> Result<String> {
        let mut result = String::new();

        for quad in dataset.iter() {
            result.push_str(&self.serialize_quad_to_nquads(&quad)?);
        }

        Ok(result)
    }

    pub fn serialize_quad_to_nquads(&self, quad: &Quad) -> Result<String> {
        let mut result = String::new();

        // Serialize subject
        match quad.subject() {
            crate::model::Subject::NamedNode(node) => {
                result.push_str(&format!("<{}>", node.as_str()));
            }
            crate::model::Subject::BlankNode(node) => {
                result.push_str(&format!("{node}"));
            }
            crate::model::Subject::Variable(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Variables not supported in N-Quads serialization".to_string(),
                ));
            }
            crate::model::Subject::QuotedTriple(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Quoted triples not supported in N-Quads serialization".to_string(),
                ));
            }
        }

        result.push(' ');

        // Serialize predicate
        match quad.predicate() {
            crate::model::Predicate::NamedNode(node) => {
                result.push_str(&format!("<{}>", node.as_str()));
            }
            crate::model::Predicate::Variable(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Variables not supported in N-Quads serialization".to_string(),
                ));
            }
        }

        result.push(' ');

        // Serialize object
        match quad.object() {
            crate::model::Object::NamedNode(node) => {
                result.push_str(&format!("<{}>", node.as_str()));
            }
            crate::model::Object::BlankNode(node) => {
                result.push_str(&format!("{node}"));
            }
            crate::model::Object::Literal(literal) => {
                result.push('"');
                // Escape quotes and backslashes in literal value
                for c in literal.value().chars() {
                    match c {
                        '"' => result.push_str("\\\""),
                        '\\' => result.push_str("\\\\"),
                        '\n' => result.push_str("\\n"),
                        '\r' => result.push_str("\\r"),
                        '\t' => result.push_str("\\t"),
                        _ => result.push(c),
                    }
                }
                result.push('"');

                // Add language tag or datatype
                if let Some(lang) = literal.language() {
                    result.push_str(&format!("@{lang}"));
                } else {
                    let datatype = literal.datatype();
                    if datatype.as_str() != "http://www.w3.org/2001/XMLSchema#string" {
                        result.push_str(&format!("^^<{}>", datatype.as_str()));
                    }
                }
            }
            crate::model::Object::Variable(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Variables not supported in N-Quads serialization".to_string(),
                ));
            }
            crate::model::Object::QuotedTriple(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Quoted triples not supported in N-Quads serialization".to_string(),
                ));
            }
        }

        result.push(' ');

        // Serialize graph name
        match quad.graph_name() {
            GraphName::NamedNode(node) => {
                result.push_str(&format!("<{}>", node.as_str()));
            }
            GraphName::BlankNode(node) => {
                result.push_str(&format!("{node}"));
            }
            GraphName::Variable(_) => {
                return Err(crate::OxirsError::Serialize(
                    "Variables not supported in N-Quads serialization".to_string(),
                ));
            }
            GraphName::DefaultGraph => {
                // For default graph, we can either omit the graph name entirely
                // or use a special representation. Let's omit it to make it N-Triples compatible
                result.pop(); // Remove the trailing space
                result.push_str(" .\n");
                return Ok(result);
            }
        }

        result.push_str(" .\n");

        Ok(result)
    }

    fn serialize_jsonld(&self, graph: &Graph) -> Result<String> {
        use oxjsonld::JsonLdSerializer;

        let mut output = Vec::new();
        let mut serializer = JsonLdSerializer::new().for_writer(&mut output);

        // Convert OxiRS triples to oxrdf triples and serialize
        for triple in graph.iter() {
            let oxrdf_quad = self.convert_triple_to_oxrdf_quad(triple, None)?;
            serializer.serialize_quad(&oxrdf_quad).map_err(|e| {
                crate::OxirsError::Serialize(format!("JSON-LD serialization error: {e}"))
            })?;
        }

        serializer
            .finish()
            .map_err(|e| crate::OxirsError::Serialize(format!("JSON-LD finish error: {e}")))?;

        String::from_utf8(output)
            .map_err(|e| crate::OxirsError::Serialize(format!("UTF-8 conversion error: {e}")))
    }

    /// Convert OxiRS Triple to oxrdf::Triple for use with external serializers
    fn convert_triple_to_oxrdf(&self, triple: &crate::model::Triple) -> Result<oxrdf::Triple> {
        // Convert subject
        let subject = match triple.subject() {
            crate::model::Subject::NamedNode(n) => {
                oxrdf::NamedOrBlankNode::NamedNode(oxrdf::NamedNode::new_unchecked(n.as_str()))
            }
            crate::model::Subject::BlankNode(b) => {
                oxrdf::NamedOrBlankNode::BlankNode(oxrdf::BlankNode::new_unchecked(b.as_str()))
            }
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variables and quoted triples not supported in serialization".to_string(),
                ))
            }
        };

        // Convert predicate
        let predicate = match triple.predicate() {
            crate::model::Predicate::NamedNode(n) => oxrdf::NamedNode::new_unchecked(n.as_str()),
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variable predicates not supported in serialization".to_string(),
                ))
            }
        };

        // Convert object
        let object = match triple.object() {
            crate::model::Object::NamedNode(n) => {
                oxrdf::Term::NamedNode(oxrdf::NamedNode::new_unchecked(n.as_str()))
            }
            crate::model::Object::BlankNode(b) => {
                oxrdf::Term::BlankNode(oxrdf::BlankNode::new_unchecked(b.as_str()))
            }
            crate::model::Object::Literal(l) => {
                let literal = if let Some(lang) = l.language() {
                    oxrdf::Literal::new_language_tagged_literal_unchecked(l.value(), lang)
                } else {
                    let datatype = oxrdf::NamedNode::new_unchecked(l.datatype().as_str());
                    oxrdf::Literal::new_typed_literal(l.value(), datatype)
                };
                oxrdf::Term::Literal(literal)
            }
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variable objects and quoted triples not supported in serialization"
                        .to_string(),
                ))
            }
        };

        Ok(oxrdf::Triple::new(subject, predicate, object))
    }

    /// Convert OxiRS Triple to oxrdf::Quad (with optional graph name)
    fn convert_triple_to_oxrdf_quad(
        &self,
        triple: &crate::model::Triple,
        graph_name: Option<&oxrdf::GraphName>,
    ) -> Result<oxrdf::Quad> {
        let oxrdf_triple = self.convert_triple_to_oxrdf(triple)?;
        let graph = graph_name
            .cloned()
            .unwrap_or(oxrdf::GraphName::DefaultGraph);
        Ok(oxrdf::Quad::new(
            oxrdf_triple.subject,
            oxrdf_triple.predicate,
            oxrdf_triple.object,
            graph,
        ))
    }

    /// Convert OxiRS Quad to oxrdf::Quad
    fn convert_quad_to_oxrdf(&self, quad: &Quad) -> Result<oxrdf::Quad> {
        // Convert subject
        let subject = match quad.subject() {
            crate::model::Subject::NamedNode(n) => {
                oxrdf::NamedOrBlankNode::NamedNode(oxrdf::NamedNode::new_unchecked(n.as_str()))
            }
            crate::model::Subject::BlankNode(b) => {
                oxrdf::NamedOrBlankNode::BlankNode(oxrdf::BlankNode::new_unchecked(b.as_str()))
            }
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variables and quoted triples not supported in serialization".to_string(),
                ))
            }
        };

        // Convert predicate
        let predicate = match quad.predicate() {
            crate::model::Predicate::NamedNode(n) => oxrdf::NamedNode::new_unchecked(n.as_str()),
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variable predicates not supported in serialization".to_string(),
                ))
            }
        };

        // Convert object
        let object = match quad.object() {
            crate::model::Object::NamedNode(n) => {
                oxrdf::Term::NamedNode(oxrdf::NamedNode::new_unchecked(n.as_str()))
            }
            crate::model::Object::BlankNode(b) => {
                oxrdf::Term::BlankNode(oxrdf::BlankNode::new_unchecked(b.as_str()))
            }
            crate::model::Object::Literal(l) => {
                let literal = if let Some(lang) = l.language() {
                    oxrdf::Literal::new_language_tagged_literal_unchecked(l.value(), lang)
                } else {
                    let datatype = oxrdf::NamedNode::new_unchecked(l.datatype().as_str());
                    oxrdf::Literal::new_typed_literal(l.value(), datatype)
                };
                oxrdf::Term::Literal(literal)
            }
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variable objects and quoted triples not supported in serialization"
                        .to_string(),
                ))
            }
        };

        // Convert graph name
        let graph_name = match quad.graph_name() {
            GraphName::NamedNode(n) => {
                oxrdf::GraphName::NamedNode(oxrdf::NamedNode::new_unchecked(n.as_str()))
            }
            GraphName::BlankNode(b) => {
                oxrdf::GraphName::BlankNode(oxrdf::BlankNode::new_unchecked(b.as_str()))
            }
            GraphName::DefaultGraph => oxrdf::GraphName::DefaultGraph,
            _ => {
                return Err(crate::OxirsError::Serialize(
                    "Variable graph names not supported in serialization".to_string(),
                ))
            }
        };

        Ok(oxrdf::Quad::new(subject, predicate, object, graph_name))
    }
}

/// Turtle serializer with prefix optimization
struct TurtleSerializer {
    prefixes: std::collections::HashMap<String, String>,
    used_namespaces: std::collections::HashSet<String>,
}

impl TurtleSerializer {
    fn new() -> Self {
        let mut prefixes = std::collections::HashMap::new();

        // Add common prefixes
        prefixes.insert(
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
            "rdf".to_string(),
        );
        prefixes.insert(
            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
            "rdfs".to_string(),
        );
        prefixes.insert(
            "http://www.w3.org/2001/XMLSchema#".to_string(),
            "xsd".to_string(),
        );
        prefixes.insert("http://xmlns.com/foaf/0.1/".to_string(), "foaf".to_string());
        prefixes.insert(
            "http://purl.org/dc/elements/1.1/".to_string(),
            "dc".to_string(),
        );

        TurtleSerializer {
            prefixes,
            used_namespaces: std::collections::HashSet::new(),
        }
    }

    fn serialize_graph(&mut self, graph: &Graph) -> Result<String> {
        // First pass: collect all namespaces used in the graph
        self.collect_namespaces(graph);

        let mut result = String::new();

        // Write prefix declarations
        let mut prefix_entries: Vec<_> = self.prefixes.iter().collect();
        prefix_entries.sort_by_key(|(_, prefix)| *prefix);

        for (namespace, prefix) in prefix_entries {
            if self.used_namespaces.contains(namespace) {
                result.push_str(&format!("@prefix {prefix}: <{namespace}> .\n"));
            }
        }

        if !self.prefixes.is_empty() && !graph.is_empty() {
            result.push('\n');
        }

        // Group triples by subject for better readability
        let mut subjects_map: std::collections::HashMap<
            crate::model::Subject,
            Vec<&crate::model::Triple>,
        > = std::collections::HashMap::new();

        for triple in graph.iter() {
            subjects_map
                .entry(triple.subject().clone())
                .or_default()
                .push(triple);
        }

        let mut subject_entries: Vec<_> = subjects_map.iter().collect();
        subject_entries.sort_by_key(|(subject, _)| format!("{subject}"));

        for (i, (subject, triples)) in subject_entries.iter().enumerate() {
            if i > 0 {
                result.push('\n');
            }

            result.push_str(&self.serialize_subject(subject)?);

            // Group by predicate for ; syntax
            let mut predicates_map: std::collections::HashMap<
                crate::model::Predicate,
                Vec<&crate::model::Object>,
            > = std::collections::HashMap::new();

            for triple in triples.iter() {
                predicates_map
                    .entry(triple.predicate().clone())
                    .or_default()
                    .push(triple.object());
            }

            let mut predicate_entries: Vec<_> = predicates_map.iter().collect();
            predicate_entries.sort_by_key(|(predicate, _)| format!("{predicate}"));

            for (j, (predicate, objects)) in predicate_entries.iter().enumerate() {
                if j == 0 {
                    result.push(' ');
                } else {
                    result.push_str(" ;\n        ");
                }

                result.push_str(&self.serialize_predicate(predicate)?);
                result.push(' ');

                // Serialize objects with , syntax
                for (k, object) in objects.iter().enumerate() {
                    if k > 0 {
                        result.push_str(", ");
                    }
                    result.push_str(&self.serialize_object(object)?);
                }
            }

            result.push_str(" .\n");
        }

        Ok(result)
    }

    fn collect_namespaces(&mut self, graph: &Graph) {
        for triple in graph.iter() {
            self.mark_namespace_used(triple.subject());
            self.mark_namespace_used_predicate(triple.predicate());
            self.mark_namespace_used_object(triple.object());
        }
    }

    fn mark_namespace_used(&mut self, subject: &crate::model::Subject) {
        if let crate::model::Subject::NamedNode(node) = subject {
            if let Some(namespace) = self.extract_namespace(node.as_str()) {
                self.used_namespaces.insert(namespace);
            }
        }
    }

    fn mark_namespace_used_predicate(&mut self, predicate: &crate::model::Predicate) {
        if let crate::model::Predicate::NamedNode(node) = predicate {
            if let Some(namespace) = self.extract_namespace(node.as_str()) {
                self.used_namespaces.insert(namespace);
            }
        }
    }

    fn mark_namespace_used_object(&mut self, object: &crate::model::Object) {
        match object {
            crate::model::Object::NamedNode(node) => {
                if let Some(namespace) = self.extract_namespace(node.as_str()) {
                    self.used_namespaces.insert(namespace);
                }
            }
            crate::model::Object::Literal(literal) => {
                let datatype = literal.datatype();
                if let Some(namespace) = self.extract_namespace(datatype.as_str()) {
                    self.used_namespaces.insert(namespace);
                }
            }
            _ => {}
        }
    }

    fn extract_namespace(&self, iri: &str) -> Option<String> {
        // Find the namespace part of an IRI
        if let Some(hash_pos) = iri.rfind('#') {
            Some(format!("{}#", &iri[..hash_pos]))
        } else {
            iri.rfind('/')
                .map(|slash_pos| format!("{}/", &iri[..slash_pos]))
        }
    }

    fn serialize_subject(&self, subject: &crate::model::Subject) -> Result<String> {
        match subject {
            crate::model::Subject::NamedNode(node) => self.serialize_iri(node.as_str()),
            crate::model::Subject::BlankNode(node) => Ok(node.as_str().to_string()),
            crate::model::Subject::Variable(_var) => Err(crate::OxirsError::Serialize(
                "Variables not supported in Turtle serialization".to_string(),
            )),
            crate::model::Subject::QuotedTriple(qt) => Ok(format!(
                "<< {} {} {} >>",
                self.serialize_subject(qt.subject())?,
                self.serialize_predicate(qt.predicate())?,
                self.serialize_object(qt.object())?
            )),
        }
    }

    fn serialize_predicate(&self, predicate: &crate::model::Predicate) -> Result<String> {
        match predicate {
            crate::model::Predicate::NamedNode(node) => {
                // Check for rdf:type shorthand
                if node.as_str() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" {
                    Ok("a".to_string())
                } else {
                    self.serialize_iri(node.as_str())
                }
            }
            crate::model::Predicate::Variable(_) => Err(crate::OxirsError::Serialize(
                "Variables not supported in Turtle serialization".to_string(),
            )),
        }
    }

    fn serialize_object(&self, object: &crate::model::Object) -> Result<String> {
        match object {
            crate::model::Object::NamedNode(node) => self.serialize_iri(node.as_str()),
            crate::model::Object::BlankNode(node) => Ok(node.as_str().to_string()),
            crate::model::Object::Literal(literal) => self.serialize_literal(literal),
            crate::model::Object::Variable(_) => Err(crate::OxirsError::Serialize(
                "Variables not supported in Turtle serialization".to_string(),
            )),
            crate::model::Object::QuotedTriple(qt) => Ok(format!(
                "<< {} {} {} >>",
                self.serialize_subject(qt.subject())?,
                self.serialize_predicate(qt.predicate())?,
                self.serialize_object(qt.object())?
            )),
        }
    }

    fn serialize_iri(&self, iri: &str) -> Result<String> {
        // Try to use a prefix if available
        for (namespace, prefix) in &self.prefixes {
            if iri.starts_with(namespace) && self.used_namespaces.contains(namespace) {
                let local_name = &iri[namespace.len()..];
                // Ensure local name is valid
                if self.is_valid_local_name(local_name) {
                    return Ok(format!("{prefix}:{local_name}"));
                }
            }
        }

        // Fall back to full IRI
        Ok(format!("<{iri}>"))
    }

    fn is_valid_local_name(&self, name: &str) -> bool {
        // Simple validation - should start with letter or underscore
        // and contain only alphanumeric, underscore, hyphen
        if name.is_empty() {
            return true; // Empty local name is valid
        }

        let first_char = name
            .chars()
            .next()
            .expect("non-empty name should have first char");
        if !first_char.is_alphabetic() && first_char != '_' {
            return false;
        }

        name.chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    }

    fn serialize_literal(&self, literal: &crate::model::Literal) -> Result<String> {
        let mut result = String::new();

        // Quote the literal value
        result.push('"');
        for c in literal.value().chars() {
            match c {
                '"' => result.push_str("\\\""),
                '\\' => result.push_str("\\\\"),
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                _ => result.push(c),
            }
        }
        result.push('"');

        // Add language tag or datatype
        if let Some(lang) = literal.language() {
            result.push_str(&format!("@{lang}"));
        } else {
            let datatype = literal.datatype();
            // Check if it's the default string type
            if datatype.as_str() != "http://www.w3.org/2001/XMLSchema#string" {
                result.push_str("^^");
                result.push_str(&self.serialize_iri(datatype.as_str())?);
            }
        }

        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::graph::Graph;
    use crate::model::*;

    fn create_test_graph() -> Graph {
        let mut graph = Graph::new();

        // Add a simple triple
        let subject = NamedNode::new("http://example.org/alice").expect("valid IRI");
        let predicate = NamedNode::new("http://xmlns.com/foaf/0.1/name").expect("valid IRI");
        let object = Literal::new("Alice Smith");
        let triple1 = Triple::new(subject.clone(), predicate, object);

        // Add a typed literal triple
        let age_pred = NamedNode::new("http://xmlns.com/foaf/0.1/age").expect("valid IRI");
        let age_obj = Literal::new_typed("30", crate::vocab::xsd::INTEGER.clone());
        let triple2 = Triple::new(subject.clone(), age_pred, age_obj);

        // Add a language-tagged literal triple
        let desc_pred = NamedNode::new("http://example.org/description").expect("valid IRI");
        let desc_obj =
            Literal::new_lang("Une personne", "fr").expect("construction should succeed");
        let triple3 = Triple::new(subject, desc_pred, desc_obj);

        // Add a blank node triple
        let blank_subject = BlankNode::new("person1").expect("valid blank node id");
        let knows_pred = NamedNode::new("http://xmlns.com/foaf/0.1/knows").expect("valid IRI");
        let knows_obj = NamedNode::new("http://example.org/bob").expect("valid IRI");
        let triple4 = Triple::new(blank_subject, knows_pred, knows_obj);

        graph.insert(triple1);
        graph.insert(triple2);
        graph.insert(triple3);
        graph.insert(triple4);

        graph
    }

    #[test]
    fn test_ntriples_serialization() {
        let graph = create_test_graph();
        let serializer = Serializer::new(RdfFormat::NTriples);

        let result = serializer.serialize_graph(&graph);
        assert!(result.is_ok());

        let ntriples = result.expect("should have value");
        assert!(!ntriples.is_empty());

        // Check that all lines end with " ."
        for line in ntriples.lines() {
            if !line.trim().is_empty() {
                assert!(line.ends_with(" ."), "Line should end with ' .': {line}");
            }
        }

        // Check that the output contains our expected triples
        assert!(ntriples.contains("http://example.org/alice"));
        assert!(ntriples.contains("http://xmlns.com/foaf/0.1/name"));
        assert!(ntriples.contains("\"Alice Smith\""));
        assert!(ntriples.contains("\"30\"^^<http://www.w3.org/2001/XMLSchema#integer>"));
        assert!(ntriples.contains("\"Une personne\"@fr"));
        assert!(ntriples.contains("_:person1"));
    }

    #[test]
    fn test_literal_escaping() {
        let mut graph = Graph::new();
        let subject = NamedNode::new("http://example.org/test").expect("valid IRI");
        let predicate = NamedNode::new("http://example.org/description").expect("valid IRI");

        // Test literal with quotes and escape sequences
        let object = Literal::new("Text with \"quotes\" and \n newlines \t and tabs");
        let triple = Triple::new(subject, predicate, object);
        graph.insert(triple);

        let serializer = Serializer::new(RdfFormat::NTriples);
        let result = serializer
            .serialize_graph(&graph)
            .expect("operation should succeed");

        // Check that quotes and escape sequences are properly escaped
        assert!(result.contains("\\\"quotes\\\""));
        assert!(result.contains("\\n"));
        assert!(result.contains("\\t"));
    }

    #[test]
    fn test_empty_graph_serialization() {
        let graph = Graph::new();
        let serializer = Serializer::new(RdfFormat::NTriples);

        let result = serializer.serialize_graph(&graph);
        assert!(result.is_ok());

        let ntriples = result.expect("should have value");
        assert!(ntriples.is_empty());
    }

    #[test]
    fn test_variable_serialization_error() {
        let mut graph = Graph::new();
        let variable_subject = Variable::new("x").expect("valid variable name");
        let predicate = NamedNode::new("http://example.org/predicate").expect("valid IRI");
        let object = Literal::new("test");

        let triple = Triple::new(variable_subject, predicate, object);
        graph.insert(triple);

        let serializer = Serializer::new(RdfFormat::NTriples);
        let result = serializer.serialize_graph(&graph);

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Variables not supported"));
    }

    #[test]
    fn test_turtle_serialization() {
        let graph = create_test_graph();
        let serializer = Serializer::new(RdfFormat::Turtle);

        let result = serializer.serialize_graph(&graph);
        assert!(result.is_ok());

        let turtle = result.expect("should have value");
        assert!(!turtle.is_empty());

        // Should contain prefix declarations
        assert!(turtle.contains("@prefix"));

        // Should contain the 'a' shorthand for rdf:type
        // Should use abbreviated syntax with ;

        // Should have proper Turtle syntax
        assert!(turtle.ends_with(" .\n") || turtle.ends_with("."));
    }

    #[test]
    fn test_turtle_serialization_with_prefixes() {
        let mut graph = Graph::new();

        // Create triples using FOAF vocabulary
        let alice = NamedNode::new("http://example.org/alice").expect("valid IRI");
        let name_pred = NamedNode::new("http://xmlns.com/foaf/0.1/name").expect("valid IRI");
        let person_type = NamedNode::new("http://xmlns.com/foaf/0.1/Person").expect("valid IRI");
        let rdf_type =
            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").expect("valid IRI");

        let name_literal = Literal::new("Alice");

        graph.insert(Triple::new(alice.clone(), name_pred, name_literal));
        graph.insert(Triple::new(alice, rdf_type, person_type));

        let serializer = Serializer::new(RdfFormat::Turtle);
        let turtle = serializer
            .serialize_graph(&graph)
            .expect("operation should succeed");

        // Should include FOAF prefix
        assert!(turtle.contains("@prefix foaf: <http://xmlns.com/foaf/0.1/>"));

        // Should use 'a' shorthand for rdf:type
        assert!(turtle.contains(" a "));

        // Should use prefixed names
        assert!(turtle.contains("foaf:"));
    }

    #[test]
    fn test_turtle_serialization_abbreviated_syntax() {
        let mut graph = Graph::new();

        let alice = NamedNode::new("http://example.org/alice").expect("valid IRI");
        let name_pred = NamedNode::new("http://xmlns.com/foaf/0.1/name").expect("valid IRI");
        let age_pred = NamedNode::new("http://xmlns.com/foaf/0.1/age").expect("valid IRI");

        let name_literal = Literal::new("Alice");
        let age_literal = Literal::new_typed("30", crate::vocab::xsd::INTEGER.clone());

        graph.insert(Triple::new(alice.clone(), name_pred, name_literal));
        graph.insert(Triple::new(alice, age_pred, age_literal));

        let serializer = Serializer::new(RdfFormat::Turtle);
        let turtle = serializer
            .serialize_graph(&graph)
            .expect("operation should succeed");

        // Should use ; syntax for same subject
        assert!(turtle.contains(";"));

        // Should have proper indentation and formatting
        assert!(turtle.lines().count() >= 3); // prefixes + subject line + continuation
    }

    #[test]
    fn test_turtle_serialization_literals() {
        let mut graph = Graph::new();

        let subject = NamedNode::new("http://example.org/test").expect("valid IRI");
        let desc_pred = NamedNode::new("http://example.org/description").expect("valid IRI");
        let age_pred = NamedNode::new("http://example.org/age").expect("valid IRI");

        // Language-tagged literal
        let desc_literal =
            Literal::new_lang("Une description", "fr").expect("construction should succeed");
        // Typed literal
        let age_literal = Literal::new_typed("25", crate::vocab::xsd::INTEGER.clone());

        graph.insert(Triple::new(subject.clone(), desc_pred, desc_literal));
        graph.insert(Triple::new(subject, age_pred, age_literal));

        let serializer = Serializer::new(RdfFormat::Turtle);
        let turtle = serializer
            .serialize_graph(&graph)
            .expect("operation should succeed");

        // Should contain language tag
        assert!(turtle.contains("@fr"));

        // Should contain datatype with xsd prefix
        assert!(turtle.contains("^^xsd:integer"));
    }
}