//! Entry point for the `r2md-remove` helper binary.
//!
//! This binary reads a NUL-separated path list from stdin, removes paths supplied as command-line
//! arguments after normalization, and writes the filtered path list to stdout.

use std::{io, path::PathBuf};

use clap::Parser;
use repo2markdown::path_list_editor::remove_paths;

/// Remove paths from a null-separated file list from stdin.
#[derive(Debug, Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Base path used to resolve relative input paths and removal paths.
    #[arg(long, default_value = ".")]
    origin: PathBuf,

    /// Paths to remove from the input sequence.
    paths: Vec<PathBuf>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    remove_paths(
        io::stdin().lock(),
        io::stdout().lock(),
        &cli.paths,
        &cli.origin,
    )
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use clap::Parser;

    use super::Cli;

    #[test]
    fn defaults_origin_to_current_directory() {
        let cli = Cli::try_parse_from(["r2md-remove"]).unwrap();

        assert_eq!(cli.origin, PathBuf::from("."));
    }

    #[test]
    fn accepts_origin() {
        let cli =
            Cli::try_parse_from(["r2md-remove", "--origin", "/repo", "src/generated.rs"]).unwrap();

        assert_eq!(cli.origin, PathBuf::from("/repo"));
        assert_eq!(cli.paths, vec![PathBuf::from("src/generated.rs")]);
    }

    #[test]
    fn accepts_no_paths() {
        let cli = Cli::try_parse_from(["r2md-remove"]).unwrap();

        assert_eq!(cli.paths, Vec::<PathBuf>::new());
    }

    #[test]
    fn accepts_one_path() {
        let cli = Cli::try_parse_from(["r2md-remove", "README.md"]).unwrap();

        assert_eq!(cli.paths, vec![PathBuf::from("README.md")]);
    }

    #[test]
    fn accepts_multiple_paths() {
        let cli = Cli::try_parse_from(["r2md-remove", "README.md", "src/main.rs"]).unwrap();

        assert_eq!(
            cli.paths,
            vec![PathBuf::from("README.md"), PathBuf::from("src/main.rs")]
        );
    }

    #[test]
    fn treats_arguments_after_double_dash_as_paths() {
        let cli = Cli::try_parse_from([
            "r2md-remove",
            "--",
            "--filename-that-looks-like-an-option",
            "main.rs",
        ])
        .unwrap();

        assert_eq!(
            cli.paths,
            vec![
                PathBuf::from("--filename-that-looks-like-an-option"),
                PathBuf::from("main.rs")
            ]
        );
    }
}
