oxirs-ttl 0.2.4

Turtle-family RDF parser and serializer for OxiRS - ported from Oxigraph
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
//! N-Quads format parser and serializer
//!
//! N-Quads is a line-based RDF serialization format that extends N-Triples
//! with support for named graphs. Each line contains one quad (subject, predicate,
//! object, graph) in a simple, unabbreviated format.
//!
//! # Format Overview
//!
//! - **Quad Structure**: `<subject> <predicate> <object> <graph> .`
//! - **Triple Structure** (default graph): `<subject> <predicate> <object> .`
//! - **Comments**: Lines starting with `#` are ignored
//! - **IRIs**: Enclosed in angle brackets `<http://example.org/>`
//! - **Literals**: Enclosed in quotes `"value"`
//! - **Blank Nodes**: Prefixed with `_:` like `_:b1`
//!
//! # Examples
//!
//! ## Basic N-Quads Parsing
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let nquads_data = r#"
//! <http://example.org/alice> <http://example.org/name> "Alice" .
//! <http://example.org/bob> <http://example.org/age> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .
//! "#;
//!
//! let parser = NQuadsParser::new();
//! let quads = parser.parse(Cursor::new(nquads_data))?;
//! assert_eq!(quads.len(), 2);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Parsing Named Graphs
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let nquads_data = "\
//! <http://example.org/alice> <http://example.org/knows> <http://example.org/bob> .\n\
//! <http://example.org/alice> <http://example.org/age> \"30\"^^<http://www.w3.org/2001/XMLSchema#integer> <http://example.org/graph1> .\n\
//! <http://example.org/bob> <http://example.org/name> \"Bob\" <http://example.org/graph2> .\n";
//!
//! let parser = NQuadsParser::new();
//! let quads = parser.parse(Cursor::new(nquads_data))?;
//! assert_eq!(quads.len(), 3);
//!
//! // First quad is in default graph
//! assert!(quads[0].graph_name().is_default_graph());
//!
//! // Other quads are in named graphs
//! assert!(!quads[1].graph_name().is_default_graph());
//! assert!(!quads[2].graph_name().is_default_graph());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Iterator-Based Parsing
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let nquads_data = r#"
//! <http://example.org/s1> <http://example.org/p1> "value1" .
//! <http://example.org/s2> <http://example.org/p2> "value2" .
//! <http://example.org/s3> <http://example.org/p3> "value3" .
//! "#;
//!
//! let parser = NQuadsParser::new();
//! let mut count = 0;
//!
//! for result in parser.for_reader(Cursor::new(nquads_data)) {
//!     let quad = result?;
//!     println!("Quad: {} {} {}",
//!         quad.subject(), quad.predicate(), quad.object());
//!     count += 1;
//! }
//!
//! assert_eq!(count, 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Serialization
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsSerializer;
//! use oxirs_ttl::Serializer;
//! use oxirs_core::model::{NamedNode, Quad, GraphName};
//!
//! let serializer = NQuadsSerializer::new();
//! let quad = Quad::new(
//!     NamedNode::new("http://example.org/subject")?,
//!     NamedNode::new("http://example.org/predicate")?,
//!     NamedNode::new("http://example.org/object")?,
//!     GraphName::NamedNode(NamedNode::new("http://example.org/graph1")?)
//! );
//!
//! let mut output = Vec::new();
//! serializer.serialize(&vec![quad], &mut output)?;
//!
//! let nquads_string = String::from_utf8(output)?;
//! println!("{}", nquads_string);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Language Tags and Datatypes
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let nquads_data = "\
//! <http://example.org/doc> <http://example.org/title> \"Hello\"@en .\n\
//! <http://example.org/alice> <http://example.org/age> \"30\"^^<http://www.w3.org/2001/XMLSchema#integer> .\n\
//! <http://example.org/flag> <http://example.org/active> \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> .\n";
//!
//! let parser = NQuadsParser::new();
//! let quads = parser.parse(Cursor::new(nquads_data))?;
//! assert_eq!(quads.len(), 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Blank Nodes
//!
//! ```rust
//! use oxirs_ttl::nquads::NQuadsParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let nquads_data = r#"
//! _:alice <http://example.org/name> "Alice" .
//! _:alice <http://example.org/knows> _:bob .
//! _:bob <http://example.org/name> "Bob" .
//! "#;
//!
//! let parser = NQuadsParser::new();
//! let quads = parser.parse(Cursor::new(nquads_data))?;
//! assert_eq!(quads.len(), 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::error::{TextPosition, TurtleParseError, TurtleResult, TurtleSyntaxError};
use crate::toolkit::{Parser, Serializer};
use oxirs_core::model::{
    BlankNode, GraphName, Literal, NamedNode, Object, Predicate, Quad, Subject,
};
use std::io::{BufRead, BufReader, Read, Write};

/// N-Quads parser for parsing RDF quads from N-Quads format
///
/// N-Quads is a line-oriented RDF format that extends N-Triples with support
/// for named graphs. Each line contains exactly one quad (subject, predicate,
/// object, graph) or triple (when graph is omitted, using default graph).
///
/// # Examples
///
/// ```rust
/// use oxirs_ttl::nquads::NQuadsParser;
/// use oxirs_ttl::Parser;
/// use std::io::Cursor;
///
/// let nquads = "<http://example.org/s> <http://example.org/p> \"o\" <http://example.org/g> .";
/// let parser = NQuadsParser::new();
/// let quads = parser.parse(Cursor::new(nquads))?;
/// assert_eq!(quads.len(), 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct NQuadsParser;

impl NQuadsParser {
    /// Creates a new N-Quads parser
    pub fn new() -> Self {
        Self
    }

    /// Strip inline comments from a line (# after data, not inside quotes or IRIs)
    fn strip_inline_comment<'a>(&self, line: &'a str) -> &'a str {
        let mut in_string = false;
        let mut in_iri = false;
        let mut escaped = false;

        for (i, ch) in line.char_indices() {
            if escaped {
                escaped = false;
                continue;
            }

            match ch {
                '\\' if in_string => escaped = true,
                '"' => in_string = !in_string,
                '<' if !in_string => in_iri = true,
                '>' if !in_string => in_iri = false,
                '#' if !in_string && !in_iri => return line[..i].trim_end(),
                _ => {}
            }
        }

        line
    }

    /// Parse a single line of N-Quads format
    fn parse_line(&self, line: &str, line_num: usize) -> TurtleResult<Option<Quad>> {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            return Ok(None);
        }

        // Strip inline comments (# after the statement, not inside quotes)
        let line = self.strip_inline_comment(line);

        // Lines must end with '.'
        if !line.ends_with('.') {
            return Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: "N-Quads line must end with '.'".to_string(),
                position: TextPosition::new(line_num, line.len(), 0),
            }));
        }

        // Remove the trailing '.'
        let content = line[..line.len() - 1].trim();

        // Split into tokens (very simple tokenizer for N-Quads)
        let tokens = self.tokenize(content)?;

        if tokens.len() < 3 || tokens.len() > 4 {
            return Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!(
                    "N-Quads line must have 3 or 4 components, found {}",
                    tokens.len()
                ),
                position: TextPosition::new(line_num, 1, 0),
            }));
        }

        let subject = self.parse_subject(&tokens[0])?;
        let predicate = self.parse_predicate(&tokens[1])?;
        let object = self.parse_object(&tokens[2])?;

        let graph_name = if tokens.len() == 4 {
            self.parse_graph(&tokens[3])?
        } else {
            GraphName::DefaultGraph
        };

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

    /// Simple tokenizer for N-Quads format
    fn tokenize(&self, content: &str) -> TurtleResult<Vec<String>> {
        let mut tokens = Vec::new();
        let mut current_token = String::new();
        let mut in_string = false;
        let mut in_iri = false;
        let mut escape_next = false;

        for ch in content.chars() {
            if escape_next {
                current_token.push(ch);
                escape_next = false;
                continue;
            }

            match ch {
                '\\' if in_string => {
                    current_token.push('\\');
                    escape_next = true;
                }
                '"' => {
                    current_token.push('"');
                    in_string = !in_string;
                }
                '<' if !in_string => {
                    // Check if this is part of a typed literal (^^<IRI>)
                    // If current_token ends with ^^, keep building the same token
                    if !current_token.ends_with("^^") && !current_token.is_empty() {
                        tokens.push(current_token.clone());
                        current_token.clear();
                    }
                    current_token.push('<');
                    in_iri = true;
                }
                '>' if in_iri && !in_string => {
                    current_token.push('>');
                    in_iri = false;
                    // Only push token if we're not in the middle of a typed literal
                    // If the token starts with a quote, it's a literal with datatype
                    if !current_token.starts_with('"') {
                        tokens.push(current_token.clone());
                        current_token.clear();
                    }
                }
                ' ' | '\t' if !in_string && !in_iri => {
                    if !current_token.is_empty() {
                        tokens.push(current_token.clone());
                        current_token.clear();
                    }
                }
                _ => {
                    current_token.push(ch);
                }
            }
        }

        if !current_token.is_empty() {
            tokens.push(current_token);
        }

        Ok(tokens)
    }

    fn parse_subject(&self, token: &str) -> TurtleResult<Subject> {
        if token.starts_with('<') && token.ends_with('>') {
            let iri = &token[1..token.len() - 1];
            Ok(Subject::NamedNode(
                NamedNode::new(iri).map_err(TurtleParseError::model)?,
            ))
        } else if let Some(stripped) = token.strip_prefix("_:") {
            Ok(Subject::BlankNode(
                BlankNode::new(stripped).map_err(TurtleParseError::model)?,
            ))
        } else {
            Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid subject: {token}"),
                position: TextPosition::default(),
            }))
        }
    }

    fn parse_predicate(&self, token: &str) -> TurtleResult<NamedNode> {
        if token.starts_with('<') && token.ends_with('>') {
            let iri = &token[1..token.len() - 1];
            Ok(NamedNode::new(iri).map_err(TurtleParseError::model)?)
        } else {
            Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid predicate: {token}"),
                position: TextPosition::default(),
            }))
        }
    }

    fn parse_object(&self, token: &str) -> TurtleResult<Object> {
        if token.starts_with('<') && token.ends_with('>') {
            let iri = &token[1..token.len() - 1];
            Ok(Object::NamedNode(
                NamedNode::new(iri).map_err(TurtleParseError::model)?,
            ))
        } else if let Some(stripped) = token.strip_prefix("_:") {
            Ok(Object::BlankNode(
                BlankNode::new(stripped).map_err(TurtleParseError::model)?,
            ))
        } else if token.starts_with('"') {
            self.parse_literal(token)
        } else {
            Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid object: {token}"),
                position: TextPosition::default(),
            }))
        }
    }

    fn parse_graph(&self, token: &str) -> TurtleResult<GraphName> {
        if token.starts_with('<') && token.ends_with('>') {
            let iri = &token[1..token.len() - 1];
            Ok(GraphName::NamedNode(
                NamedNode::new(iri).map_err(TurtleParseError::model)?,
            ))
        } else if let Some(stripped) = token.strip_prefix("_:") {
            Ok(GraphName::BlankNode(
                BlankNode::new(stripped).map_err(TurtleParseError::model)?,
            ))
        } else {
            Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid graph name: {token}"),
                position: TextPosition::default(),
            }))
        }
    }

    fn parse_literal(&self, token: &str) -> TurtleResult<Object> {
        if !token.starts_with('"') {
            return Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: "Literal must start with quote".to_string(),
                position: TextPosition::default(),
            }));
        }

        // Find the closing quote (handling escapes) - use byte indices for proper UTF-8 handling
        let mut end_quote_byte_idx = None;
        let mut char_iter = token.char_indices().skip(1); // Skip opening quote

        while let Some((byte_idx, ch)) = char_iter.next() {
            if ch == '\\' {
                // Skip the escaped character
                char_iter.next();
            } else if ch == '"' {
                end_quote_byte_idx = Some(byte_idx);
                break;
            }
        }

        let end_quote_byte_idx = end_quote_byte_idx.ok_or_else(|| {
            TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: "Unterminated literal".to_string(),
                position: TextPosition::default(),
            })
        })?;

        // Use byte indices for slicing to properly handle UTF-8 multi-byte characters
        let value_with_escapes = &token[1..end_quote_byte_idx];
        let value = self.unescape_string(value_with_escapes)?;

        let remainder = &token[end_quote_byte_idx + 1..];

        if remainder.is_empty() {
            // Simple literal
            Ok(Object::Literal(Literal::new(value)))
        } else if let Some(lang) = remainder.strip_prefix('@') {
            // Language-tagged literal
            Ok(Object::Literal(
                Literal::new_language_tagged_literal(value, lang).map_err(|e| {
                    TurtleParseError::syntax(TurtleSyntaxError::Generic {
                        message: format!("Invalid language tag: {e}"),
                        position: TextPosition::default(),
                    })
                })?,
            ))
        } else if remainder.starts_with("^^") && remainder.len() > 2 {
            // Typed literal
            let datatype_token = &remainder[2..];
            if datatype_token.starts_with('<') && datatype_token.ends_with('>') {
                let datatype_iri = &datatype_token[1..datatype_token.len() - 1];
                let datatype = NamedNode::new(datatype_iri).map_err(TurtleParseError::model)?;
                Ok(Object::Literal(Literal::new_typed_literal(value, datatype)))
            } else {
                Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                    message: "Invalid datatype IRI".to_string(),
                    position: TextPosition::default(),
                }))
            }
        } else {
            Err(TurtleParseError::syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid literal format: {remainder}"),
                position: TextPosition::default(),
            }))
        }
    }

    fn unescape_string(&self, s: &str) -> TurtleResult<String> {
        let mut result = String::new();
        let mut chars = s.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '\\' {
                match chars.next() {
                    Some('\\') => result.push('\\'),
                    Some('"') => result.push('"'),
                    Some('n') => result.push('\n'),
                    Some('r') => result.push('\r'),
                    Some('t') => result.push('\t'),
                    Some('u') => {
                        // Unicode escape \uXXXX (4 hex digits)
                        let mut hex = String::new();
                        for _ in 0..4 {
                            if let Some(hex_char) = chars.next() {
                                hex.push(hex_char);
                            } else {
                                return Err(TurtleParseError::syntax(
                                    TurtleSyntaxError::InvalidEscape {
                                        sequence: format!("u{hex}"),
                                        position: TextPosition::default(),
                                    },
                                ));
                            }
                        }

                        let code_point = u32::from_str_radix(&hex, 16).map_err(|_| {
                            TurtleParseError::syntax(TurtleSyntaxError::InvalidEscape {
                                sequence: format!("u{hex}"),
                                position: TextPosition::default(),
                            })
                        })?;

                        let unicode_char = char::from_u32(code_point).ok_or_else(|| {
                            TurtleParseError::syntax(TurtleSyntaxError::InvalidUnicode {
                                codepoint: code_point,
                                position: TextPosition::default(),
                            })
                        })?;

                        result.push(unicode_char);
                    }
                    Some('U') => {
                        // Unicode escape \UXXXXXXXX (8 hex digits)
                        let mut hex = String::new();
                        for _ in 0..8 {
                            if let Some(hex_char) = chars.next() {
                                hex.push(hex_char);
                            } else {
                                return Err(TurtleParseError::syntax(
                                    TurtleSyntaxError::InvalidEscape {
                                        sequence: format!("U{hex}"),
                                        position: TextPosition::default(),
                                    },
                                ));
                            }
                        }

                        let code_point = u32::from_str_radix(&hex, 16).map_err(|_| {
                            TurtleParseError::syntax(TurtleSyntaxError::InvalidEscape {
                                sequence: format!("U{hex}"),
                                position: TextPosition::default(),
                            })
                        })?;

                        let unicode_char = char::from_u32(code_point).ok_or_else(|| {
                            TurtleParseError::syntax(TurtleSyntaxError::InvalidUnicode {
                                codepoint: code_point,
                                position: TextPosition::default(),
                            })
                        })?;

                        result.push(unicode_char);
                    }
                    Some(other) => {
                        return Err(TurtleParseError::syntax(TurtleSyntaxError::InvalidEscape {
                            sequence: other.to_string(),
                            position: TextPosition::default(),
                        }));
                    }
                    None => {
                        return Err(TurtleParseError::syntax(TurtleSyntaxError::InvalidEscape {
                            sequence: "".to_string(),
                            position: TextPosition::default(),
                        }));
                    }
                }
            } else {
                result.push(ch);
            }
        }

        Ok(result)
    }
}

impl Parser<Quad> for NQuadsParser {
    fn parse<R: Read>(&self, reader: R) -> TurtleResult<Vec<Quad>> {
        let mut quads = Vec::new();
        let buf_reader = BufReader::new(reader);

        for (line_num, line_result) in buf_reader.lines().enumerate() {
            let line = line_result.map_err(TurtleParseError::io)?;

            if let Some(quad) = self.parse_line(&line, line_num + 1)? {
                quads.push(quad)
            } // Empty line or comment
        }

        Ok(quads)
    }

    fn for_reader<R: BufRead + 'static>(
        &self,
        reader: R,
    ) -> Box<dyn Iterator<Item = TurtleResult<Quad>>> {
        Box::new(NQuadsIterator::new(reader))
    }
}

/// N-Quads serializer for writing RDF quads in N-Quads format
///
/// Serializes RDF quads into the N-Quads format, which is a line-oriented
/// format where each line represents one quad (subject, predicate, object, graph).
///
/// # Examples
///
/// ## Basic Serialization
///
/// ```rust
/// use oxirs_ttl::nquads::NQuadsSerializer;
/// use oxirs_ttl::Serializer;
/// use oxirs_core::model::{NamedNode, Quad, GraphName};
///
/// let serializer = NQuadsSerializer::new();
/// let quad = Quad::new(
///     NamedNode::new("http://example.org/subject")?,
///     NamedNode::new("http://example.org/predicate")?,
///     NamedNode::new("http://example.org/object")?,
///     GraphName::DefaultGraph
/// );
///
/// let mut output = Vec::new();
/// serializer.serialize(&vec![quad], &mut output)?;
/// let nquads_string = String::from_utf8(output)?;
/// assert!(nquads_string.contains("<http://example.org/subject>"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Serializing with Named Graphs
///
/// ```rust
/// use oxirs_ttl::nquads::NQuadsSerializer;
/// use oxirs_ttl::Serializer;
/// use oxirs_core::model::{NamedNode, Quad, GraphName, Literal};
///
/// let serializer = NQuadsSerializer::new();
/// let quad = Quad::new(
///     NamedNode::new("http://example.org/alice")?,
///     NamedNode::new("http://example.org/age")?,
///     Literal::new("30"),
///     GraphName::NamedNode(NamedNode::new("http://example.org/peopleGraph")?)
/// );
///
/// let mut output = Vec::new();
/// serializer.serialize_item(&quad, &mut output)?;
/// let nquads_string = String::from_utf8(output)?;
/// assert!(nquads_string.contains("<http://example.org/peopleGraph>"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct NQuadsSerializer;

impl Default for NQuadsSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl NQuadsSerializer {
    /// Creates a new N-Quads serializer
    pub fn new() -> Self {
        Self
    }

    fn format_subject(&self, subject: &Subject) -> String {
        match subject {
            Subject::NamedNode(n) => format!("<{}>", n.as_str()),
            Subject::BlankNode(b) => {
                format!("_:{}", b.as_str().strip_prefix("_:").unwrap_or(b.as_str()))
            }
            Subject::Variable(v) => format!("?{}", v.name()),
            Subject::QuotedTriple(_) => "<<quoted-triple>>".to_string(), // RDF-star support placeholder
        }
    }

    fn format_predicate(&self, predicate: &Predicate) -> String {
        match predicate {
            Predicate::NamedNode(n) => format!("<{}>", n.as_str()),
            Predicate::Variable(v) => format!("?{}", v.name()),
        }
    }

    fn format_object(&self, object: &Object) -> String {
        match object {
            Object::NamedNode(n) => format!("<{}>", n.as_str()),
            Object::BlankNode(b) => {
                format!("_:{}", b.as_str().strip_prefix("_:").unwrap_or(b.as_str()))
            }
            Object::Literal(l) => self.format_literal(l),
            Object::Variable(v) => format!("?{}", v.name()),
            Object::QuotedTriple(_) => "<<quoted-triple>>".to_string(), // RDF-star support placeholder
        }
    }

    fn format_graph(&self, graph: &GraphName) -> String {
        match graph {
            GraphName::NamedNode(n) => format!("<{}>", n.as_str()),
            GraphName::BlankNode(b) => {
                format!("_:{}", b.as_str().strip_prefix("_:").unwrap_or(b.as_str()))
            }
            GraphName::Variable(v) => format!("?{}", v.name()),
            GraphName::DefaultGraph => "<>".to_string(),
        }
    }

    fn format_literal(&self, literal: &Literal) -> String {
        let value = literal.value();
        let escaped = self.escape_string(value);

        if let Some(lang) = literal.language() {
            format!("\"{escaped}\"@{lang}")
        } else {
            let datatype = literal.datatype();
            if datatype.as_str() == "http://www.w3.org/2001/XMLSchema#string" {
                format!("\"{escaped}\"")
            } else {
                format!("\"{escaped}\"^^<{}>", datatype.as_str())
            }
        }
    }

    fn escape_string(&self, s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        for ch in s.chars() {
            match ch {
                '\\' => result.push_str("\\\\"),
                '\"' => result.push_str("\\\""),
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                c if c.is_control() => result.push_str(&format!("\\u{:04X}", c as u32)),
                c => result.push(c),
            }
        }
        result
    }
}

impl Serializer<Quad> for NQuadsSerializer {
    fn serialize<W: Write>(&self, quads: &[Quad], mut writer: W) -> TurtleResult<()> {
        for quad in quads {
            self.serialize_item(quad, &mut writer)?;
        }
        Ok(())
    }

    fn serialize_item<W: Write>(&self, quad: &Quad, mut writer: W) -> TurtleResult<()> {
        // Format: <subject> <predicate> <object> [<graph>] .
        write!(
            writer,
            "{} {} {}",
            self.format_subject(quad.subject()),
            self.format_predicate(quad.predicate()),
            self.format_object(quad.object())
        )
        .map_err(TurtleParseError::io)?;

        // Add graph if not default graph
        if !quad.graph_name().is_default_graph() {
            write!(writer, " {}", self.format_graph(quad.graph_name()))
                .map_err(TurtleParseError::io)?;
        }

        writeln!(writer, " .").map_err(TurtleParseError::io)?;
        Ok(())
    }
}

/// Iterator for parsing N-Quads from a buffered reader
pub struct NQuadsIterator<R: BufRead> {
    reader: R,
    parser: NQuadsParser,
    line_num: usize,
}

impl<R: BufRead> NQuadsIterator<R> {
    /// Creates a new N-Quads iterator from a reader
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            parser: NQuadsParser::new(),
            line_num: 0,
        }
    }
}

impl<R: BufRead> Iterator for NQuadsIterator<R> {
    type Item = TurtleResult<Quad>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut line = String::new();
        loop {
            line.clear();
            match self.reader.read_line(&mut line) {
                Ok(0) => return None, // EOF
                Ok(_) => {
                    self.line_num += 1;
                    match self.parser.parse_line(&line, self.line_num) {
                        Ok(Some(quad)) => return Some(Ok(quad)),
                        Ok(None) => continue, // Empty line or comment
                        Err(e) => return Some(Err(e)),
                    }
                }
                Err(e) => return Some(Err(TurtleParseError::io(e))),
            }
        }
    }
}

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

    #[test]
    fn test_parse_triple_in_default_graph() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> <http://example.org/o> .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        assert!(
            quads[0].graph_name().is_default_graph(),
            "quad without graph should be in default graph"
        );
    }

    #[test]
    fn test_parse_quad_with_named_graph() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> <http://example.org/o> <http://example.org/g> .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        assert!(
            !quads[0].graph_name().is_default_graph(),
            "quad with graph IRI should not be in default graph"
        );
    }

    #[test]
    fn test_parse_literal_object() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> \"hello\" .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        if let Object::Literal(lit) = quads[0].object() {
            assert_eq!(lit.value(), "hello");
        } else {
            panic!("expected string literal object");
        }
    }

    #[test]
    fn test_parse_language_tagged_literal() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> \"hello\"@en .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        if let Object::Literal(lit) = quads[0].object() {
            assert_eq!(lit.value(), "hello");
            assert_eq!(lit.language(), Some("en"));
        } else {
            panic!("expected language-tagged literal");
        }
    }

    #[test]
    fn test_parse_typed_literal() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> \"42\"^^<http://www.w3.org/2001/XMLSchema#integer> .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        if let Object::Literal(lit) = quads[0].object() {
            assert_eq!(lit.value(), "42");
            assert_eq!(
                lit.datatype().as_str(),
                "http://www.w3.org/2001/XMLSchema#integer"
            );
        } else {
            panic!("expected typed literal");
        }
    }

    #[test]
    fn test_parse_blank_node_subject() {
        let parser = NQuadsParser::new();
        let input = "_:b1 <http://example.org/p> <http://example.org/o> .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        assert!(
            matches!(quads[0].subject(), Subject::BlankNode(_)),
            "subject should be a blank node"
        );
    }

    #[test]
    fn test_parse_blank_node_object() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> _:b2 .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        assert!(
            matches!(quads[0].object(), Object::BlankNode(_)),
            "object should be a blank node"
        );
    }

    #[test]
    fn test_parse_multiple_quads() {
        let parser = NQuadsParser::new();
        let input = "\
<http://example.org/s1> <http://example.org/p> \"v1\" .\n\
<http://example.org/s2> <http://example.org/p> \"v2\" .\n\
<http://example.org/s3> <http://example.org/p> \"v3\" .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 3);
    }

    #[test]
    fn test_skip_empty_lines_and_comments() {
        let parser = NQuadsParser::new();
        let input = "\
# This is a comment\n\
\n\
<http://example.org/s> <http://example.org/p> \"v\" .\n\
\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
    }

    #[test]
    fn test_parse_error_missing_dot() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/s> <http://example.org/p> \"v\"\n";
        let result = parser.parse(Cursor::new(input));
        assert!(result.is_err(), "missing dot should produce an error");
    }

    #[test]
    fn test_serialize_quad_default_graph() {
        let serializer = NQuadsSerializer::new();
        let quad = Quad::new(
            NamedNode::new("http://example.org/s").expect("valid IRI"),
            NamedNode::new("http://example.org/p").expect("valid IRI"),
            NamedNode::new("http://example.org/o").expect("valid IRI"),
            GraphName::DefaultGraph,
        );
        let mut output = Vec::new();
        serializer
            .serialize(&[quad], &mut output)
            .expect("serialization should succeed");
        let out_str = String::from_utf8(output).expect("valid UTF-8");
        assert!(out_str.contains("<http://example.org/s>"));
        assert!(out_str.contains("<http://example.org/p>"));
        assert!(out_str.contains("<http://example.org/o>"));
        assert!(out_str.ends_with(".\n"));
    }

    #[test]
    fn test_serialize_quad_named_graph() {
        let serializer = NQuadsSerializer::new();
        let quad = Quad::new(
            NamedNode::new("http://example.org/s").expect("valid IRI"),
            NamedNode::new("http://example.org/p").expect("valid IRI"),
            NamedNode::new("http://example.org/o").expect("valid IRI"),
            GraphName::NamedNode(NamedNode::new("http://example.org/g").expect("valid IRI")),
        );
        let mut output = Vec::new();
        serializer
            .serialize(&[quad], &mut output)
            .expect("serialization should succeed");
        let out_str = String::from_utf8(output).expect("valid UTF-8");
        assert!(out_str.contains("<http://example.org/g>"));
    }

    #[test]
    fn test_for_reader_iterator() {
        let parser = NQuadsParser::new();
        let input = "\
<http://example.org/s1> <http://example.org/p> \"v1\" .\n\
<http://example.org/s2> <http://example.org/p> \"v2\" .\n";
        let quads: Vec<_> = parser
            .for_reader(Cursor::new(input))
            .collect::<Result<Vec<_>, _>>()
            .expect("for_reader should succeed");
        assert_eq!(quads.len(), 2);
    }

    #[test]
    fn test_parse_mixed_default_and_named_graphs() {
        let parser = NQuadsParser::new();
        let input = "\
<http://example.org/alice> <http://example.org/knows> <http://example.org/bob> .\n\
<http://example.org/alice> <http://example.org/age> \"30\" <http://example.org/graph1> .\n\
<http://example.org/bob> <http://example.org/name> \"Bob\" <http://example.org/graph2> .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 3);
        let default_count = quads
            .iter()
            .filter(|q| q.graph_name().is_default_graph())
            .count();
        assert_eq!(
            default_count, 1,
            "only first quad should be in default graph"
        );
    }

    #[test]
    fn test_subject_iri_roundtrip() {
        let parser = NQuadsParser::new();
        let input = "<http://example.org/subject> <http://example.org/p> \"value\" .\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("nquads parsing should succeed");
        assert_eq!(quads.len(), 1);
        if let Subject::NamedNode(nn) = quads[0].subject() {
            assert_eq!(nn.as_str(), "http://example.org/subject");
        } else {
            panic!("expected named node subject");
        }
    }
}