//! Utilities for wrapping arbitrary input in a Markdown fenced code block.

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

use crate::util::fence::generate_outer_backticks;

/// Reads all input, wraps it in a Markdown fenced code block, and writes it to output.
///
/// The opening fence includes the supplied language tag. If `lang` is empty, the fence is emitted
/// without a language identifier.
///
/// The fence length is chosen so that any backtick runs inside the input do not accidentally close
/// the outer fence.
///
/// This function intentionally writes a blank line before the closing fence.
pub fn wrap_in_fence<R: Read, W: Write>(
    mut input: R,
    mut output: W,
    lang: &str,
) -> std::io::Result<()> {
    let mut contents = Vec::new();
    input.read_to_end(&mut contents)?;
    let fence = generate_outer_backticks(&contents);
    writeln!(output, "{}{}", fence, lang)?;
    output.write_all(&contents)?;
    writeln!(output, "\n{}", fence)
}

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

    use super::wrap_in_fence;

    #[test]
    fn wraps_input_in_fence_with_language() {
        let input = Cursor::new("fn main() {}\n");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "rust").unwrap();

        assert_eq!(
            String::from_utf8(output).unwrap(),
            "```rust\nfn main() {}\n\n```\n"
        );
    }

    #[test]
    fn puts_closing_fence_on_new_line_when_input_has_no_trailing_newline() {
        let input = Cursor::new("hello");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "text").unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "```text\nhello\n```\n");
    }

    #[test]
    fn uses_longer_fence_when_input_contains_backticks() {
        let input = Cursor::new("contains ``` inside\n");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "markdown").unwrap();

        assert_eq!(
            String::from_utf8(output).unwrap(),
            "````markdown\ncontains ``` inside\n\n````\n"
        );
    }

    #[test]
    fn wraps_empty_input() {
        let input = Cursor::new("");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "text").unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "```text\n\n```\n");
    }

    #[test]
    fn supports_empty_language() {
        let input = Cursor::new("hello\n");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "").unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "```\nhello\n\n```\n");
    }

    #[test]
    fn wraps_empty_input_with_empty_language() {
        let input = Cursor::new("");
        let mut output = Vec::new();

        wrap_in_fence(input, &mut output, "").unwrap();

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