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
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
//! Tera template environment registration and text transformation helpers
//!
//! This module provides comprehensive text transformation filters and functions
//! for the Tera templating engine. It includes case conversion, string manipulation,
//! SPARQL query helpers, and context blessing for Hygen compatibility.
//!
//! ## Features
//!
//! - **Case Conversion**: camelCase, PascalCase, snake_case, kebab-case, and more
//! - **String Manipulation**: Pluralization, singularization, ordinalization
//! - **SPARQL Helpers**: Functions for working with SPARQL query results in templates
//! - **Context Blessing**: Auto-generate derived variables (Name, locals) for Hygen compatibility
//! - **Inflector Integration**: Full integration with the Inflector crate
//! - **Heck Integration**: Additional case conversion utilities from Heck
//!
//! ## Available Filters
//!
//! ### Case Conversion
//! - `camel` - camelCase
//! - `pascal` - PascalCase
//! - `snake` - snake_case
//! - `kebab` - kebab-case
//! - `class` - ClassCase
//! - `title` - Title Case
//! - `sentence` - Sentence case
//! - `train` - Train-Case
//! - `shouty_snake` - SCREAMING_SNAKE_CASE
//! - `shouty_kebab` - SCREAMING-KEBAB-CASE
//!
//! ### String Manipulation
//! - `pluralize` - Convert to plural form
//! - `singularize` - Convert to singular form
//! - `ordinalize` - Convert number to ordinal (1st, 2nd, 3rd)
//! - `deordinalize` - Remove ordinal suffix
//! - `foreign_key` - Generate foreign key name
//!
//! ### SPARQL Functions
//! - `sparql_column` - Extract a column from SPARQL results
//! - `sparql_row` - Get a specific row from SPARQL results
//! - `sparql_first` - Get first value from a column
//! - `sparql_values` - Get all values from a column
//! - `sparql_empty` - Check if results are empty
//! - `sparql_count` - Count results
//!
//! ## Examples
//!
//! ### Registering Filters
//!
//! ```rust
//! use crate::register::register_all;
//! use tera::Tera;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let mut tera = Tera::default();
//! register_all(&mut tera);
//!
//! // Now you can use filters in templates
//! let mut ctx = tera::Context::new();
//! ctx.insert("name", "hello_world");
//! let result = tera.render_str("{{ name | pascal }}", &ctx)?;
//! assert_eq!(result, "HelloWorld");
//! # Ok(())
//! # }
//! ```
//!
//! ### Context Blessing
//!
//! ```rust
//! use crate::register::bless_context;
//! use tera::Context;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let mut ctx = Context::new();
//! ctx.insert("name", "user_profile");
//!
//! bless_context(&mut ctx);
//!
//! // Name is auto-generated from name
//! assert_eq!(ctx.get("Name").unwrap().as_str().unwrap(), "UserProfile");
//! # Ok(())
//! # }
//! ```

use heck::{
    ToShoutyKebabCase,
    ToShoutySnakeCase,
    ToTitleCase, // supplemental only
};
use inflector::{
    cases::{
        camelcase, classcase, kebabcase, pascalcase, sentencecase, snakecase, titlecase, traincase,
    },
    numbers::{deordinalize, ordinalize},
    string::{deconstantize, demodulize, pluralize, singularize},
    suffix::foreignkey,
};
use std::collections::HashMap;
use tera::{Context, Result as TeraResult, Tera, Value};

/// Register all text transformation helpers into Tera.
pub fn register_all(tera: &mut Tera) {
    // ---------- Inflector canonical ----------
    reg_str(tera, "camel", camelcase::to_camel_case);
    reg_str(tera, "pascal", pascalcase::to_pascal_case);
    reg_str(tera, "snake", snakecase::to_snake_case);
    reg_str(tera, "kebab", kebabcase::to_kebab_case);
    reg_str(tera, "class", classcase::to_class_case);
    reg_str(tera, "title", titlecase::to_title_case);
    reg_str(tera, "sentence", sentencecase::to_sentence_case);
    reg_str(tera, "train", traincase::to_train_case);

    reg_str(tera, "pluralize", pluralize::to_plural);
    reg_str(tera, "singularize", singularize::to_singular);
    reg_str(tera, "deconstantize", deconstantize::deconstantize);
    reg_str(tera, "demodulize", demodulize::demodulize);

    reg_str(tera, "ordinalize", ordinalize::ordinalize);
    reg_str(tera, "deordinalize", deordinalize::deordinalize);

    reg_str(tera, "foreign_key", foreignkey::to_foreign_key);

    // ---------- Heck fill-ins (not in Inflector) ----------
    reg_str(tera, "shouty_snake", |s| s.to_shouty_snake_case());
    reg_str(tera, "shouty_kebab", |s| s.to_shouty_kebab_case());
    reg_str(tera, "titlecase", |s| s.to_title_case()); // better consistency

    // ---------- Common change-case style aliases ----------
    reg_str(tera, "param", kebabcase::to_kebab_case);
    reg_str(tera, "constant", |s| s.to_shouty_snake_case());
    reg_str(tera, "upper", |s| s.to_uppercase());
    reg_str(tera, "lower", |s| s.to_lowercase());
    reg_str(tera, "lcfirst", |s| {
        let mut c = s.chars();
        match c.next() {
            Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
            None => String::new(),
        }
    });
    reg_str(tera, "ucfirst", |s| {
        let mut c = s.chars();
        match c.next() {
            Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
            None => String::new(),
        }
    });

    tera.register_filter(
        "pad_right",
        |value: &tera::Value,
         args: &std::collections::HashMap<String, tera::Value>|
         -> tera::Result<tera::Value> {
            let s = match value.as_str() {
                Some(s) => s.to_string(),
                None => value.to_string(),
            };
            let width = args.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
            Ok(tera::Value::String(format!("{:<width$}", s, width = width)))
        },
    );

    // ---------- SPARQL projection helpers ----------
    register_sparql_helpers(tera);

    // ---------- Schema code generation filters ----------
    register_schema_filters(tera);
}

/// Auto-bless context variables for Hygen compatibility.
///
/// This function adds common derived variables to the context:
/// - `Name` = `name | pascal` (when `name` exists)
/// - `locals` = alias to the same context (for Hygen compatibility)
pub fn bless_context(context: &mut Context) {
    // Auto-bless Name when name exists
    if let Some(name_value) = context.get("name") {
        if let Some(name_str) = name_value.as_str() {
            let pascal_name = pascalcase::to_pascal_case(name_str);
            context.insert("Name", &pascal_name);
        }
    }

    // Add locals alias (Hygen compatibility)
    // In Hygen, locals is an alias to the context itself
    // We'll add it as a function that returns the context
    context.insert("locals", &HashMap::<String, Value>::new());
}

// ---------- SPARQL projection helpers ----------
fn register_sparql_helpers(tera: &mut Tera) {
    // Helper to get a specific column from SPARQL results
    tera.register_function("sparql_column", SparqlColumnFn);

    // Helper to get a specific row from SPARQL results
    tera.register_function("sparql_row", SparqlRowFn);

    // Helper to get the first value from a specific column
    tera.register_function("sparql_first", SparqlFirstFn);

    // Helper to get all values from a specific column
    tera.register_function("sparql_values", SparqlValuesFn);

    // Helper to check if SPARQL results are empty
    tera.register_function("sparql_empty", SparqlEmptyFn);

    // Helper to get the count of SPARQL results
    tera.register_function("sparql_count", SparqlCountFn);
}

// ---------- Schema code generation filters ----------
fn register_schema_filters(tera: &mut Tera) {
    // Register schema-to-code filters for all target languages
    tera.register_filter("schema_to_rust", schema_to_rust_filter);
    tera.register_filter("schema_to_go", schema_to_go_filter);
    tera.register_filter("schema_to_elixir", schema_to_elixir_filter);
    tera.register_filter("schema_to_java", schema_to_java_filter);
    tera.register_filter("schema_to_typescript", schema_to_typescript_filter);
}

/// Tera filter: convert schema string to Rust struct
/// Usage: {{ skill.input_type | schema_to_rust }}
fn schema_to_rust_filter(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
    let schema_str = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("schema_to_rust filter requires a string value"))?;

    // Parse the schema using the parser
    let result = crate::schema::SchemaParser::parse(schema_str)
        .map_err(|e| tera::Error::msg(format!("Failed to parse schema: {}", e)))?;

    // Generate Rust code
    let rust_code = crate::schema::generators::RustGenerator::generate(&result);

    Ok(Value::String(rust_code))
}

/// Tera filter: convert schema string to Go struct
/// Usage: {{ skill.input_type | schema_to_go }}
fn schema_to_go_filter(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
    let schema_str = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("schema_to_go filter requires a string value"))?;

    let result = crate::schema::SchemaParser::parse(schema_str)
        .map_err(|e| tera::Error::msg(format!("Failed to parse schema: {}", e)))?;

    let go_code = crate::schema::generators::GoGenerator::generate(&result);

    Ok(Value::String(go_code))
}

/// Tera filter: convert schema string to Elixir struct
/// Usage: {{ skill.input_type | schema_to_elixir }}
fn schema_to_elixir_filter(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
    let schema_str = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("schema_to_elixir filter requires a string value"))?;

    let result = crate::schema::SchemaParser::parse(schema_str)
        .map_err(|e| tera::Error::msg(format!("Failed to parse schema: {}", e)))?;

    let elixir_code = crate::schema::generators::ElixirGenerator::generate_struct(&result);

    Ok(Value::String(elixir_code))
}

/// Tera filter: convert schema string to Java class
/// Usage: {{ skill.input_type | schema_to_java }}
fn schema_to_java_filter(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
    let schema_str = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("schema_to_java filter requires a string value"))?;

    let result = crate::schema::SchemaParser::parse(schema_str)
        .map_err(|e| tera::Error::msg(format!("Failed to parse schema: {}", e)))?;

    let java_code = crate::schema::generators::JavaGenerator::generate_class(&result);

    Ok(Value::String(java_code))
}

/// Tera filter: convert schema string to TypeScript interface
/// Usage: {{ skill.input_type | schema_to_typescript }}
fn schema_to_typescript_filter(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> {
    let schema_str = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("schema_to_typescript filter requires a string value"))?;

    let result = crate::schema::SchemaParser::parse(schema_str)
        .map_err(|e| tera::Error::msg(format!("Failed to parse schema: {}", e)))?;

    let ts_code = crate::schema::generators::TypeScriptGenerator::generate_interface(&result);

    Ok(Value::String(ts_code))
}

#[derive(Clone)]
struct SparqlColumnFn;

impl tera::Function for SparqlColumnFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_column: results parameter required"))?;
        let column = args
            .get("column")
            .and_then(|v| v.as_str())
            .ok_or_else(|| tera::Error::msg("sparql_column: column parameter required"))?;

        if let Some(array) = results.as_array() {
            let mut column_values = Vec::new();
            for row in array {
                if let Some(obj) = row.as_object() {
                    // Try exact column name first
                    if let Some(value) = obj.get(column) {
                        column_values.push(value.clone());
                    } else {
                        // Try with ? prefix (SPARQL variable names)
                        let sparql_column = format!("?{}", column);
                        if let Some(value) = obj.get(&sparql_column) {
                            column_values.push(value.clone());
                        }
                    }
                }
            }
            Ok(Value::Array(column_values))
        } else {
            Ok(Value::Array(Vec::new()))
        }
    }
}

#[derive(Clone)]
struct SparqlRowFn;

impl tera::Function for SparqlRowFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_row: results parameter required"))?;
        let index = args
            .get("index")
            .and_then(|v| v.as_number())
            .and_then(|n| n.as_u64())
            .ok_or_else(|| tera::Error::msg("sparql_row: index parameter required"))?;

        if let Some(array) = results.as_array() {
            if let Some(row) = array.get(index as usize) {
                Ok(row.clone())
            } else {
                Ok(Value::Null)
            }
        } else {
            Ok(Value::Null)
        }
    }
}

#[derive(Clone)]
struct SparqlFirstFn;

impl tera::Function for SparqlFirstFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_first: results parameter required"))?;
        let column = args
            .get("column")
            .and_then(|v| v.as_str())
            .ok_or_else(|| tera::Error::msg("sparql_first: column parameter required"))?;

        if let Some(array) = results.as_array() {
            if let Some(first_row) = array.first() {
                if let Some(obj) = first_row.as_object() {
                    // Try exact column name first
                    if let Some(value) = obj.get(column) {
                        return Ok(value.clone());
                    }
                    // Try with ? prefix (SPARQL variable names)
                    let sparql_column = format!("?{}", column);
                    if let Some(value) = obj.get(&sparql_column) {
                        return Ok(value.clone());
                    }
                }
            }
        }
        Ok(Value::Null)
    }
}

#[derive(Clone)]
struct SparqlValuesFn;

impl tera::Function for SparqlValuesFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_values: results parameter required"))?;
        let column = args
            .get("column")
            .and_then(|v| v.as_str())
            .ok_or_else(|| tera::Error::msg("sparql_values: column parameter required"))?;

        if let Some(array) = results.as_array() {
            let mut values = Vec::new();
            for row in array {
                if let Some(obj) = row.as_object() {
                    // Try exact column name first
                    if let Some(value) = obj.get(column) {
                        if let Some(str_val) = value.as_str() {
                            values.push(Value::String(str_val.to_string()));
                        } else {
                            values.push(value.clone());
                        }
                    } else {
                        // Try with ? prefix (SPARQL variable names)
                        let sparql_column = format!("?{}", column);
                        if let Some(value) = obj.get(&sparql_column) {
                            if let Some(str_val) = value.as_str() {
                                values.push(Value::String(str_val.to_string()));
                            } else {
                                values.push(value.clone());
                            }
                        }
                    }
                }
            }
            Ok(Value::Array(values))
        } else {
            Ok(Value::Array(Vec::new()))
        }
    }
}

#[derive(Clone)]
struct SparqlEmptyFn;

impl tera::Function for SparqlEmptyFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_empty: results parameter required"))?;

        let is_empty = match results {
            Value::Array(arr) => arr.is_empty(),
            Value::Bool(_) => false, // Boolean results are never "empty"
            _ => true,
        };

        Ok(Value::Bool(is_empty))
    }
}

#[derive(Clone)]
struct SparqlCountFn;

impl tera::Function for SparqlCountFn {
    fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
        let results = args
            .get("results")
            .ok_or_else(|| tera::Error::msg("sparql_count: results parameter required"))?;

        let count = match results {
            Value::Array(arr) => arr.len(),
            Value::Bool(_) => 1, // Boolean results count as 1
            _ => 0,
        };

        Ok(Value::Number(tera::Number::from(count)))
    }
}

// ---------- internals ----------
fn reg_str<F>(tera: &mut Tera, name: &str, f: F)
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    tera.register_filter(
        name,
        move |v: &Value, _a: &HashMap<String, Value>| -> TeraResult<Value> {
            let input_str = match v.as_str() {
                Some(s) => s.to_string(),
                None => v.to_string(),
            };
            Ok(Value::String(f(&input_str)))
        },
    );
}

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

    fn create_test_tera() -> Tera {
        let mut tera = Tera::default();
        register_all(&mut tera);
        tera
    }

    #[test]
    fn test_case_conversions() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();
        ctx.insert("name", "hello_world_example");

        // Test camel case
        let result = tera.render_str("{{ name | camel }}", &ctx).unwrap();
        assert_eq!(result, "helloWorldExample");

        // Test pascal case
        let result = tera.render_str("{{ name | pascal }}", &ctx).unwrap();
        assert_eq!(result, "HelloWorldExample");

        // Test snake case
        let result = tera.render_str("{{ name | snake }}", &ctx).unwrap();
        assert_eq!(result, "hello_world_example");

        // Test kebab case
        let result = tera.render_str("{{ name | kebab }}", &ctx).unwrap();
        assert_eq!(result, "hello-world-example");

        // Test class case
        let result = tera.render_str("{{ name | class }}", &ctx).unwrap();
        assert_eq!(result, "HelloWorldExample");

        // Test title case
        let result = tera.render_str("{{ name | title }}", &ctx).unwrap();
        assert_eq!(result, "Hello World Example");

        // Test sentence case
        let result = tera.render_str("{{ name | sentence }}", &ctx).unwrap();
        assert_eq!(result, "Hello world example");

        // Test train case
        let result = tera.render_str("{{ name | train }}", &ctx).unwrap();
        assert_eq!(result, "Hello-World-Example");
    }

    #[test]
    fn test_heck_fill_ins() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();
        ctx.insert("name", "hello_world_example");

        // Test shouty snake case
        let result = tera.render_str("{{ name | shouty_snake }}", &ctx).unwrap();
        assert_eq!(result, "HELLO_WORLD_EXAMPLE");

        // Test shouty kebab case
        let result = tera.render_str("{{ name | shouty_kebab }}", &ctx).unwrap();
        assert_eq!(result, "HELLO-WORLD-EXAMPLE");

        // Test titlecase (heck version)
        let result = tera.render_str("{{ name | titlecase }}", &ctx).unwrap();
        assert_eq!(result, "Hello World Example");
    }

    #[test]
    fn test_ordinalization() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test ordinalize
        ctx.insert("num", "1");
        let result = tera.render_str("{{ num | ordinalize }}", &ctx).unwrap();
        assert_eq!(result, "1st");

        ctx.insert("num", "2");
        let result = tera.render_str("{{ num | ordinalize }}", &ctx).unwrap();
        assert_eq!(result, "2nd");

        ctx.insert("num", "3");
        let result = tera.render_str("{{ num | ordinalize }}", &ctx).unwrap();
        assert_eq!(result, "3rd");

        ctx.insert("num", "4");
        let result = tera.render_str("{{ num | ordinalize }}", &ctx).unwrap();
        assert_eq!(result, "4th");

        ctx.insert("num", "11");
        let result = tera.render_str("{{ num | ordinalize }}", &ctx).unwrap();
        assert_eq!(result, "11th");

        // Test deordinalize
        ctx.insert("num", "1st");
        let result = tera.render_str("{{ num | deordinalize }}", &ctx).unwrap();
        assert_eq!(result, "1");

        ctx.insert("num", "2nd");
        let result = tera.render_str("{{ num | deordinalize }}", &ctx).unwrap();
        assert_eq!(result, "2");
    }

    #[test]
    fn test_string_manipulation() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test deconstantize
        ctx.insert("path", "ActiveRecord::Base");
        let result = tera.render_str("{{ path | deconstantize }}", &ctx).unwrap();
        assert_eq!(result, "ActiveRecord");

        // Test demodulize
        ctx.insert("path", "ActiveRecord::Base");
        let result = tera.render_str("{{ path | demodulize }}", &ctx).unwrap();
        assert_eq!(result, "Base");

        // Test foreign_key
        ctx.insert("name", "Message");
        let result = tera.render_str("{{ name | foreign_key }}", &ctx).unwrap();
        assert_eq!(result, "message_id");
    }

    #[test]
    fn test_complex_combinations() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();
        ctx.insert("class_name", "UserProfile");

        // Test chaining transformations
        let result = tera
            .render_str("{{ class_name | snake | pluralize }}", &ctx)
            .unwrap();
        assert_eq!(result, "user_profiles");

        let result = tera
            .render_str("{{ class_name | kebab | shouty_kebab }}", &ctx)
            .unwrap();
        assert_eq!(result, "USER-PROFILE");

        let result = tera
            .render_str("{{ class_name | demodulize | snake }}", &ctx)
            .unwrap();
        assert_eq!(result, "user_profile");
    }

    #[test]
    fn test_edge_cases() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test empty string
        ctx.insert("empty", "");
        let result = tera.render_str("{{ empty | camel }}", &ctx).unwrap();
        assert_eq!(result, "");

        // Test single character
        ctx.insert("single", "A");
        let result = tera.render_str("{{ single | snake }}", &ctx).unwrap();
        assert_eq!(result, "a");

        // Test numbers
        ctx.insert("number", "123");
        let result = tera.render_str("{{ number | camel }}", &ctx).unwrap();
        assert_eq!(result, "123");

        // Test special characters
        ctx.insert("special", "hello@world#test");
        let result = tera.render_str("{{ special | kebab }}", &ctx).unwrap();
        assert_eq!(result, "hello-world-test");
    }

    #[test]
    fn test_non_string_input() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test with number
        ctx.insert("num", &42);
        let result = tera.render_str("{{ num | camel }}", &ctx).unwrap();
        assert_eq!(result, "42");

        // Test with boolean
        ctx.insert("flag", &true);
        let result = tera.render_str("{{ flag | snake }}", &ctx).unwrap();
        assert_eq!(result, "true");
    }

    #[test]
    fn test_real_world_scenarios() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test database table naming
        ctx.insert("model", "UserAccount");
        let table_name = tera
            .render_str("{{ model | snake | pluralize }}", &ctx)
            .unwrap();
        assert_eq!(table_name, "user_accounts");

        // Test API endpoint naming
        ctx.insert("resource", "UserProfile");
        let endpoint = tera
            .render_str("{{ resource | kebab | pluralize }}", &ctx)
            .unwrap();
        assert_eq!(endpoint, "user-profiles");

        // Test constant naming
        ctx.insert("name", "max_retry_count");
        let constant = tera.render_str("{{ name | shouty_snake }}", &ctx).unwrap();
        assert_eq!(constant, "MAX_RETRY_COUNT");

        // Test class method naming
        ctx.insert("action", "get_user_profile");
        let method = tera.render_str("{{ action | camel }}", &ctx).unwrap();
        assert_eq!(method, "getUserProfile");
    }

    #[test]
    fn test_change_case_aliases() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();
        ctx.insert("name", "hello_world_example");

        // Test param (kebab-case)
        let result = tera.render_str("{{ name | param }}", &ctx).unwrap();
        assert_eq!(result, "hello-world-example");

        // Test constant (SCREAMING_SNAKE_CASE)
        let result = tera.render_str("{{ name | constant }}", &ctx).unwrap();
        assert_eq!(result, "HELLO_WORLD_EXAMPLE");

        // Test upper
        let result = tera.render_str("{{ name | upper }}", &ctx).unwrap();
        assert_eq!(result, "HELLO_WORLD_EXAMPLE");

        // Test lower
        ctx.insert("name", "HELLO_WORLD_EXAMPLE");
        let result = tera.render_str("{{ name | lower }}", &ctx).unwrap();
        assert_eq!(result, "hello_world_example");

        // Test lcfirst
        ctx.insert("name", "HelloWorld");
        let result = tera.render_str("{{ name | lcfirst }}", &ctx).unwrap();
        assert_eq!(result, "helloWorld");

        // Test ucfirst
        ctx.insert("name", "helloWorld");
        let result = tera.render_str("{{ name | ucfirst }}", &ctx).unwrap();
        assert_eq!(result, "HelloWorld");

        // Test edge cases for lcfirst/ucfirst
        ctx.insert("name", "");
        let result = tera.render_str("{{ name | lcfirst }}", &ctx).unwrap();
        assert_eq!(result, "");

        let result = tera.render_str("{{ name | ucfirst }}", &ctx).unwrap();
        assert_eq!(result, "");

        // Test Unicode handling
        ctx.insert("name", "ñáéíóú");
        let result = tera.render_str("{{ name | ucfirst }}", &ctx).unwrap();
        assert_eq!(result, "Ñáéíóú");
    }

    #[test]
    fn test_all_filters_registered() {
        let mut tera = create_test_tera();

        // Test that all expected filters are registered
        let expected_filters = vec![
            "camel",
            "pascal",
            "snake",
            "kebab",
            "class",
            "title",
            "sentence",
            "train",
            "pluralize",
            "singularize",
            "deconstantize",
            "demodulize",
            "ordinalize",
            "deordinalize",
            "foreign_key",
            "shouty_snake",
            "shouty_kebab",
            "titlecase",
            "param",
            "constant",
            "upper",
            "lower",
            "lcfirst",
            "ucfirst",
        ];

        for filter in expected_filters {
            let mut ctx = Context::new();
            ctx.insert("test", "hello_world");

            // This should not panic if the filter is registered
            let result = tera.render_str(&format!("{{{{ test | {} }}}}", filter), &ctx);
            assert!(result.is_ok(), "Filter '{}' should be registered", filter);
        }
    }

    #[test]
    fn test_bless_context_name() {
        let mut ctx = Context::new();
        ctx.insert("name", "hello_world");

        bless_context(&mut ctx);

        // Should have Name auto-blessed
        assert_eq!(ctx.get("Name").unwrap().as_str().unwrap(), "HelloWorld");
        // Original name should still be there
        assert_eq!(ctx.get("name").unwrap().as_str().unwrap(), "hello_world");
    }

    #[test]
    fn test_bless_context_no_name() {
        let mut ctx = Context::new();
        ctx.insert("other", "value");

        bless_context(&mut ctx);

        // Should not have Name when name doesn't exist
        assert!(ctx.get("Name").is_none());
        // Should have locals placeholder
        assert!(ctx.get("locals").is_some());
    }

    #[test]
    fn test_bless_context_non_string_name() {
        let mut ctx = Context::new();
        ctx.insert("name", &42); // Non-string value

        bless_context(&mut ctx);

        // Should not bless Name for non-string values
        assert!(ctx.get("Name").is_none());
    }

    #[test]
    fn test_sparql_column_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Create mock SPARQL results
        let results = serde_json::json!([
            {"name": "Alice", "age": "30"},
            {"name": "Bob", "age": "25"},
            {"name": "Charlie", "age": "35"}
        ]);
        ctx.insert("results", &results);

        // Test extracting name column
        let result = tera
            .render_str(
                "{{ sparql_column(results=results, column=\"name\") }}",
                &ctx,
            )
            .unwrap();
        // Tera returns a string representation of the array
        assert_eq!(result, "[Alice, Bob, Charlie]");
    }

    #[test]
    fn test_sparql_row_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        let results = serde_json::json!([
            {"name": "Alice", "age": "30"},
            {"name": "Bob", "age": "25"}
        ]);
        ctx.insert("results", &results);

        // Test getting first row
        let result = tera
            .render_str("{{ sparql_row(results=results, index=0) }}", &ctx)
            .unwrap();
        assert_eq!(result, "[object]");

        // Test getting second row
        let result = tera
            .render_str("{{ sparql_row(results=results, index=1) }}", &ctx)
            .unwrap();
        assert_eq!(result, "[object]");

        // Test out of bounds
        let result = tera
            .render_str("{{ sparql_row(results=results, index=5) }}", &ctx)
            .unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_sparql_first_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        let results = serde_json::json!([
            {"name": "Alice", "age": "30"},
            {"name": "Bob", "age": "25"}
        ]);
        ctx.insert("results", &results);

        // Test getting first name
        let result = tera
            .render_str("{{ sparql_first(results=results, column=\"name\") }}", &ctx)
            .unwrap();
        assert_eq!(result, "Alice");

        // Test getting first age
        let result = tera
            .render_str("{{ sparql_first(results=results, column=\"age\") }}", &ctx)
            .unwrap();
        assert_eq!(result, "30");

        // Test non-existent column
        let result = tera
            .render_str(
                "{{ sparql_first(results=results, column=\"nonexistent\") }}",
                &ctx,
            )
            .unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_sparql_values_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        let results = serde_json::json!([
            {"name": "Alice", "age": "30"},
            {"name": "Bob", "age": "25"},
            {"name": "Charlie", "age": "35"}
        ]);
        ctx.insert("results", &results);

        // Test extracting all names
        let result = tera
            .render_str(
                "{{ sparql_values(results=results, column=\"name\") }}",
                &ctx,
            )
            .unwrap();
        assert_eq!(result, "[Alice, Bob, Charlie]");
    }

    #[test]
    fn test_sparql_empty_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test empty results
        let empty_results = serde_json::json!([]);
        ctx.insert("empty_results", &empty_results);
        let result = tera
            .render_str("{{ sparql_empty(results=empty_results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "true");

        // Test non-empty results
        let non_empty_results = serde_json::json!([
            {"name": "Alice", "age": "30"}
        ]);
        ctx.insert("non_empty_results", &non_empty_results);
        let result = tera
            .render_str("{{ sparql_empty(results=non_empty_results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "false");

        // Test boolean results
        let bool_results = serde_json::json!(true);
        ctx.insert("bool_results", &bool_results);
        let result = tera
            .render_str("{{ sparql_empty(results=bool_results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "false");
    }

    #[test]
    fn test_sparql_count_function() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        // Test counting results
        let results = serde_json::json!([
            {"name": "Alice", "age": "30"},
            {"name": "Bob", "age": "25"},
            {"name": "Charlie", "age": "35"}
        ]);
        ctx.insert("results", &results);
        let result = tera
            .render_str("{{ sparql_count(results=results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "3");

        // Test empty results
        let empty_results = serde_json::json!([]);
        ctx.insert("empty_results", &empty_results);
        let result = tera
            .render_str("{{ sparql_count(results=empty_results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "0");

        // Test boolean results
        let bool_results = serde_json::json!(true);
        ctx.insert("bool_results", &bool_results);
        let result = tera
            .render_str("{{ sparql_count(results=bool_results) }}", &ctx)
            .unwrap();
        assert_eq!(result, "1");
    }

    #[test]
    fn test_schema_to_rust_filter() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert(
            "schema",
            "FileReadRequest { path: string, offset?: integer }",
        );

        let result = tera
            .render_str("{{ schema | schema_to_rust }}", &ctx)
            .expect("schema_to_rust filter failed");

        assert!(result.contains("pub struct FileReadRequest"));
        assert!(result.contains("pub path: String"));
        assert!(result.contains("pub offset: Option<i64>"));
    }

    #[test]
    fn test_schema_to_go_filter() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert(
            "schema",
            "FileReadRequest { path: string, offset?: integer }",
        );

        let result = tera
            .render_str("{{ schema | schema_to_go }}", &ctx)
            .expect("schema_to_go filter failed");

        assert!(result.contains("type FileReadRequest struct"));
        assert!(result.contains("Path string"));
        assert!(result.contains("Offset int64"));
        assert!(result.contains("omitempty"));
    }

    #[test]
    fn test_schema_to_elixir_filter() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert(
            "schema",
            "FileReadRequest { path: string, offset?: integer }",
        );

        let result = tera
            .render_str("{{ schema | schema_to_elixir }}", &ctx)
            .expect("schema_to_elixir filter failed");

        assert!(result.contains("defmodule FileReadRequest"));
        assert!(result.contains("defstruct"));
    }

    #[test]
    fn test_schema_to_typescript_filter() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert(
            "schema",
            "FileReadRequest { path: string, offset?: integer }",
        );

        let result = tera
            .render_str("{{ schema | schema_to_typescript }}", &ctx)
            .expect("schema_to_typescript filter failed");

        assert!(result.contains("export interface FileReadRequest"));
        assert!(result.contains("path: string"));
        assert!(result.contains("offset?: number"));
    }

    #[test]
    fn test_schema_to_java_filter() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert(
            "schema",
            "FileReadRequest { path: string, offset?: integer }",
        );

        let result = tera
            .render_str("{{ schema | schema_to_java }}", &ctx)
            .expect("schema_to_java filter failed");

        assert!(result.contains("public class FileReadRequest"));
        assert!(result.contains("private String path"));
        assert!(result.contains("private Long offset"));
    }

    #[test]
    fn test_schema_filters_all_registered() {
        let mut tera = create_test_tera();
        let mut ctx = Context::new();

        ctx.insert("schema", "Test { field: string }");

        // Test that all schema filters are registered and work
        let filters = vec![
            "schema_to_rust",
            "schema_to_go",
            "schema_to_elixir",
            "schema_to_java",
            "schema_to_typescript",
        ];

        for filter in filters {
            let result = tera.render_str(&format!("{{{{ schema | {} }}}}", filter), &ctx);
            assert!(
                result.is_ok(),
                "Filter '{}' should be registered and working",
                filter
            );
        }
    }
}