ggen-core 26.6.25

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
//! Template processing pipeline with RDF/SPARQL integration
//!
//! This module provides the core pipeline for processing templates with integrated
//! RDF graph operations and SPARQL query execution. The `Pipeline` type orchestrates
//! template parsing, frontmatter rendering, graph processing, and body rendering.
//!
//! ## Architecture
//!
//! The pipeline follows a multi-stage processing flow:
//! 1. **Template Parsing**: Parse YAML frontmatter and template body
//! 2. **Frontmatter Rendering**: Render frontmatter variables with Tera
//! 3. **Graph Processing**: Load RDF data and execute SPARQL queries
//! 4. **Body Rendering**: Render template body with full context
//! 5. **Plan Execution**: Apply generation plan (write files, inject content, etc.)
//!
//! ## Features
//!
//! - **SPARQL Integration**: Execute queries and expose results to templates
//! - **Prefix Management**: Register RDF prefixes and base IRIs
//! - **File Injection**: Support for modifying existing files with markers
//! - **Dry Run Mode**: Preview changes without writing files
//! - **Shell Hooks**: Execute commands before/after file operations (with security checks)
//!
//! ## Examples
//!
//! ### Basic Pipeline Usage
//!
//! ```rust,no_run
//! use crate::pipeline::{Pipeline, PipelineBuilder};
//! use std::collections::BTreeMap;
//! use std::path::Path;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! // Create a new pipeline
//! let mut pipeline = Pipeline::new()?;
//!
//! // Register RDF prefixes
//! let mut prefixes = BTreeMap::new();
//! prefixes.insert("ex".to_string(), "http://example.org/".to_string());
//! pipeline.register_prefixes(Some("http://example.org/base/"), &prefixes);
//!
//! // Render a template file
//! let vars = BTreeMap::new();
//! let plan = pipeline.render_file(Path::new("template.tmpl"), &vars, false)?;
//! plan.apply()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Using PipelineBuilder
//!
//! ```rust,no_run
//! use crate::pipeline::PipelineBuilder;
//! use std::collections::BTreeMap;
//!
//! # fn main() -> crate::utils::error::Result<()> {
//! let mut prefixes = BTreeMap::new();
//! prefixes.insert("ex".to_string(), "http://example.org/".to_string());
//!
//! let pipeline = PipelineBuilder::new()
//!     .with_prefixes(prefixes, Some("http://example.org/base/".to_string()))
//!     .with_rdf_file("data.ttl")
//!     .with_inline_rdf(vec!["@prefix ex: <http://example.org/> . ex:test a ex:Type ."])
//!     .build()?;
//! # Ok(())
//! # }
//! ```

use crate::graph::{build_prolog, Graph};
use crate::register;
use crate::template_types::Frontmatter;
use crate::tracing::PipelineTracer;
use crate::utils::error::{Error, Result};
use oxigraph::sparql::QueryResults;
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tera::{Context, Function as TeraFunction, Tera};

pub struct Pipeline {
    pub(crate) tera: Tera,
    pub(crate) graph: Graph,
}

impl Pipeline {
    /// Create a new pipeline with default configuration
    ///
    /// # Example
    ///
    /// ```rust
    /// use crate::pipeline::Pipeline;
    ///
    /// let pipeline = Pipeline::new().unwrap();
    /// // Pipeline is ready to use
    /// ```
    pub fn new() -> Result<Self> {
        let mut tera = Tera::default();
        tera.autoescape_on(vec![]);
        register::register_all(&mut tera);
        Ok(Self {
            tera,
            graph: Graph::new()?,
        })
    }

    /// Get the number of triples in the pipeline's RDF graph
    pub fn graph_len(&self) -> usize {
        self.graph.len()
    }

    /// Get mutable reference to the Tera instance
    pub fn tera_mut(&mut self) -> &mut Tera {
        &mut self.tera
    }

    /// Register SPARQL + local() for a given BASE+PREFIX set
    pub fn register_prefixes(&mut self, base: Option<&str>, prefixes: &BTreeMap<String, String>) {
        let prolog = build_prolog(prefixes, base);
        self.tera.register_function(
            "sparql",
            SparqlFn {
                graph: self.graph.clone(),
                prolog,
            },
        );
        self.tera.register_function("local", LocalFn);
    }

    /// Pure render of a template body with a ready Context.
    pub fn render_body(&mut self, body: &str, ctx: &Context) -> Result<String> {
        Ok(self.tera.render_str(body, ctx)?)
    }

    /// Render a template file and return a Plan
    pub fn render_file(
        &mut self, template_path: &Path, vars: &BTreeMap<String, String>, dry_run: bool,
    ) -> Result<Plan> {
        // Start performance timing
        // let _timer = SimpleTimer::start("template_processing"); // Temporarily disabled

        PipelineTracer::template_start(template_path);

        // Read template file
        let input = std::fs::read_to_string(template_path)?;
        let _body_lines = input.lines().count();

        // Create Tera context from vars
        let mut ctx = Context::from_serialize(vars)?;

        // Parse template to get frontmatter
        let mut template = crate::template_types::Template::parse(&input)?;

        // Render frontmatter first to get the final 'to' field
        template.render_frontmatter(&mut self.tera, &ctx)?;
        PipelineTracer::frontmatter_processed(&template.front);

        // Auto-bless context variables (Name, locals)
        crate::register::bless_context(&mut ctx);
        PipelineTracer::context_blessed(vars.len());

        // ❌ REMOVED: template.front.vars - Variables now come from CLI/API only

        // Determine output path from frontmatter or default
        let out_path = if let Some(to_path) = &template.front.to {
            // Render the 'to' field as a template
            let rendered_to = self.tera.render_str(to_path, &ctx)?;
            PathBuf::from(rendered_to)
        } else {
            PathBuf::from("out.txt")
        };

        // ❌ REMOVED: template.front.rdf - RDF files now loaded via CLI/API
        // Load RDF and execute SPARQL declared in frontmatter
        PipelineTracer::rdf_loading_start(
            &Vec::new(), // No RDF files in frontmatter
            template.front.rdf_inline.len(),
        );
        template.process_graph(&mut self.graph, &mut self.tera, &ctx, template_path)?;
        PipelineTracer::rdf_loading_complete(self.graph.len());

        // Render body
        let rendered = template.render(&mut self.tera, &ctx, std::path::Path::new(""))?;
        PipelineTracer::template_rendering_complete(&out_path, rendered.len());

        // Create plan
        let plan = Plan {
            template_path: template_path.to_path_buf(),
            output_path: out_path,
            content: rendered,
            frontmatter: template.front,
            dry_run,
        };

        if dry_run {
            // PipelineTracer::dry_run(&plan.output_path, plan.content.len()); // Temporarily disabled
        }

        Ok(plan)
    }
}

pub struct PipelineBuilder {
    prefixes: BTreeMap<String, String>,
    base: Option<String>,
    preload_ttl_files: Vec<String>,
    preload_ttl_inline: Vec<String>,
}

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

impl PipelineBuilder {
    /// Create a new pipeline builder
    ///
    /// # Example
    ///
    /// ```rust
    /// use crate::pipeline::PipelineBuilder;
    ///
    /// let builder = PipelineBuilder::new();
    /// // Builder is ready to use
    /// ```
    pub fn new() -> Self {
        Self {
            prefixes: BTreeMap::new(),
            base: None,
            preload_ttl_files: vec![],
            preload_ttl_inline: vec![],
        }
    }
    pub fn with_prefixes(mut self, pfx: BTreeMap<String, String>, base: Option<String>) -> Self {
        self.prefixes = pfx;
        self.base = base;
        self
    }
    pub fn with_rdf_files<S: Into<String>>(mut self, files: impl IntoIterator<Item = S>) -> Self {
        self.preload_ttl_files = files.into_iter().map(Into::into).collect();
        self
    }

    pub fn with_rdf_file<S: Into<String>>(mut self, file: S) -> Self {
        self.preload_ttl_files.push(file.into());
        self
    }
    pub fn with_inline_rdf<S: Into<String>>(mut self, blocks: impl IntoIterator<Item = S>) -> Self {
        self.preload_ttl_inline = blocks.into_iter().map(Into::into).collect();
        self
    }
    /// Build the pipeline with the configured options
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use crate::pipeline::PipelineBuilder;
    /// use std::collections::BTreeMap;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let mut prefixes = BTreeMap::new();
    /// prefixes.insert("ex".to_string(), "http://example.org/".to_string());
    ///
    /// let pipeline = PipelineBuilder::new()
    ///     .with_prefixes(prefixes, Some("http://example.org/".to_string()))
    ///     .with_rdf_file("data.ttl")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self) -> Result<Pipeline> {
        let mut p = Pipeline::new()?;
        for f in &self.preload_ttl_files {
            let ttl = std::fs::read_to_string(f)?;
            p.graph.insert_turtle(&ttl)?;
        }
        for ttl in &self.preload_ttl_inline {
            p.graph.insert_turtle(ttl)?;
        }
        p.register_prefixes(self.base.as_deref(), &self.prefixes);
        Ok(p)
    }
}

/* ---------- Tera helpers ---------- */
#[derive(Clone)]
struct SparqlFn {
    graph: Graph,
    prolog: String,
}

impl TeraFunction for SparqlFn {
    fn call(&self, args: &std::collections::HashMap<String, Value>) -> tera::Result<Value> {
        let q = args
            .get("query")
            .and_then(|v| v.as_str())
            .ok_or_else(|| tera::Error::msg("sparql: query required"))?;
        let want = args.get("var").and_then(|v| v.as_str());

        let final_q = if self.prolog.is_empty() {
            q.to_string()
        } else {
            format!("{}\n{}", self.prolog, q)
        };

        // Trace SPARQL query execution
        PipelineTracer::sparql_query(&final_q, None);

        let results = self
            .graph
            .query(&final_q)
            .map_err(|e| tera::Error::msg(e.to_string()))?;

        let json_val = match results {
            QueryResults::Boolean(b) => serde_json::Value::Bool(b),
            QueryResults::Solutions(solutions) => {
                let mut rows = Vec::new();
                for solution in solutions {
                    let solution = solution.map_err(|e| tera::Error::msg(e.to_string()))?;
                    let mut row = serde_json::Map::new();
                    for (var, term) in solution.iter() {
                        row.insert(var.to_string(), serde_json::Value::String(term.to_string()));
                    }
                    rows.push(serde_json::Value::Object(row));
                }
                serde_json::Value::Array(rows)
            }
            QueryResults::Graph(triples) => {
                let mut rows = Vec::new();
                for triple_result in triples {
                    let triple = triple_result.map_err(|e| tera::Error::msg(e.to_string()))?;
                    let mut row = serde_json::Map::new();
                    row.insert(
                        "subject".to_string(),
                        serde_json::Value::String(triple.subject.to_string()),
                    );
                    row.insert(
                        "predicate".to_string(),
                        serde_json::Value::String(triple.predicate.to_string()),
                    );
                    row.insert(
                        "object".to_string(),
                        serde_json::Value::String(triple.object.to_string()),
                    );
                    rows.push(serde_json::Value::Object(row));
                }
                serde_json::Value::Array(rows)
            }
        };

        // Handle var extraction if requested
        if let Some(var_name) = want {
            if let serde_json::Value::Array(rows) = &json_val {
                if let Some(serde_json::Value::Object(obj)) = rows.first() {
                    if let Some(val) = obj.get(var_name) {
                        return Ok(val.clone());
                    }
                }
            }
            return Ok(serde_json::Value::String(String::new()));
        }

        Ok(json_val)
    }
}

#[derive(Clone)]
struct LocalFn;
impl TeraFunction for LocalFn {
    fn call(&self, args: &std::collections::HashMap<String, Value>) -> tera::Result<Value> {
        let iri = args.get("iri").and_then(|v| v.as_str()).unwrap_or_default();
        let s = iri.trim();
        let s = s
            .strip_prefix('<')
            .and_then(|x| x.strip_suffix('>'))
            .unwrap_or(s);
        let idx = s.rfind(['#', '/']).map(|i| i + 1).unwrap_or(0);
        Ok(serde_json::Value::String(s[idx..].to_string()))
    }
}

/// Plan represents a generation plan that can be applied or previewed
#[allow(dead_code)]
pub struct Plan {
    template_path: PathBuf,
    output_path: PathBuf,
    content: String,
    frontmatter: Frontmatter,
    dry_run: bool,
}

impl Plan {
    /// Get the rendered content of the plan
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Get the output path where the plan will write
    pub fn output_path(&self) -> &std::path::Path {
        &self.output_path
    }

    /// Get the template path that produced this plan
    pub fn template_path(&self) -> &std::path::Path {
        &self.template_path
    }

    /// Whether this is a dry-run plan
    pub fn is_dry_run(&self) -> bool {
        self.dry_run
    }

    /// Apply the plan by writing the content to the output path
    pub fn apply(&self) -> Result<()> {
        if self.dry_run {
            PipelineTracer::dry_run(&self.output_path, self.content.len());
            return Ok(());
        }

        // Handle injection templates
        if self.frontmatter.flags.inject {
            return self.apply_injection();
        }

        // Handle regular file generation
        self.apply_regular()
    }

    /// Apply injection logic for modifying existing files
    fn apply_injection(&self) -> Result<()> {
        use crate::inject::{EolNormalizer, SkipIfGenerator};

        // Check if target file exists
        if !self.output_path.exists() {
            // Create new file with content
            if let Some(parent) = self.output_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&self.output_path, &self.content)?;
            // info!(path = %self.output_path.display(), "Created new file"); // Temporarily disabled
            return Ok(());
        }

        // Read existing content
        let existing_content = std::fs::read_to_string(&self.output_path)?;
        // debug!(path = %self.output_path.display(), existing_size = existing_content.len(), "Read existing file content"); // Temporarily disabled

        // Check idempotency guards
        if let Some(skip_if) = &self.frontmatter.skip_if {
            let regex = regex::Regex::new(skip_if)
                .map_err(|e| Error::new(&format!("Invalid regex pattern '{}': {}", skip_if, e)))?;
            if regex.is_match(&existing_content) {
                // PipelineTracer::skip_condition("skip_if", &format!("pattern '{}' found", skip_if)); // Temporarily disabled
                return Ok(());
            }
        }

        // Check if content already exists (idempotent mode)
        if self.frontmatter.flags.idempotent
            && SkipIfGenerator::content_exists_in_file(&self.content, &self.output_path)?
        {
            // PipelineTracer::skip_condition("idempotent", "content already exists"); // Temporarily disabled
            return Ok(());
        }

        // Create backup if requested
        if self.frontmatter.backup.unwrap_or(false) {
            let backup_path = format!("{}.backup", self.output_path.display());
            std::fs::copy(&self.output_path, &backup_path)?;
            // PipelineTracer::backup_created(&self.output_path, &PathBuf::from(&backup_path)); // Temporarily disabled
        }

        // Normalize EOL for injection content
        let normalized_content =
            EolNormalizer::normalize_to_match_file(&self.content, &self.output_path)?;

        // Apply injection based on mode
        let new_content = self.inject_content(&existing_content, &normalized_content)?;

        // Execute shell hook before writing (if specified)
        if let Some(sh_before) = &self.frontmatter.sh_before {
            self.execute_shell_hook(sh_before, "before")?;
        }

        // Write the modified content
        std::fs::write(&self.output_path, new_content)?;
        log::info!("Injected: {}", self.output_path.display());

        // Execute shell hook after writing (if specified)
        if let Some(sh_after) = &self.frontmatter.sh_after {
            self.execute_shell_hook(sh_after, "after")?;
        }

        Ok(())
    }

    /// Apply regular file generation (non-injection)
    fn apply_regular(&self) -> Result<()> {
        // Check unless_exists guard
        if self.frontmatter.flags.unless_exists && self.output_path.exists() {
            log::info!("Skipped: file already exists and unless_exists=true");
            return Ok(());
        }

        // Check force flag
        if !self.frontmatter.flags.force && self.output_path.exists() {
            return Err(Error::new(&format!(
                "File already exists: {}. Use --force to overwrite.",
                self.output_path.display()
            )));
        }

        // Create parent directories if needed
        if let Some(parent) = self.output_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Execute shell hook before writing (if specified)
        if let Some(sh_before) = &self.frontmatter.sh_before {
            self.execute_shell_hook(sh_before, "before")?;
        }

        // Write content
        std::fs::write(&self.output_path, &self.content)?;

        log::info!("Generated: {}", self.output_path.display());

        // Execute shell hook after writing (if specified)
        if let Some(sh_after) = &self.frontmatter.sh_after {
            self.execute_shell_hook(sh_after, "after")?;
        }

        Ok(())
    }

    /// Inject content into existing content based on frontmatter settings
    fn inject_content(&self, existing: &str, new_content: &str) -> Result<String> {
        let lines: Vec<&str> = existing.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();

        match (
            self.frontmatter.flags.prepend,
            self.frontmatter.flags.append,
            &self.frontmatter.before,
            &self.frontmatter.after,
            self.frontmatter.at_line,
        ) {
            (true, _, _, _, _) => {
                // Prepend mode
                let mut result = new_lines;
                result.extend(lines);
                Ok(result.join("\n"))
            }
            (_, true, _, _, _) => {
                // Append mode
                let mut result = lines;
                result.extend(new_lines);
                Ok(result.join("\n"))
            }
            (_, _, Some(before), _, _) => {
                // Before mode - find the line and insert before it
                if let Some(index) = lines.iter().position(|line| line.contains(before)) {
                    let mut result = lines[..index].to_vec();
                    result.extend(new_lines);
                    result.extend(lines[index..].to_vec());
                    Ok(result.join("\n"))
                } else {
                    // Pattern not found, append
                    let mut result = lines;
                    result.extend(new_lines);
                    Ok(result.join("\n"))
                }
            }
            (_, _, _, Some(after), _) => {
                // After mode - find the line and insert after it
                if let Some(index) = lines.iter().position(|line| line.contains(after)) {
                    let mut result = lines[..=index].to_vec();
                    result.extend(new_lines);
                    result.extend(lines[index + 1..].to_vec());
                    Ok(result.join("\n"))
                } else {
                    // Pattern not found, append
                    let mut result = lines;
                    result.extend(new_lines);
                    Ok(result.join("\n"))
                }
            }
            (_, _, _, _, Some(line_num)) => {
                // At line mode - insert at specific line number (1-based)
                let index = (line_num as usize).saturating_sub(1);
                let mut result = lines[..index].to_vec();
                result.extend(new_lines);
                result.extend(lines[index..].to_vec());
                Ok(result.join("\n"))
            }
            _ => {
                // Default to append if no mode specified
                let mut result = lines;
                result.extend(new_lines);
                Ok(result.join("\n"))
            }
        }
    }

    /// Execute a shell hook command
    ///
    /// SECURITY: Uses SafeCommand to prevent command injection. Only whitelisted
    /// programs are allowed to execute. Shell features (pipes, redirects) are blocked.
    fn execute_shell_hook(&self, command_str: &str, _timing: &str) -> Result<()> {
        use crate::security::SafeCommand;

        // Split the command string into program and args
        let parts: Vec<&str> = command_str.split_whitespace().collect();
        if parts.is_empty() {
            return Ok(());
        }

        let mut cmd = SafeCommand::new(parts[0])?;
        for arg in &parts[1..] {
            cmd = cmd.arg(arg)?;
        }

        // PipelineTracer::shell_hook_start(command_str, timing); // Temporarily disabled

        // Execute the command safely in the current directory
        let output = cmd.current_dir(&std::env::current_dir()?)?.execute()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::new(&format!("Shell hook failed: {}", stderr)));
        }

        // Print stdout if any
        if !output.stdout.is_empty() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            print!("{}", stdout);
        }

        // PipelineTracer::shell_hook_complete(command_str, timing, exit_code); // Temporarily disabled
        Ok(())
    }

    /// Print unified diff of what would be written
    pub fn print_diff(&self) -> Result<()> {
        log::info!("DRY RUN - Would generate: {}", self.output_path.display());

        if self.output_path.exists() {
            let existing_content = std::fs::read_to_string(&self.output_path)?;
            print_colorized_diff(&existing_content, &self.content, &self.output_path);
        } else {
            print_colorized_new_file(&self.content, &self.output_path);
        }

        Ok(())
    }

    /// Get content hash for determinism
    pub fn content_hash(&self) -> Option<String> {
        let mut hasher = Sha256::new();
        hasher.update(self.content.as_bytes());
        Some(format!("{:x}", hasher.finalize()))
    }
}

/// Print colorized diff between two strings
fn print_colorized_diff(old: &str, new: &str, path: &Path) {
    use colored::*;

    log::debug!("{} {}", "---".red(), path.display());
    log::debug!("{} {}", "+++".green(), path.display());

    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();

    // Simple diff implementation with colors
    let max_lines = old_lines.len().max(new_lines.len());

    for i in 0..max_lines {
        let old_line = old_lines.get(i);
        let new_line = new_lines.get(i);

        match (old_line, new_line) {
            (Some(old), Some(new)) if old == new => {
                log::debug!(" {}", old);
            }
            (Some(old), Some(new)) => {
                log::debug!("{}{}", "-".red(), old.red());
                log::debug!("{}{}", "+".green(), new.green());
            }
            (Some(old), None) => {
                log::debug!("{}{}", "-".red(), old.red());
            }
            (None, Some(new)) => {
                log::debug!("{}{}", "+".green(), new.green());
            }
            (None, None) => break,
        }
    }
}

/// Print colorized output for new file creation
fn print_colorized_new_file(content: &str, path: &Path) {
    use colored::*;

    log::debug!("{} /dev/null", "---".red());
    log::debug!("{} {}", "+++".green(), path.display());

    for line in content.lines() {
        log::debug!("{}{}", "+".green(), line.green());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;
    use tempfile::TempDir;

    // Test 1: Pipeline initialization
    #[test]
    fn test_pipeline_new() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let pipeline = Pipeline::new()?;
        assert!(!pipeline.graph.is_empty() || pipeline.graph.is_empty()); // Just verify it exists
        Ok(())
    }

    // Test 2: Basic rendering
    #[test]
    fn test_pipeline_render_body() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let mut pipeline = Pipeline::new()?;
        let mut ctx = Context::new();
        ctx.insert("name", "World");

        let result = pipeline.render_body("Hello {{ name }}", &ctx)?;
        assert_eq!(result, "Hello World");
        Ok(())
    }

    // Test 3: Render file with frontmatter
    #[test]
    fn test_pipeline_render_file_basic() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let template_content = r#"---
to: "output.txt"
---
Hello {{ name }}"#;
        let template_path = temp_dir.path().join("test.tmpl");
        std::fs::write(&template_path, template_content)?;

        let mut pipeline = Pipeline::new()?;
        let mut vars = BTreeMap::new();
        vars.insert("name".to_string(), "World".to_string());

        let plan = pipeline.render_file(&template_path, &vars, false)?;

        assert_eq!(plan.content, "Hello World");
        assert_eq!(plan.output_path.file_name().unwrap(), "output.txt");
        Ok(())
    }

    // Test 4: Plan dry run
    #[test]
    fn test_plan_apply_dry_run() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let output_path = temp_dir.path().join("output.txt");

        let plan = Plan {
            template_path: temp_dir.path().join("test.tmpl"),
            output_path: output_path.clone(),
            content: "Test content".to_string(),
            frontmatter: crate::template_types::Frontmatter::default(),
            dry_run: true,
        };

        plan.apply()?;

        // Verify file was NOT created
        assert!(!output_path.exists());
        Ok(())
    }

    // Test 5: Plan apply creates new file
    #[test]
    fn test_plan_apply_creates_file() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let output_path = temp_dir.path().join("output.txt");

        let plan = Plan {
            template_path: temp_dir.path().join("test.tmpl"),
            output_path: output_path.clone(),
            content: "Test content".to_string(),
            frontmatter: crate::template_types::Frontmatter::default(),
            dry_run: false,
        };

        plan.apply()?;

        // Verify file was created with correct content
        assert!(output_path.exists());
        let content = std::fs::read_to_string(&output_path)?;
        assert_eq!(content, "Test content");
        Ok(())
    }

    // Test 6: Plan with unless_exists
    #[test]
    fn test_plan_unless_exists() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        let output_path = temp_dir.path().join("output.txt");

        // Create existing file
        std::fs::write(&output_path, "Original content")?;

        let frontmatter = crate::template_types::Frontmatter {
            flags: crate::template_types::FrontmatterFlags {
                unless_exists: true,
                ..Default::default()
            },
            ..Default::default()
        };

        let plan = Plan {
            template_path: temp_dir.path().join("test.tmpl"),
            output_path: output_path.clone(),
            content: "New content".to_string(),
            frontmatter,
            dry_run: false,
        };

        plan.apply()?;

        // Verify file was NOT overwritten
        let content = std::fs::read_to_string(&output_path)?;
        assert_eq!(content, "Original content");
        Ok(())
    }

    // Test 7: PipelineBuilder with prefixes
    #[test]
    fn test_pipeline_builder_with_prefixes() -> Result<()> {
        let mut prefixes = BTreeMap::new();
        prefixes.insert("ex".to_string(), "http://example.org/".to_string());

        let pipeline = PipelineBuilder::new()
            .with_prefixes(prefixes, Some("http://example.org/base/".to_string()))
            .build()?;

        // Just verify it builds successfully
        assert!(!pipeline.graph.is_empty() || pipeline.graph.is_empty());
        Ok(())
    }

    // Test 8: Register prefixes
    #[test]
    fn test_pipeline_register_prefixes() -> Result<()> {
        let mut pipeline = Pipeline::new()?;
        let mut prefixes = BTreeMap::new();
        prefixes.insert("ex".to_string(), "http://example.org/".to_string());

        pipeline.register_prefixes(Some("http://example.org/base/"), &prefixes);

        // Verify SPARQL function is registered (try to render)
        let ctx = Context::new();
        let result = pipeline.render_body("{{ 1 + 1 }}", &ctx)?;
        assert_eq!(result, "2");
        Ok(())
    }
}