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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::needless_raw_string_hashes,
    clippy::duration_suboptimal_units,
    clippy::branches_sharing_code,
    clippy::used_underscore_binding,
    clippy::single_char_pattern,
    clippy::ignore_without_reason,
    clippy::cloned_ref_to_slice_refs,
    clippy::doc_overindented_list_items,
    clippy::match_wildcard_for_single_variants,
    clippy::ignored_unit_patterns,
    clippy::needless_collect,
    clippy::unnecessary_map_or,
    clippy::manual_flatten,
    clippy::manual_strip,
    clippy::future_not_send,
    clippy::unnested_or_patterns,
    clippy::no_effect_underscore_binding,
    clippy::literal_string_with_formatting_args
)]
//! Conditional execution tests (T019) - Chicago School TDD
//!
//! Tests the rule conditional execution functionality (`when` field in generation rules).
//!
//! ## Coverage
//! - Rule executed when SPARQL ASK returns true
//! - Rule skipped when SPARQL ASK returns false
//! - Rule executed when no condition specified
//! - Malformed SPARQL ASK queries handled gracefully
//! - Multiple conditions work correctly
//! - Condition evaluation integrates with pipeline

use ggen_core::codegen::pipeline::GenerationPipeline;
use ggen_core::manifest::{
    GenerationConfig, GenerationMode, GenerationRule, GgenManifest, InferenceConfig,
    OntologyConfig, ProjectConfig, QuerySource, TemplateSource, ValidationConfig,
};
use std::collections::BTreeMap;
use std::path::PathBuf;
use tempfile::TempDir;

// ============================================================================
// T025.1: test_rule_executed_when_ask_true
// ============================================================================

#[test]
fn test_rule_executed_when_ask_true() {
    // Arrange: Create rule with condition that evaluates to true
    let rule = GenerationRule {
        name: "conditional_rule".to_string(),
        query: QuerySource::Inline {
            inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Generated code".to_string(),
        },
        output_file: "output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: false,
        when: None,
    };

    // Note: In ggen v26_5_19, conditions are part of the rule definition
    // This test validates the rule structure can be created
    assert_eq!(rule.name, "conditional_rule", "Rule name should match");
    assert_eq!(rule.mode, GenerationMode::Create, "Mode should be Create");
}

// ============================================================================
// T025.2: test_rule_skipped_when_ask_false
// ============================================================================

#[test]
fn test_rule_skipped_when_ask_false() {
    // Arrange: Create rule with condition that evaluates to false
    let rule = GenerationRule {
        name: "skipped_rule".to_string(),
        query: QuerySource::Inline {
            inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Should not generate".to_string(),
        },
        output_file: "skipped_output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: false,
        when: None,
    };

    // Note: In ggen v26_5_19, skip_empty controls whether generation runs on empty queries
    // This test validates the skip_empty flag
    assert!(
        !rule.skip_empty,
        "Rule should not skip on empty results by default"
    );
    assert_eq!(rule.name, "skipped_rule", "Rule name should match");
}

// ============================================================================
// T025.3: test_rule_executed_when_no_condition
// ============================================================================

#[test]
fn test_rule_executed_when_no_condition() {
    // Arrange: Create rule without condition (unconditional execution)
    let rule = GenerationRule {
        name: "unconditional_rule".to_string(),
        query: QuerySource::Inline {
            inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Always generated".to_string(),
        },
        output_file: "always_output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: false,
        when: None,
    };

    // Assert: Rule should always execute (no skip_empty restriction)
    assert!(
        !rule.skip_empty,
        "Rule should not skip on empty (always execute)"
    );
    assert_eq!(rule.name, "unconditional_rule", "Rule name should match");
}

// ============================================================================
// T025.4: test_malformed_sparql_handled
// ============================================================================

#[test]
fn test_malformed_sparql_handled() {
    // Arrange: Create rule with malformed SPARQL condition
    let rule_invalid_syntax = GenerationRule {
        name: "malformed_rule".to_string(),
        query: QuerySource::Inline {
            inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Code".to_string(),
        },
        output_file: "output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: false,
        when: None,
    };

    // Note: Malformed SPARQL would be caught during pipeline execution
    // This test verifies the rule structure can be created
    // (Query validation happens at runtime, not construction time)
    assert_eq!(
        rule_invalid_syntax.name, "malformed_rule",
        "Rule should be created"
    );

    // Test inline query with malformed SPARQL
    if let QuerySource::Inline { inline } = &rule_invalid_syntax.query {
        // Validation would fail at runtime, but structure is valid
        assert!(!inline.is_empty(), "Query should have content");
    } else {
        panic!("Expected inline query");
    }
}

// ============================================================================
// T025.5: test_condition_logging
// ============================================================================

#[test]
fn test_condition_logging() {
    // Arrange: Create manifest with conditional rules for logging
    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "condition_test".to_string(),
            version: "1.0.0".to_string(),
            description: Some("Testing conditional execution logging".to_string()),
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: PathBuf::from("ontology.ttl"),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![
                GenerationRule {
                    name: "rule_with_condition".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Generated".to_string(),
                    },
                    output_file: "output.rs".to_string(),
                    mode: GenerationMode::Create,
                    skip_empty: true, // Skip if query returns empty
                    when: None,
                },
                GenerationRule {
                    name: "rule_without_condition".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Always generated".to_string(),
                    },
                    output_file: "always.rs".to_string(),
                    mode: GenerationMode::Create,
                    skip_empty: false, // Always generate
                    when: None,
                },
            ],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: PathBuf::from("generated"),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Assert: Manifest has mixed skip_empty rules
    assert_eq!(manifest.generation.rules.len(), 2, "Should have 2 rules");
    assert!(
        manifest.generation.rules[0].skip_empty,
        "First rule should skip on empty"
    );
    assert!(
        !manifest.generation.rules[1].skip_empty,
        "Second rule should never skip"
    );
}

// ============================================================================
// T025.6: test_multiple_conditions_in_manifest
// ============================================================================

#[test]
fn test_multiple_conditions_in_manifest() {
    // Arrange: Manifest with multiple conditional rules (using skip_empty)
    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "multi_condition_test".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: PathBuf::from("ontology.ttl"),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![
                GenerationRule {
                    name: "rule1".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 1".to_string(),
                    },
                    output_file: "output1.rs".to_string(),
                    mode: GenerationMode::Create,
                    skip_empty: true, // Conditional: skip on empty
                    when: None,
                },
                GenerationRule {
                    name: "rule2".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 2".to_string(),
                    },
                    output_file: "output2.rs".to_string(),
                    mode: GenerationMode::Create,
                    skip_empty: true, // Conditional: skip on empty
                    when: None,
                },
                GenerationRule {
                    name: "rule3".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 3".to_string(),
                    },
                    output_file: "output3.rs".to_string(),
                    mode: GenerationMode::Create,
                    skip_empty: false, // Unconditional
                    when: None,
                },
            ],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: PathBuf::from("generated"),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Assert: Rules have different skip_empty settings
    let rules = &manifest.generation.rules;
    assert_eq!(rules.len(), 3, "Should have 3 rules");

    // Assert: Rule 1 skips on empty
    assert!(rules[0].skip_empty, "Rule 1 should skip on empty");

    // Assert: Rule 2 skips on empty
    assert!(rules[1].skip_empty, "Rule 2 should skip on empty");

    // Assert: Rule 3 is unconditional (never skips)
    assert!(!rules[2].skip_empty, "Rule 3 should never skip");
}

// ============================================================================
// T025.7: test_complex_ask_queries
// ============================================================================

#[test]
fn test_complex_sparql_queries() {
    // Arrange: Rule with complex SPARQL query (multiple patterns)
    let rule = GenerationRule {
        name: "complex_query".to_string(),
        query: QuerySource::Inline {
            inline: r#"SELECT ?s ?prop WHERE {
                ?s a <http://example.org/Entity> .
                ?s <http://example.org/hasProperty> ?prop .
                FILTER(?prop > 10)
            }"#
            .to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Complex query result: {{s}} has property {{prop}}".to_string(),
        },
        output_file: "output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: true, // Skip if no entities match filter
        when: None,
    };

    // Assert: Complex query is preserved
    if let QuerySource::Inline { inline } = &rule.query {
        assert!(inline.contains("SELECT"), "Should be SELECT query");
        assert!(inline.contains("FILTER"), "Should have FILTER clause");
        assert!(
            inline.contains("hasProperty"),
            "Should have property pattern"
        );
        assert!(inline.contains("> 10"), "Should have filter condition");
    } else {
        panic!("Expected inline query");
    }
    assert!(
        rule.skip_empty,
        "Should skip if query returns empty (after filter)"
    );
}

// ============================================================================
// T025.8: test_condition_with_prefixes
// ============================================================================

#[test]
fn test_query_with_prefixes() {
    // Arrange: Rule with prefixed SELECT query
    let rule = GenerationRule {
        name: "prefixed_query".to_string(),
        query: QuerySource::Inline {
            inline: r#"PREFIX ex: <http://example.org/>
               SELECT ?s WHERE { ?s a ex:Type }"#
                .to_string(),
        },
        template: TemplateSource::Inline {
            inline: "// Prefixed query result: {{s}}".to_string(),
        },
        output_file: "output.rs".to_string(),
        mode: GenerationMode::Create,
        skip_empty: false,
        when: None,
    };

    // Assert: Prefixed query is preserved
    if let QuerySource::Inline { inline } = &rule.query {
        assert!(inline.contains("PREFIX"), "Should have PREFIX declaration");
        assert!(inline.contains("ex:Type"), "Should use prefix in pattern");
    } else {
        panic!("Expected inline query");
    }
}

// ============================================================================
// Integration Tests - T019: SPARQL ASK Conditional Execution
// ============================================================================

/// Helper: Create test ontology with sample data
fn create_test_ontology() -> String {
    r#"
@prefix ex: <http://example.org/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

ex:Entity1 a ex:Type ;
    ex:hasProperty "value1" ;
    ex:enabled true .

ex:Entity2 a ex:Type ;
    ex:hasProperty "value2" ;
    ex:enabled false .
"#
    .to_string()
}

#[test]
fn test_integration_rule_executed_when_ask_true() {
    // Arrange: Create manifest with rule that has WHEN condition evaluating to true
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let ontology_path = temp_dir.path().join("ontology.ttl");
    std::fs::write(&ontology_path, create_test_ontology()).expect("Failed to write ontology");

    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "conditional_test".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: ontology_path.clone(),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![GenerationRule {
                name: "conditional_rule".to_string(),
                query: QuerySource::Inline {
                    inline: "PREFIX ex: <http://example.org/>\nSELECT ?s ?prop WHERE { ?s a ex:Type . ?s ex:hasProperty ?prop }".to_string(),
                },
                template: TemplateSource::Inline {
                    inline: "// Entity: {{s}}, Property: {{prop}}".to_string(),
                },
                output_file: "output.txt".to_string(),
                mode: GenerationMode::Overwrite,
                skip_empty: false,
                // WHEN condition: Check if there are any ex:Type entities (should be true)
                when: Some("PREFIX ex: <http://example.org/>\nASK { ?s a ex:Type }".to_string()),
            }],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: temp_dir.path().to_path_buf(),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Act: Execute pipeline
    let mut pipeline = GenerationPipeline::new(manifest, temp_dir.path().to_path_buf());
    let result = pipeline.run();

    // Assert: Pipeline succeeded and file was generated
    assert!(result.is_ok(), "Pipeline should succeed");
    let state = result.expect("Pipeline state");

    // Assert: A file was generated because the WHEN condition was true.
    // The output_file ("output.txt") is STATIC (no `{{ }}` placeholder), so the
    // pipeline renders ONCE with all SPARQL rows in context (see the static-vs-dynamic
    // output handling in codegen/pipeline.rs). The two entity rows therefore produce a
    // single combined file, not one file per row.
    assert_eq!(
        state.generated_files.len(),
        1,
        "Static output_file renders once with all rows -> exactly 1 file when condition is true"
    );

    let output_path = temp_dir.path().join("output.txt");
    assert!(
        output_path.exists(),
        "Output file should exist when condition is true"
    );
}

#[test]
fn test_integration_rule_skipped_when_ask_false() {
    // Arrange: Create manifest with rule that has WHEN condition evaluating to false
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let ontology_path = temp_dir.path().join("ontology.ttl");
    std::fs::write(&ontology_path, create_test_ontology()).expect("Failed to write ontology");

    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "skip_test".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: ontology_path.clone(),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![GenerationRule {
                name: "skipped_rule".to_string(),
                query: QuerySource::Inline {
                    inline: "PREFIX ex: <http://example.org/>\nSELECT ?s WHERE { ?s a ex:Type }"
                        .to_string(),
                },
                template: TemplateSource::Inline {
                    inline: "// Should not generate".to_string(),
                },
                output_file: "skipped.txt".to_string(),
                mode: GenerationMode::Overwrite,
                skip_empty: false,
                // WHEN condition: Check for non-existent type (should be false)
                when: Some(
                    "PREFIX ex: <http://example.org/>\nASK { ?s a ex:NonExistentType }".to_string(),
                ),
            }],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: temp_dir.path().to_path_buf(),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Act: Execute pipeline
    let mut pipeline = GenerationPipeline::new(manifest, temp_dir.path().to_path_buf());
    let result = pipeline.run();

    // Assert: Pipeline succeeded but no file was generated
    assert!(result.is_ok(), "Pipeline should succeed");
    let state = result.expect("Pipeline state");

    // Assert: No file was generated (condition was false)
    assert_eq!(
        state.generated_files.len(),
        0,
        "Should generate 0 files when condition is false"
    );

    let output_path = temp_dir.path().join("skipped.txt");
    assert!(
        !output_path.exists(),
        "Output file should NOT exist when condition is false"
    );
}

#[test]
fn test_integration_malformed_ask_query_error() {
    // Arrange: Create manifest with malformed SPARQL ASK query
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let ontology_path = temp_dir.path().join("ontology.ttl");
    std::fs::write(&ontology_path, create_test_ontology()).expect("Failed to write ontology");

    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "malformed_test".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: ontology_path.clone(),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![GenerationRule {
                name: "malformed_rule".to_string(),
                query: QuerySource::Inline {
                    inline: "SELECT * WHERE { ?s ?p ?o }".to_string(),
                },
                template: TemplateSource::Inline {
                    inline: "// Should not execute".to_string(),
                },
                output_file: "output.txt".to_string(),
                mode: GenerationMode::Overwrite,
                skip_empty: false,
                // WHEN condition: Malformed SPARQL (not an ASK query)
                when: Some("SELECT ?s WHERE { ?s ?p ?o }".to_string()),
            }],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: temp_dir.path().to_path_buf(),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Act: Execute pipeline
    let mut pipeline = GenerationPipeline::new(manifest, temp_dir.path().to_path_buf());
    let result = pipeline.run();

    // Assert: Pipeline should fail with helpful error message
    assert!(
        result.is_err(),
        "Pipeline should fail on malformed ASK query"
    );

    let error_msg = match result {
        Err(e) => e.to_string(),
        Ok(_) => panic!("Expected error but got success"),
    };

    // Assert: Error message mentions it must be an ASK query
    assert!(
        error_msg.contains("ASK") || error_msg.contains("must be ASK query"),
        "Error should mention ASK query requirement, got: {}",
        error_msg
    );
}

#[test]
fn test_integration_multiple_conditions() {
    // Arrange: Create manifest with multiple rules having different conditions
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let ontology_path = temp_dir.path().join("ontology.ttl");
    std::fs::write(&ontology_path, create_test_ontology()).expect("Failed to write ontology");

    let manifest = GgenManifest {
        project: ProjectConfig {
            name: "multi_condition_test".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            ..Default::default()
        },
        ontology: OntologyConfig {
            source: ontology_path.clone(),
            imports: vec![],
            base_iri: None,
            prefixes: BTreeMap::new(),
            ..Default::default()
        },
        inference: InferenceConfig {
            rules: vec![],
            max_reasoning_timeout_ms: 5000,
        },
        generation: GenerationConfig {
            rules: vec![
                // Rule 1: Condition TRUE - should execute
                GenerationRule {
                    name: "rule1_executes".to_string(),
                    query: QuerySource::Inline {
                        inline:
                            "PREFIX ex: <http://example.org/>\nSELECT ?s WHERE { ?s a ex:Type }"
                                .to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 1 executed".to_string(),
                    },
                    output_file: "rule1.txt".to_string(),
                    mode: GenerationMode::Overwrite,
                    skip_empty: false,
                    when: Some(
                        "PREFIX ex: <http://example.org/>\nASK { ?s a ex:Type }".to_string(),
                    ),
                },
                // Rule 2: Condition FALSE - should skip
                GenerationRule {
                    name: "rule2_skipped".to_string(),
                    query: QuerySource::Inline {
                        inline: "SELECT ?s WHERE { ?s ?p ?o }".to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 2 should not execute".to_string(),
                    },
                    output_file: "rule2.txt".to_string(),
                    mode: GenerationMode::Overwrite,
                    skip_empty: false,
                    when: Some(
                        "PREFIX ex: <http://example.org/>\nASK { ?s a ex:NonExistent }".to_string(),
                    ),
                },
                // Rule 3: No condition - always execute
                GenerationRule {
                    name: "rule3_always".to_string(),
                    query: QuerySource::Inline {
                        inline:
                            "PREFIX ex: <http://example.org/>\nSELECT ?s WHERE { ?s a ex:Type }"
                                .to_string(),
                    },
                    template: TemplateSource::Inline {
                        inline: "// Rule 3 always executed".to_string(),
                    },
                    output_file: "rule3.txt".to_string(),
                    mode: GenerationMode::Overwrite,
                    skip_empty: false,
                    when: None, // No condition
                },
            ],
            max_sparql_timeout_ms: 5000,
            require_audit_trail: false,
            enable_llm: false,
            llm_provider: None,
            llm_model: None,
            determinism_salt: None,
            output_dir: temp_dir.path().to_path_buf(),
        },
        validation: ValidationConfig::default(),
        packs: vec![],
        ..Default::default()
    };

    // Act: Execute pipeline
    let mut pipeline = GenerationPipeline::new(manifest, temp_dir.path().to_path_buf());
    let result = pipeline.run();

    // Assert: Pipeline succeeded
    assert!(result.is_ok(), "Pipeline should succeed");
    let state = result.expect("Pipeline state");

    // Assert: 2 files generated. Each rule's output_file is STATIC (rule1.txt /
    // rule3.txt), so each renders ONCE with all rows -> one file per executed rule
    // (rule1: 1, rule3: 1, rule2 skipped). See static-output handling in pipeline.rs.
    assert_eq!(
        state.generated_files.len(),
        2,
        "Static outputs render once per rule -> rule1: 1, rule3: 1, rule2 skipped = 2 files"
    );

    // Assert: Rule 1 file exists (condition was true)
    let rule1_path = temp_dir.path().join("rule1.txt");
    assert!(rule1_path.exists(), "Rule 1 output should exist");

    // Assert: Rule 2 file does NOT exist (condition was false)
    let rule2_path = temp_dir.path().join("rule2.txt");
    assert!(!rule2_path.exists(), "Rule 2 output should NOT exist");

    // Assert: Rule 3 file exists (no condition, always executes)
    let rule3_path = temp_dir.path().join("rule3.txt");
    assert!(rule3_path.exists(), "Rule 3 output should exist");
}