ggen-core 26.7.2

Core graph-aware code generation engine
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
//! Type-safe SPARQL query builder with compile-time safety
//!
//! This module provides a type-safe SPARQL query builder that eliminates injection
//! vulnerabilities through:
//! - Type-state pattern with PhantomData for compile-time validation
//! - Automatic escaping of all user inputs via newtype wrappers
//! - Zero-cost abstractions (all methods inlined)
//! - Builder pattern for SELECT, CONSTRUCT, ASK, DESCRIBE queries
//!
//! ## Architecture
//!
//! The builder uses a type-state pattern with four states:
//! - `Building` - Initial state, can add prefixes and variables
//! - `WithVars` - Variables added, can add WHERE patterns
//! - `WithWhere` - WHERE clause added, can add filters/modifiers
//! - `Complete` - Query is complete and can be built
//!
//! ## Examples
//!
//! ### SELECT query with filter
//!
//! ```rust
//! use crate::rdf::query_builder::{SparqlQueryBuilder, Variable, Iri};
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let query = SparqlQueryBuilder::select()
//!     .prefix("ex", Iri::new("https://example.com/")?)
//!     .var(Variable::new("subject")?)
//!     .var(Variable::new("object")?)
//!     .where_pattern("?subject <http://example.com/predicate> ?object")
//!     .filter("?subject = <http://example.com/Entity>")
//!     .limit(100)
//!     .build()?;
//!
//! assert!(query.contains("SELECT"));
//! assert!(query.contains("?subject"));
//! # Ok(())
//! # }
//! ```
//!
//! ### CONSTRUCT query
//!
//! ```rust
//! use crate::rdf::query_builder::{SparqlQueryBuilder, Iri};
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let query = SparqlQueryBuilder::construct()
//!     .prefix("ex", Iri::new("https://example.com/")?)
//!     .construct_pattern("?s <http://example.com/new> ?o")
//!     .where_pattern("?s <http://example.com/old> ?o")
//!     .build()?;
//!
//! assert!(query.contains("CONSTRUCT"));
//! # Ok(())
//! # }
//! ```

use crate::utils::error::{Error, Result};
use std::marker::PhantomData;

/// Type-safe IRI wrapper with automatic validation and escaping
///
/// Prevents SPARQL injection by validating IRI format and escaping special characters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Iri(String);

impl Iri {
    /// Create a new IRI with validation
    ///
    /// # Arguments
    ///
    /// * `iri` - IRI string to validate
    ///
    /// # Errors
    ///
    /// Returns an error if the IRI contains invalid characters or format
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::rdf::query_builder::Iri;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let iri = Iri::new("https://example.com/resource")?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn new(iri: impl AsRef<str>) -> Result<Self> {
        let iri_str = iri.as_ref();

        // Validate IRI format - reject injection attempts
        if iri_str.contains(['<', '>', '"', '{', '}', '|', '^', '`', '\\']) {
            return Err(Error::new(&format!(
                "Invalid IRI format: contains forbidden characters: {}",
                iri_str
            )));
        }

        Ok(Self(iri_str.to_string()))
    }

    /// Get the IRI string
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe variable wrapper with validation
///
/// Prevents SPARQL injection by validating variable names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variable(String);

impl Variable {
    /// Create a new variable with validation
    ///
    /// # Arguments
    ///
    /// * `name` - Variable name (without leading ?)
    ///
    /// # Errors
    ///
    /// Returns an error if the variable name is invalid
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::rdf::query_builder::Variable;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let var = Variable::new("subject")?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn new(name: impl AsRef<str>) -> Result<Self> {
        let name_str = name.as_ref();

        // Remove leading ? if present
        let name_clean = name_str.strip_prefix('?').unwrap_or(name_str);

        // Validate variable name - must be alphanumeric with underscores
        if !name_clean.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return Err(Error::new(&format!(
                "Invalid variable name: {}. Must be alphanumeric with underscores.",
                name_str
            )));
        }

        if name_clean.is_empty() {
            return Err(Error::new("Variable name cannot be empty"));
        }

        Ok(Self(name_clean.to_string()))
    }

    /// Get the variable name with leading ?
    #[inline]
    pub fn as_str(&self) -> String {
        format!("?{}", self.0)
    }

    /// Get the variable name without leading ?
    #[inline]
    pub fn name(&self) -> &str {
        &self.0
    }
}

/// Type-safe literal wrapper with automatic escaping
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Literal(String);

impl Literal {
    /// Create a new literal with automatic escaping
    ///
    /// # Arguments
    ///
    /// * `value` - Literal value to escape
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::rdf::query_builder::Literal;
    ///
    /// let lit = Literal::new("Alice's value");
    /// assert!(lit.as_str().contains("Alice"));
    /// ```
    #[inline]
    pub fn new(value: impl AsRef<str>) -> Self {
        let escaped = value
            .as_ref()
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('\n', "\\n")
            .replace('\r', "\\r")
            .replace('\t', "\\t");

        Self(escaped)
    }

    /// Get the escaped literal value
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-state marker for building phase
#[derive(Debug)]
pub struct Building;

/// Type-state marker for SELECT queries with variables
#[derive(Debug)]
pub struct WithVars;

/// Type-state marker for queries with WHERE clause
#[derive(Debug)]
pub struct WithWhere;

/// Type-state marker for complete queries
#[derive(Debug)]
pub struct Complete;

/// Query type marker for SELECT
#[derive(Debug)]
pub struct Select;

/// Query type marker for CONSTRUCT
#[derive(Debug)]
pub struct Construct;

/// Query type marker for ASK
#[derive(Debug)]
pub struct Ask;

/// Query type marker for DESCRIBE
#[derive(Debug)]
pub struct Describe;

/// Type-safe SPARQL query builder
///
/// Uses type-state pattern to ensure queries are constructed correctly at compile time.
/// All methods are inlined for zero runtime overhead.
#[derive(Debug)]
pub struct SparqlQueryBuilder<Q, S> {
    query_type: PhantomData<Q>,
    state: PhantomData<S>,
    prefixes: Vec<(String, String)>,
    vars: Vec<String>,
    construct_patterns: Vec<String>,
    where_patterns: Vec<String>,
    filters: Vec<String>,
    order_by: Vec<String>,
    limit_value: Option<usize>,
    offset_value: Option<usize>,
    distinct: bool,
}

impl<Q, S> SparqlQueryBuilder<Q, S> {
    /// Add a prefix to the query
    ///
    /// # Arguments
    ///
    /// * `prefix` - Prefix name
    /// * `iri` - IRI for the prefix
    #[inline]
    pub fn prefix(mut self, prefix: impl AsRef<str>, iri: Iri) -> Self {
        self.prefixes
            .push((prefix.as_ref().to_string(), iri.as_str().to_string()));
        self
    }
}

impl SparqlQueryBuilder<Select, Building> {
    /// Create a new SELECT query builder
    ///
    /// # Examples
    ///
    /// ```rust
    /// use crate::rdf::query_builder::SparqlQueryBuilder;
    ///
    /// let builder = SparqlQueryBuilder::select();
    /// ```
    #[inline]
    pub fn select() -> Self {
        Self {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: Vec::new(),
            vars: Vec::new(),
            construct_patterns: Vec::new(),
            where_patterns: Vec::new(),
            filters: Vec::new(),
            order_by: Vec::new(),
            limit_value: None,
            offset_value: None,
            distinct: false,
        }
    }

    /// Add a variable to select
    ///
    /// # Arguments
    ///
    /// * `var` - Variable to select
    #[inline]
    pub fn var(mut self, var: Variable) -> SparqlQueryBuilder<Select, WithVars> {
        self.vars.push(var.as_str());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }

    /// Select all variables (SELECT *)
    #[inline]
    pub fn all_vars(mut self) -> SparqlQueryBuilder<Select, WithVars> {
        self.vars.push("*".to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }

    /// Make the query DISTINCT
    #[inline]
    pub fn distinct(mut self) -> Self {
        self.distinct = true;
        self
    }
}

impl SparqlQueryBuilder<Select, WithVars> {
    /// Add another variable to select
    #[inline]
    pub fn var(mut self, var: Variable) -> Self {
        self.vars.push(var.as_str());
        self
    }

    /// Add a WHERE pattern
    ///
    /// # Arguments
    ///
    /// * `pattern` - SPARQL pattern string
    #[inline]
    pub fn where_pattern(
        mut self, pattern: impl AsRef<str>,
    ) -> SparqlQueryBuilder<Select, WithWhere> {
        self.where_patterns.push(pattern.as_ref().to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }
}

impl SparqlQueryBuilder<Select, WithWhere> {
    /// Add another WHERE pattern
    #[inline]
    pub fn where_pattern(mut self, pattern: impl AsRef<str>) -> Self {
        self.where_patterns.push(pattern.as_ref().to_string());
        self
    }

    /// Add a FILTER clause
    ///
    /// # Arguments
    ///
    /// * `filter` - FILTER expression
    #[inline]
    pub fn filter(mut self, filter: impl AsRef<str>) -> Self {
        self.filters.push(filter.as_ref().to_string());
        self
    }

    /// Add an ORDER BY clause
    ///
    /// # Arguments
    ///
    /// * `var` - Variable to order by
    #[inline]
    pub fn order_by(mut self, var: Variable) -> Self {
        self.order_by.push(var.as_str());
        self
    }

    /// Add a LIMIT clause
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of results
    #[inline]
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit_value = Some(limit);
        self
    }

    /// Add an OFFSET clause
    ///
    /// # Arguments
    ///
    /// * `offset` - Number of results to skip
    #[inline]
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset_value = Some(offset);
        self
    }

    /// Build the final SPARQL query string
    ///
    /// # Errors
    ///
    /// Returns an error if the query cannot be constructed
    #[inline]
    pub fn build(self) -> Result<String> {
        let mut query = String::new();

        // Add prefixes
        for (prefix, iri) in &self.prefixes {
            query.push_str(&format!("PREFIX {}: <{}>\n", prefix, iri));
        }

        // Add SELECT clause
        if self.distinct {
            query.push_str("SELECT DISTINCT ");
        } else {
            query.push_str("SELECT ");
        }

        query.push_str(&self.vars.join(" "));
        query.push('\n');

        // Add WHERE clause
        query.push_str("WHERE {\n");
        for pattern in &self.where_patterns {
            query.push_str("  ");
            query.push_str(pattern);
            query.push_str(" .\n");
        }

        // Add FILTER clauses
        for filter in &self.filters {
            query.push_str("  FILTER (");
            query.push_str(filter);
            query.push_str(")\n");
        }

        query.push_str("}\n");

        // Add ORDER BY
        if !self.order_by.is_empty() {
            query.push_str("ORDER BY ");
            query.push_str(&self.order_by.join(" "));
            query.push('\n');
        }

        // Add LIMIT
        if let Some(limit) = self.limit_value {
            query.push_str(&format!("LIMIT {}\n", limit));
        }

        // Add OFFSET
        if let Some(offset) = self.offset_value {
            query.push_str(&format!("OFFSET {}\n", offset));
        }

        Ok(query)
    }
}

impl SparqlQueryBuilder<Construct, Building> {
    /// Create a new CONSTRUCT query builder
    #[inline]
    pub fn construct() -> Self {
        Self {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: Vec::new(),
            vars: Vec::new(),
            construct_patterns: Vec::new(),
            where_patterns: Vec::new(),
            filters: Vec::new(),
            order_by: Vec::new(),
            limit_value: None,
            offset_value: None,
            distinct: false,
        }
    }

    /// Add a CONSTRUCT pattern
    ///
    /// # Arguments
    ///
    /// * `pattern` - Triple pattern to construct
    #[inline]
    pub fn construct_pattern(
        mut self, pattern: impl AsRef<str>,
    ) -> SparqlQueryBuilder<Construct, WithVars> {
        self.construct_patterns.push(pattern.as_ref().to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }
}

impl SparqlQueryBuilder<Construct, WithVars> {
    /// Add another CONSTRUCT pattern
    #[inline]
    pub fn construct_pattern(mut self, pattern: impl AsRef<str>) -> Self {
        self.construct_patterns.push(pattern.as_ref().to_string());
        self
    }

    /// Add a WHERE pattern
    #[inline]
    pub fn where_pattern(
        mut self, pattern: impl AsRef<str>,
    ) -> SparqlQueryBuilder<Construct, WithWhere> {
        self.where_patterns.push(pattern.as_ref().to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }
}

impl SparqlQueryBuilder<Construct, WithWhere> {
    /// Add another WHERE pattern
    #[inline]
    pub fn where_pattern(mut self, pattern: impl AsRef<str>) -> Self {
        self.where_patterns.push(pattern.as_ref().to_string());
        self
    }

    /// Add a FILTER clause
    #[inline]
    pub fn filter(mut self, filter: impl AsRef<str>) -> Self {
        self.filters.push(filter.as_ref().to_string());
        self
    }

    /// Build the final SPARQL query string
    #[inline]
    pub fn build(self) -> Result<String> {
        let mut query = String::new();

        // Add prefixes
        for (prefix, iri) in &self.prefixes {
            query.push_str(&format!("PREFIX {}: <{}>\n", prefix, iri));
        }

        // Add CONSTRUCT clause
        query.push_str("CONSTRUCT {\n");
        for pattern in &self.construct_patterns {
            query.push_str("  ");
            query.push_str(pattern);
            query.push_str(" .\n");
        }
        query.push_str("}\n");

        // Add WHERE clause
        query.push_str("WHERE {\n");
        for pattern in &self.where_patterns {
            query.push_str("  ");
            query.push_str(pattern);
            query.push_str(" .\n");
        }

        // Add FILTER clauses
        for filter in &self.filters {
            query.push_str("  FILTER (");
            query.push_str(filter);
            query.push_str(")\n");
        }

        query.push_str("}\n");

        Ok(query)
    }
}

impl SparqlQueryBuilder<Ask, Building> {
    /// Create a new ASK query builder
    #[inline]
    pub fn ask() -> Self {
        Self {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: Vec::new(),
            vars: Vec::new(),
            construct_patterns: Vec::new(),
            where_patterns: Vec::new(),
            filters: Vec::new(),
            order_by: Vec::new(),
            limit_value: None,
            offset_value: None,
            distinct: false,
        }
    }

    /// Add a WHERE pattern
    #[inline]
    pub fn where_pattern(mut self, pattern: impl AsRef<str>) -> SparqlQueryBuilder<Ask, WithWhere> {
        self.where_patterns.push(pattern.as_ref().to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }
}

impl SparqlQueryBuilder<Ask, WithWhere> {
    /// Add another WHERE pattern
    #[inline]
    pub fn where_pattern(mut self, pattern: impl AsRef<str>) -> Self {
        self.where_patterns.push(pattern.as_ref().to_string());
        self
    }

    /// Add a FILTER clause
    #[inline]
    pub fn filter(mut self, filter: impl AsRef<str>) -> Self {
        self.filters.push(filter.as_ref().to_string());
        self
    }

    /// Build the final SPARQL query string
    #[inline]
    pub fn build(self) -> Result<String> {
        let mut query = String::new();

        // Add prefixes
        for (prefix, iri) in &self.prefixes {
            query.push_str(&format!("PREFIX {}: <{}>\n", prefix, iri));
        }

        // Add ASK clause
        query.push_str("ASK {\n");
        for pattern in &self.where_patterns {
            query.push_str("  ");
            query.push_str(pattern);
            query.push_str(" .\n");
        }

        // Add FILTER clauses
        for filter in &self.filters {
            query.push_str("  FILTER (");
            query.push_str(filter);
            query.push_str(")\n");
        }

        query.push_str("}\n");

        Ok(query)
    }
}

impl SparqlQueryBuilder<Describe, Building> {
    /// Create a new DESCRIBE query builder
    #[inline]
    pub fn describe() -> Self {
        Self {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: Vec::new(),
            vars: Vec::new(),
            construct_patterns: Vec::new(),
            where_patterns: Vec::new(),
            filters: Vec::new(),
            order_by: Vec::new(),
            limit_value: None,
            offset_value: None,
            distinct: false,
        }
    }

    /// Describe a resource by IRI
    #[inline]
    pub fn resource(mut self, iri: Iri) -> SparqlQueryBuilder<Describe, Complete> {
        self.vars.push(format!("<{}>", iri.as_str()));
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }

    /// Describe resources matching a variable
    #[inline]
    pub fn var(mut self, var: Variable) -> SparqlQueryBuilder<Describe, Complete> {
        self.vars.push(var.as_str());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }
}

impl SparqlQueryBuilder<Describe, Complete> {
    /// Add a WHERE clause to filter described resources
    #[inline]
    pub fn where_pattern(
        mut self, pattern: impl AsRef<str>,
    ) -> SparqlQueryBuilder<Describe, WithWhere> {
        self.where_patterns.push(pattern.as_ref().to_string());
        SparqlQueryBuilder {
            query_type: PhantomData,
            state: PhantomData,
            prefixes: self.prefixes,
            vars: self.vars,
            construct_patterns: self.construct_patterns,
            where_patterns: self.where_patterns,
            filters: self.filters,
            order_by: self.order_by,
            limit_value: self.limit_value,
            offset_value: self.offset_value,
            distinct: self.distinct,
        }
    }

    /// Build the final SPARQL query string
    #[inline]
    pub fn build(self) -> Result<String> {
        let mut query = String::new();

        // Add prefixes
        for (prefix, iri) in &self.prefixes {
            query.push_str(&format!("PREFIX {}: <{}>\n", prefix, iri));
        }

        // Add DESCRIBE clause
        query.push_str("DESCRIBE ");
        query.push_str(&self.vars.join(" "));
        query.push('\n');

        Ok(query)
    }
}

impl SparqlQueryBuilder<Describe, WithWhere> {
    /// Add another WHERE pattern
    #[inline]
    pub fn where_pattern(mut self, pattern: impl AsRef<str>) -> Self {
        self.where_patterns.push(pattern.as_ref().to_string());
        self
    }

    /// Build the final SPARQL query string
    #[inline]
    pub fn build(self) -> Result<String> {
        let mut query = String::new();

        // Add prefixes
        for (prefix, iri) in &self.prefixes {
            query.push_str(&format!("PREFIX {}: <{}>\n", prefix, iri));
        }

        // Add DESCRIBE clause
        query.push_str("DESCRIBE ");
        query.push_str(&self.vars.join(" "));
        query.push('\n');

        // Add WHERE clause
        query.push_str("WHERE {\n");
        for pattern in &self.where_patterns {
            query.push_str("  ");
            query.push_str(pattern);
            query.push_str(" .\n");
        }
        query.push_str("}\n");

        Ok(query)
    }
}

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

    #[test]
    fn test_iri_validation_rejects_injection() {
        // Arrange & Act
        let result = Iri::new("<malicious>");

        // Assert
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid IRI format"));
    }

    #[test]
    fn test_iri_validation_accepts_valid_iri() {
        // Arrange & Act
        let result = Iri::new("https://example.com/resource");

        // Assert
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "https://example.com/resource");
    }

    #[test]
    fn test_variable_validation_rejects_injection() {
        // Arrange & Act
        let result = Variable::new("var; DROP TABLE users;");

        // Assert
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid variable"));
    }

    #[test]
    fn test_variable_validation_accepts_valid_name() {
        // Arrange & Act
        let result = Variable::new("valid_var_123");

        // Assert
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "?valid_var_123");
    }

    #[test]
    fn test_variable_handles_leading_question_mark() {
        // Arrange & Act
        let result = Variable::new("?myvar");

        // Assert
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "?myvar");
    }

    #[test]
    fn test_literal_escapes_special_characters() {
        // Arrange & Act
        let lit = Literal::new("Alice's \"quote\" \n newline");

        // Assert
        assert!(lit.as_str().contains("Alice's"));
        assert!(lit.as_str().contains("\\\"quote\\\""));
        assert!(lit.as_str().contains("\\n"));
    }

    #[test]
    fn test_select_query_basic() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .var(Variable::new("subject").unwrap())
            .var(Variable::new("object").unwrap())
            .where_pattern("?subject <http://example.com/pred> ?object")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("SELECT ?subject ?object"));
        assert!(query.contains("WHERE {"));
        assert!(query.contains("?subject <http://example.com/pred> ?object"));
    }

    #[test]
    fn test_select_query_with_prefix() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .prefix("ex", Iri::new("https://example.com/").unwrap())
            .var(Variable::new("s").unwrap())
            .where_pattern("?s a ex:Entity")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("PREFIX ex: <https://example.com/>"));
        assert!(query.contains("SELECT ?s"));
    }

    #[test]
    fn test_select_query_with_filter() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .var(Variable::new("s").unwrap())
            .where_pattern("?s <http://example.com/name> ?name")
            .filter("?name = \"Alice\"")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("FILTER (?name = \"Alice\")"));
    }

    #[test]
    fn test_select_query_with_limit_and_offset() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .var(Variable::new("s").unwrap())
            .where_pattern("?s ?p ?o")
            .limit(100)
            .offset(50)
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("LIMIT 100"));
        assert!(query.contains("OFFSET 50"));
    }

    #[test]
    fn test_select_query_distinct() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .distinct()
            .var(Variable::new("s").unwrap())
            .where_pattern("?s ?p ?o")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("SELECT DISTINCT"));
    }

    #[test]
    fn test_select_all_vars() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .all_vars()
            .where_pattern("?s ?p ?o")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("SELECT *"));
    }

    #[test]
    fn test_construct_query() {
        // Arrange & Act
        let query = SparqlQueryBuilder::construct()
            .construct_pattern("?s <http://example.com/new> ?o")
            .where_pattern("?s <http://example.com/old> ?o")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("CONSTRUCT {"));
        assert!(query.contains("?s <http://example.com/new> ?o"));
        assert!(query.contains("WHERE {"));
        assert!(query.contains("?s <http://example.com/old> ?o"));
    }

    #[test]
    fn test_ask_query() {
        // Arrange & Act
        let query = SparqlQueryBuilder::ask()
            .where_pattern("?s <http://example.com/pred> ?o")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("ASK {"));
        assert!(query.contains("?s <http://example.com/pred> ?o"));
    }

    #[test]
    fn test_describe_query_with_iri() {
        // Arrange & Act
        let query = SparqlQueryBuilder::describe()
            .resource(Iri::new("http://example.com/alice").unwrap())
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("DESCRIBE <http://example.com/alice>"));
    }

    #[test]
    fn test_describe_query_with_var() {
        // Arrange & Act
        let query = SparqlQueryBuilder::describe()
            .var(Variable::new("s").unwrap())
            .where_pattern("?s a <http://example.com/Person>")
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("DESCRIBE ?s"));
        assert!(query.contains("WHERE {"));
    }

    #[test]
    fn test_order_by() {
        // Arrange & Act
        let query = SparqlQueryBuilder::select()
            .var(Variable::new("s").unwrap())
            .var(Variable::new("name").unwrap())
            .where_pattern("?s <http://example.com/name> ?name")
            .order_by(Variable::new("name").unwrap())
            .build()
            .unwrap();

        // Assert
        assert!(query.contains("ORDER BY ?name"));
    }
}