use std::io::{Read, Write};

use repo2markdown::{
    fenced_md_generator::generate_fenced_markdown, logger::Logger,
    md_generator::generate_markdown_from_paths,
};

use crate::cli::Cli;

pub fn run<R: Read, W: Write>(
    cli: &Cli,
    input: R,
    output: W,
) -> Result<(), Box<dyn std::error::Error>> {
    let logger = Logger::new(cli.verbosity());

    if cli.fenced {
        generate_fenced_markdown(
            input,
            output,
            cli.render_options(),
            &cli.root,
            &cli.origin,
            cli.name.as_deref(),
            logger,
        )
    } else {
        generate_markdown_from_paths(
            input,
            output,
            cli.render_options(),
            &cli.root,
            &cli.origin,
            cli.name.as_deref(),
            logger,
        )
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use clap::Parser;

    use crate::cli::Cli;

    use super::run;

    #[test]
    fn run_does_not_fence_output_by_default() {
        let cli = Cli::try_parse_from(["repo2markdown", "--name", "Project name"]).unwrap();

        let input = Cursor::new(b"");
        let mut output = Vec::new();

        run(&cli, input, &mut output).unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "# Project name\n");
    }

    #[test]
    fn run_uses_fenced_output_when_requested() {
        let cli =
            Cli::try_parse_from(["repo2markdown", "--fenced", "--name", "Project name"]).unwrap();

        let input = Cursor::new(b"");
        let mut output = Vec::new();

        run(&cli, input, &mut output).unwrap();

        assert_eq!(
            String::from_utf8(output).unwrap(),
            "```markdown\n# Project name\n```\n"
        );
    }
}
