//! Pipeline and chaining example.
//!
//! Demonstrates `|`, `|&`, `&&`, `||`, redirection, and optional piping.
//!
//! Run with: `cargo run --example parse_pipeline`

use slash_lang::parser::{
    ast::{Op, Redirection},
    parse,
};

fn main() {
    let inputs = [
        // Pipe: stdout flows right
        "/lint | /format | /build",
        // Pipe with stderr: both stdout and stderr flow right
        "/compile |& /report",
        // AND chain: next runs only on success
        "/test && /deploy",
        // OR chain: next runs only on failure
        "/primary || /fallback",
        // Redirection: capture output to a file
        "/report > out.txt",
        // Append redirection
        "/log >> audit.log",
        // AND then pipe in a new pipeline
        "/check && /lint | /fix",
        // Optional pipe: accumulates Context for the final command
        "/foo? | /bar? | /baz",
    ];

    for input in &inputs {
        println!("Input:  {input}");
        match parse(input) {
            Ok(program) => {
                for (pi, pipeline) in program.pipelines.iter().enumerate() {
                    let sep = match &pipeline.operator {
                        Some(Op::And) => " && …",
                        Some(Op::Or) => " || …",
                        _ => "",
                    };
                    println!("  Pipeline[{pi}]{sep}:");
                    for cmd in &pipeline.commands {
                        let pipe_sym = match &cmd.pipe {
                            Some(Op::Pipe) => " |",
                            Some(Op::PipeErr) => " |&",
                            _ => "",
                        };
                        let redir = match &cmd.redirect {
                            Some(Redirection::Truncate(f)) => format!(" > {f}"),
                            Some(Redirection::Append(f)) => format!(" >> {f}"),
                            None => String::new(),
                        };
                        println!(
                            "    /{}{opt}{pipe}{redir}",
                            cmd.name,
                            opt = if cmd.optional { "?" } else { "" },
                            pipe = pipe_sym,
                            redir = redir,
                        );
                    }
                }
            }
            Err(e) => println!("  ERROR: {:?}", e),
        }
        println!();
    }
}
