use std::{fmt::Write, iter};

fn main() {
    const TEST_FILE: &str = "src/testcases.rs";
    const INPUT: &str = include_str!("./README.md");

    let mut out = String::new();
    for (name, code) in block_iter(INPUT) {
        let name = name.replace(' ', "_");
        _ = writeln!(
            out,
            "#[test] fn {name}() {{ run_codegen_test(\"{name}\", r##\"{code}\"##) }}"
        );
    }

    std::fs::write(TEST_FILE, out).unwrap();
}

fn block_iter(mut input: &str) -> impl Iterator<Item = (&str, &str)> {
    const CASE_PREFIX: &str = "#### ";
    const CASE_SUFFIX: &str = "\n```hb";

    iter::from_fn(move || loop {
        let pos = input.find(CASE_PREFIX)?;
        input = unsafe { input.get_unchecked(pos + CASE_PREFIX.len()..) };
        let Some((test_name, rest)) = input.split_once(CASE_SUFFIX) else { continue };
        if !test_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            continue;
        }
        input = rest;
        let (body, rest) = input.split_once("```").unwrap_or((input, ""));
        input = rest;
        break Some((test_name, body));
    })
}