pub fn generate_outer_backticks(contents: impl AsRef<[u8]>) -> String {
    let bytes = contents.as_ref();
    let mut max_ticks = 0;
    let mut current_count = 0;
    for &byte in bytes {
        if byte == b'`' {
            current_count += 1;
            if current_count > max_ticks {
                max_ticks = current_count;
            }
        } else {
            current_count = 0;
        }
    }
    let fence_len = std::cmp::max(3, max_ticks + 1);
    "`".repeat(fence_len)
}

#[cfg(test)]
mod tests {
    use super::generate_outer_backticks;

    #[test]
    fn empty_content_returns_three_backticks() {
        assert_eq!(generate_outer_backticks(b""), "```");
        assert_eq!(generate_outer_backticks(""), "```");
    }

    #[test]
    fn content_without_backticks_returns_three_backticks() {
        assert_eq!(generate_outer_backticks(b"no backticks here"), "```");
        assert_eq!(generate_outer_backticks("hello world"), "```");
    }

    #[test]
    fn single_backtick_returns_three_backticks() {
        assert_eq!(generate_outer_backticks(b"`"), "```");
        assert_eq!(generate_outer_backticks("a ` b"), "```");
    }

    #[test]
    fn two_consecutive_backticks_returns_three_backticks() {
        assert_eq!(generate_outer_backticks(b"``"), "```");
        assert_eq!(generate_outer_backticks("a `` b"), "```");
    }

    #[test]
    fn three_consecutive_backticks_returns_four_backticks() {
        assert_eq!(generate_outer_backticks(b"```"), "````");
        assert_eq!(generate_outer_backticks("a ``` b"), "````");
    }

    #[test]
    fn four_consecutive_backticks_returns_five_backticks() {
        assert_eq!(generate_outer_backticks(b"````"), "`````");
        assert_eq!(generate_outer_backticks("a ```` b"), "`````");
    }

    #[test]
    fn long_run_of_backticks_returns_run_plus_one() {
        let run = 10;
        let input = "`".repeat(run);
        let expected = "`".repeat(run + 1);
        assert_eq!(generate_outer_backticks(&input), expected);
    }

    #[test]
    fn maximum_run_across_multiple_groups() {
        let input = "``` and then ````` and then ``"; // longest run is 5
        assert_eq!(generate_outer_backticks(input), "``````"); // 5+1 = 6
    }

    #[test]
    fn backticks_at_start_or_end_handled_correctly() {
        assert_eq!(generate_outer_backticks("````start"), "`````");
        assert_eq!(generate_outer_backticks("end`````"), "``````");
    }
}
