pub fn glob_match(pattern: &str, text: &str) -> bool {
    match_impl(pattern.as_bytes(), text.as_bytes())
}

fn match_impl(pattern: &[u8], text: &[u8]) -> bool {
    if pattern.is_empty() {
        return text.is_empty();
    }
    if pattern.len() >= 2 && pattern[0] == b'*' && pattern[1] == b'*' {
        let rest = skip_double_star_slash(pattern);
        for i in 0..=text.len() {
            if match_impl(rest, &text[i..]) {
                return true;
            }
        }
        return false;
    }
    if pattern[0] == b'*' {
        let rest = &pattern[1..];
        for i in 0..=text.len() {
            if i > 0 && text[i - 1] == b'/' {
                break;
            }
            if match_impl(rest, &text[i..]) {
                return true;
            }
        }
        return false;
    }

    if text.is_empty() {
        return false;
    }
    if pattern[0] == b'?' {
        if text[0] == b'/' {
            return false;
        }
        return match_impl(&pattern[1..], &text[1..]);
    }
    if pattern[0] == text[0] {
        return match_impl(&pattern[1..], &text[1..]);
    }

    false
}
fn skip_double_star_slash(pattern: &[u8]) -> &[u8] {
    let rest = &pattern[2..];
    if rest.first() == Some(&b'/') {
        &rest[1..]
    } else {
        rest
    }
}

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

    #[test]
    fn exact_match() {
        assert!(glob_match("main", "main"));
        assert!(!glob_match("main", "develop"));
    }

    #[test]
    fn single_star_matches_segment() {
        assert!(glob_match("featurerelease", "release"));
        assert!(glob_match("**/release", "a/b/c/release"));
    }

    #[test]
    fn question_mark() {
        assert!(glob_match("v?", "v1"));
        assert!(glob_match("v?", "vA"));
        assert!(!glob_match("v?", "v12"));
        assert!(!glob_match("v?", "v/"));
    }

    #[test]
    fn tag_patterns() {
        assert!(glob_match("v*", "v1.0.0"));
        assert!(glob_match("v*", "v2"));
        assert!(!glob_match("v*", "2.0.0"));
        assert!(glob_match("release-*", "release-2024"));
    }

    #[test]
    fn star_at_start() {
        assert!(glob_match("*-staging", "dev-staging"));
        assert!(glob_match("*-staging", "test-staging"));
        assert!(!glob_match("*-staging", "dev/staging"));
    }
}
