use crate::{Arg, Command};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HelpFormat {
    /// Output generated by clap (Rust).
    Clap,
    /// Output generated by Python's argparse module.
    Argparse,
    /// Unknown or generic format.
    Generic,
    /// Format like ip command help.
    Ebnf,
}

fn detect_format(help: &str) -> HelpFormat {
    if help.contains(":=") && help.contains('{') {
        return HelpFormat::Ebnf;
    }

    let has_usage = help.contains("Usage:") || help.contains("USAGE") || help.contains("Usage of ");

    let has_commands_section = help.lines().any(|l| {
        let trimmed = l.trim();
        let lower = trimmed.to_lowercase();
        trimmed == "Commands:"
            || trimmed == "Subcommands:"
            || trimmed == "Available Commands:"
            || (lower.contains("common") && lower.contains("commands"))
            || lower.contains("commands used in")
            || (lower.contains("commands")
                && (trimmed.ends_with(':')
                    || lower.contains("commands are")
                    || (trimmed
                        .chars()
                        .all(|c| c.is_uppercase() || c.is_whitespace() || c == '-')
                        && !trimmed.is_empty())))
    });

    let has_positional = help.lines().any(|l| {
        let t = l.trim();
        t == "positional arguments:" || t == "arguments:"
    });
    let has_optional = help.lines().any(|l| {
        let t = l.trim();
        t == "optional arguments:" || t == "options:" || t.starts_with("named arguments:")
    });

    // Check if there is any options/flags/arguments section header.
    let has_options_header = help.lines().any(|l| {
        let trimmed = l.trim();
        if trimmed.is_empty() {
            return false;
        }
        let is_options = trimmed.len() <= 40
            && (trimmed.ends_with(':')
                || (trimmed
                    .chars()
                    .all(|c| c.is_uppercase() || c.is_whitespace() || c == '-')
                    && !trimmed.is_empty())
                || {
                    let lower = trimmed.to_lowercase();
                    lower == "options"
                        || lower == "flags"
                        || lower == "arguments"
                        || lower == "args"
                })
            && {
                let lower = trimmed.to_lowercase();
                lower.contains("options")
                    || lower.contains("flags")
                    || lower.contains("arguments")
                    || lower.contains("args")
                    || lower.contains("builder")
                    || lower.contains("parameters")
                    || lower.contains("settings")
                    || lower.contains("control")
                    || lower.contains("selection")
                    || lower.contains("miscellaneous")
                    || lower.contains("interpretation")
                    || lower.starts_with("usage of ")
            };
        is_options
    });

    if has_positional || (has_optional && !has_commands_section) {
        // Pure argparse output never has a "Commands:" section.
        HelpFormat::Argparse
    } else if (has_usage || has_commands_section) && (has_options_header || has_commands_section) {
        HelpFormat::Clap
    } else {
        HelpFormat::Generic
    }
}

fn strip_ansi(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                while let Some(next_c) = chars.next() {
                    if next_c.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Parse a `--help` string into a [`Command`] with the best fidelity possible.
///
/// The function auto-detects whether the string was produced by clap,
/// Python argparse, or an unknown tool, and dispatches accordingly.
pub fn parse_help(help: &str) -> Command {
    let clean_help = strip_ansi(help);

    let mut cmd = match detect_format(&clean_help) {
        HelpFormat::Clap => parse_help_clap(&clean_help),
        HelpFormat::Argparse => parse_help_argparse(&clean_help),
        HelpFormat::Ebnf => parse_help_ebnf(&clean_help),
        HelpFormat::Generic => parse_help_generic(&clean_help),
    };
    // Expand bracketed negation flags (like --[no-]color) into both variants
    cmd.expand_no_options();
    cmd.populate_possible_values();
    cmd.deduplicate_args();

    // Fallback: if we have subcommands but no name was parsed from Usage,
    // try to extract the command name from patterns like "common <name> commands"
    if cmd.name.is_none() && !cmd.subcommands.is_empty() {
        if let Some(name) = extract_fallback_name(&clean_help) {
            cmd.name = Some(name);
        }
    }

    cmd
}

fn extract_fallback_name(help: &str) -> Option<String> {
    let help_lower = help.to_lowercase();
    static RE_COMMON: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let re =
        RE_COMMON.get_or_init(|| regex::Regex::new(r"common\s+([a-z0-9_-]+)\s+commands").unwrap());
    if let Some(caps) = re.captures(&help_lower) {
        let name = caps.get(1).unwrap().as_str();
        if name != "sub" && name != "main" && name != "available" && name != "frequently" {
            return Some(name.to_string());
        }
    }
    None
}

fn split_top_level(s: &str, delimiter: char) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut depth_braces = 0;
    let mut depth_brackets = 0;
    let mut depth_parens = 0;
    for c in s.chars() {
        if c == '{' {
            depth_braces += 1;
        } else if c == '}' {
            depth_braces -= 1;
        } else if c == '[' {
            depth_brackets += 1;
        } else if c == ']' {
            depth_brackets -= 1;
        } else if c == '(' {
            depth_parens += 1;
        } else if c == ')' {
            depth_parens -= 1;
        }

        if c == delimiter && depth_braces == 0 && depth_brackets == 0 && depth_parens == 0 {
            parts.push(current.trim().to_string());
            current.clear();
        } else {
            current.push(c);
        }
    }
    if !current.trim().is_empty() {
        parts.push(current.trim().to_string());
    }
    parts
}

fn is_like_value_name(t: &str) -> bool {
    if t.starts_with('<') || t.starts_with('[') || t.starts_with('(') {
        return true;
    }
    let clean = t.trim_end_matches(',');
    if clean.is_empty() {
        return false;
    }
    let lower = clean.to_lowercase();
    if [
        "string",
        "number",
        "integer",
        "boolean",
        "bool",
        "path",
        "file",
        "dir",
        "directory",
        "value",
        "val",
        "name",
    ]
    .contains(&lower.as_str())
    {
        return true;
    }
    let mut has_letter = false;
    let mut all_upper = true;
    for c in clean.chars() {
        if c.is_alphabetic() {
            has_letter = true;
            if !c.is_uppercase() {
                all_upper = false;
            }
        }
    }
    has_letter && all_upper
}

fn split_option_line(flag_part: &str) -> (&str, Option<String>) {
    let mut search_start = 0;
    while let Some(pos) = flag_part[search_start..].find("  ") {
        let actual_pos = search_start + pos;
        let prefix = &flag_part[..actual_pos];
        let remainder = flag_part[actual_pos..].trim();

        // Check if the remainder starts with a flag (e.g., --long or -l)
        let starts_with_flag = remainder.starts_with("--")
            && remainder
                .chars()
                .nth(2)
                .map_or(false, |c| c.is_alphanumeric() || c == '-');
        let starts_with_short = remainder.starts_with('-')
            && remainder
                .chars()
                .nth(1)
                .map_or(false, |c| c.is_alphanumeric());

        if starts_with_flag || starts_with_short {
            // Skip this double space and keep searching
            search_start = actual_pos + 2;
            continue;
        }

        let desc = if remainder.is_empty() {
            None
        } else {
            Some(remainder.to_string())
        };
        return (prefix, desc);
    }

    let tokens: Vec<&str> = flag_part.split_whitespace().collect();
    let mut prefix_tokens_count = 0;
    let mut seen_flag = false;

    for &t in &tokens {
        if t.starts_with('-') {
            seen_flag = true;
            prefix_tokens_count += 1;
        } else if seen_flag && (t == "," || t == "|" || t == "/" || t == "or") {
            prefix_tokens_count += 1;
        } else if seen_flag && is_like_value_name(t) {
            prefix_tokens_count += 1;
        } else {
            break;
        }
    }

    if prefix_tokens_count == 0 {
        return (flag_part, None);
    }

    let mut pos = 0;
    let mut count = 0;
    let mut in_whitespace = true;
    for (idx, c) in flag_part.char_indices() {
        if c.is_whitespace() {
            in_whitespace = true;
        } else {
            if in_whitespace {
                in_whitespace = false;
                count += 1;
                if count > prefix_tokens_count {
                    pos = idx;
                    break;
                }
            }
        }
    }

    if pos > 0 {
        let prefix = &flag_part[..pos];
        let desc = flag_part[pos..].trim().to_string();
        let desc_opt = if desc.is_empty() { None } else { Some(desc) };
        (prefix, desc_opt)
    } else {
        (flag_part, None)
    }
}

/// Parse an EBNF-style command help generically.
pub fn parse_help_ebnf(help: &str) -> Command {
    let mut cmd = Command::default();

    // Generically extract the command name from Usage: or usage:
    for line in help.lines() {
        let trimmed = line.trim();
        if trimmed.to_lowercase().starts_with("usage:") {
            let after = trimmed["usage:".len()..].trim();
            if let Some(name_part) = after.split_whitespace().next() {
                cmd.name = Some(name_part.to_string());
                break;
            }
        }
    }
    if cmd.name.is_none() {
        cmd.name = Some("ip".to_string());
    }

    // Parse all variables of form NAME := { ... }
    let mut search_idx = 0;
    while let Some(assign_pos) = help[search_idx..].find(":=") {
        let abs_assign_pos = search_idx + assign_pos;
        let pre_assign = &help[..abs_assign_pos];
        let mut var_name = "";
        if let Some(last_line) = pre_assign.lines().last() {
            let last_line_trimmed = last_line.trim();
            if let Some(word) = last_line_trimmed.split_whitespace().last() {
                let clean_word =
                    word.trim_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '-');
                if !clean_word.is_empty() {
                    var_name = clean_word;
                }
            }
        }

        let post_assign = &help[abs_assign_pos + 2..];
        if let Some(brace_start) = post_assign.find('{') {
            let abs_brace_start = abs_assign_pos + 2 + brace_start;
            let mut depth = 0;
            let mut brace_end_pos = None;
            for (idx, c) in help[abs_brace_start..].char_indices() {
                if c == '{' {
                    depth += 1;
                } else if c == '}' {
                    depth -= 1;
                    if depth == 0 {
                        brace_end_pos = Some(abs_brace_start + idx);
                        break;
                    }
                }
            }

            if let Some(abs_brace_end) = brace_end_pos {
                let content = &help[abs_brace_start + 1..abs_brace_end];
                let var_name_lower = var_name.to_lowercase();
                let is_options = var_name_lower.contains("option");
                let is_subcommands =
                    var_name_lower.contains("object") || var_name_lower.contains("command");

                let parts = split_top_level(content, '|');
                for part in parts {
                    let part_trimmed = part.trim();
                    if part_trimmed.is_empty() {
                        continue;
                    }

                    if is_options {
                        if part_trimmed.starts_with('-') {
                            let clean_opt = if let Some(bracket_pos) = part_trimmed.find('[') {
                                &part_trimmed[..bracket_pos]
                            } else {
                                part_trimmed
                            };
                            let clean_opt =
                                clean_opt.split_whitespace().next().unwrap_or(clean_opt);

                            let mut value_enum = None;
                            if let Some(inner_brace_start) = part_trimmed.find('{') {
                                if let Some(inner_brace_end) =
                                    part_trimmed[inner_brace_start..].find('}')
                                {
                                    let inner_content = &part_trimmed[inner_brace_start + 1
                                        ..inner_brace_start + inner_brace_end];
                                    let possible_values = split_top_level(inner_content, '|');
                                    if !possible_values.is_empty() {
                                        value_enum = Some(
                                            possible_values
                                                .into_iter()
                                                .map(|s| s.trim().to_string())
                                                .collect(),
                                        );
                                    }
                                }
                            }

                            if clean_opt.starts_with("--") {
                                cmd.args.push(Arg {
                                    long: Some(clean_opt.to_string()),
                                    value_enum,
                                    ..Arg::default()
                                });
                            } else if clean_opt.starts_with('-') {
                                cmd.args.push(Arg {
                                    short: Some(clean_opt.to_string()),
                                    value_enum,
                                    ..Arg::default()
                                });
                            }
                        }
                    } else if is_subcommands {
                        let name = part_trimmed
                            .split_whitespace()
                            .next()
                            .unwrap_or(part_trimmed)
                            .to_string();
                        if !name.is_empty() {
                            cmd.subcommands.push(Command {
                                name: Some(name),
                                ..Command::default()
                            });
                        }
                    }
                }
                search_idx = abs_brace_end + 1;
                continue;
            }
        }
        search_idx = abs_assign_pos + 2;
    }

    cmd
}

/// Leading-space count for a line (tabs count as 1).
fn indent_of(line: &str) -> usize {
    line.chars().take_while(|c| *c == ' ' || *c == '\t').count()
}

fn is_valid_flag_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    let stripped = name.trim_start_matches('-');
    if stripped.is_empty() {
        return false;
    }
    for c in stripped.chars() {
        if !c.is_alphanumeric() && c != '-' && c != '_' && c != '[' && c != ']' && c != '#' {
            return false;
        }
    }
    true
}

fn is_valid_subcommand_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    let first_char = name.chars().next().unwrap();
    if !first_char.is_alphanumeric() {
        return false;
    }
    name.chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == ':' || c == '.')
}

/// Try to parse a flag token like `-v`, `--verbose`, or `--output <FILE>`.
/// Returns `(short, longs, value_name, num_args)`.
pub(crate) fn parse_flag_tokens(
    token: &str,
) -> (Option<String>, Vec<String>, Option<String>, Option<String>) {
    // Split on commas / whitespace to handle "-v, --verbose <FILE>"
    let mut short = None;
    let mut real_longs = Vec::new();
    let mut fallback_longs = Vec::new();
    let mut value_name = None;
    let mut num_args = None;

    // Tokenise: split on ", " first, then whitespace
    let pieces: Vec<&str> = token.split_whitespace().collect();

    // First pass to extract value_name from pieces
    let mut extracted_val = None;
    for &piece in &pieces {
        if piece.starts_with("--") {
            let piece_str = piece.to_string();
            if let Some(start_bracket) = piece_str.find("[=") {
                if let Some(end_bracket) = piece_str.rfind(']') {
                    if end_bracket > start_bracket {
                        let val = &piece_str[start_bracket + 2..end_bracket];
                        extracted_val =
                            Some(val.trim_matches(|c| c == '<' || c == '>').to_string());
                    }
                }
            }
            if extracted_val.is_none() {
                if let Some((_, val)) = piece_str.split_once('=') {
                    extracted_val = Some(val.trim_matches(|c| c == '<' || c == '>').to_string());
                }
            }
        } else if piece.starts_with('<') || piece.starts_with('[') {
            if extracted_val.is_none() {
                extracted_val = Some(
                    piece
                        .trim_matches(|c| c == '<' || c == '>' || c == '[' || c == ']')
                        .to_string(),
                );
            }
        }
    }

    for &piece in &pieces {
        if piece.starts_with("--") {
            // May be "--flag" or "--flag=<VAL>" or "--flag[=<VAL>]"
            let mut piece_str = piece.to_string();
            // Handle optional value syntax like --untracked-files[=<mode>]
            if let Some(start_bracket) = piece_str.find("[=") {
                if let Some(end_bracket) = piece_str.rfind(']') {
                    if end_bracket > start_bracket {
                        let val = &piece_str[start_bracket + 2..end_bracket];
                        value_name = Some(val.trim_matches(|c| c == '<' || c == '>').to_string());
                        piece_str.drain(start_bracket..=end_bracket);
                        num_args = Some("?".to_string());
                    }
                }
            }

            let check_len = piece_str.find('=').unwrap_or(piece_str.len());
            if let Some(bracket_idx) = piece_str[..check_len].find('[') {
                let suffix = &piece_str[bracket_idx..];
                if !suffix.starts_with("[no-]") && !suffix.starts_with("[no]") {
                    piece_str = piece_str[..bracket_idx].to_string();
                }
            }

            let parsed_long = if let Some((flag, val)) = piece_str.split_once('=') {
                value_name = Some(val.trim_matches(|c| c == '<' || c == '>').to_string());
                flag.trim_end_matches(',').trim_end_matches('.').to_string()
            } else {
                let mut l = piece_str.trim_end_matches(',').to_string();
                while l.ends_with('.') {
                    l.pop();
                }
                l
            };
            if !real_longs.contains(&parsed_long) {
                real_longs.push(parsed_long);
            }
        } else if let Some(short_candidate) = piece.strip_prefix('-') {
            let mut short_candidate = short_candidate.trim_end_matches(',').to_string();

            // Only treat single-character forms like `-v` as clap short flags.
            // Multi-character forms such as `-wk`, `-wK`, or `-U[dlexhi]` are
            // command-specific syntax, not plain one-letter short options.
            // But we do handle bracketed optional parts like `-u[<mode>]` or `-u[mode]`.
            // We also allow forms ending with '#' (like `-T#` or `-b#`).
            let mut is_bracketed_short = false;
            if let Some(start_bracket) = short_candidate.find('[') {
                if let Some(end_bracket) = short_candidate.rfind(']') {
                    if end_bracket > start_bracket {
                        let val = &short_candidate[start_bracket + 1..end_bracket];
                        let base = &short_candidate[..start_bracket];
                        if base.chars().count() == 1 {
                            // Treat it as a short flag with optional value if the bracketed part
                            // looks like a value name (contains lowercase or angle brackets).
                            if val
                                .chars()
                                .any(|c| c.is_alphabetic() || c == '<' || c == '>')
                            {
                                if value_name.is_none() {
                                    value_name = Some(
                                        val.trim_matches(|c| c == '<' || c == '>').to_string(),
                                    );
                                }
                                short_candidate = base.to_string();
                                is_bracketed_short = true;
                                num_args = Some("?".to_string());
                            }
                        }
                    }
                }
            }

            let chars: Vec<char> = short_candidate.chars().collect();
            let mut is_wn_edgecase = false;
            if chars.len() >= 2 && chars[0].is_alphabetic() {
                if let Some(ref val_name) = extracted_val {
                    if short_candidate.ends_with(val_name) && short_candidate.len() > val_name.len()
                    {
                        let prefix = &short_candidate[..short_candidate.len() - val_name.len()];
                        if prefix.chars().count() == 1 {
                            short = Some(format!("-{prefix}"));
                            if value_name.is_none() {
                                value_name = Some(val_name.clone());
                                num_args = Some("1".to_string());
                            }
                            is_wn_edgecase = true;
                        }
                    }
                } else {
                    let suffix: String = chars[1..].iter().collect();
                    if !suffix.is_empty()
                        && suffix
                            .chars()
                            .all(|c| c.is_uppercase() && c.is_alphabetic())
                    {
                        short = Some(format!("-{}", chars[0]));
                        if value_name.is_none() {
                            value_name = Some(suffix);
                            num_args = Some("1".to_string());
                        }
                        is_wn_edgecase = true;
                    }
                }
            }

            let count = short_candidate.chars().count();
            if is_wn_edgecase {
                // Handled
            } else if count == 1
                || (count == 2 && short_candidate.ends_with('#'))
                || is_bracketed_short
            {
                let candidate_short = format!("-{short_candidate}");
                if is_valid_flag_name(&candidate_short) {
                    short = Some(candidate_short);
                }
            } else if count > 1 {
                let l = format!("--{short_candidate}");
                if !fallback_longs.contains(&l) {
                    fallback_longs.push(l);
                }
            }
        } else if piece.starts_with('<') || piece.starts_with('[') {
            // Meta-variable — only capture the first one found so that description
            // text like `[default: 10]` does not overwrite an already-parsed hint.
            // Subsequent bracketed tokens (e.g. `[boolean]`, `[default: …]`) are
            // intentionally ignored once a value-type has been established.
            if value_name.is_none() {
                value_name = Some(
                    piece
                        .trim_matches(|c| c == '<' || c == '>' || c == '[' || c == ']')
                        .to_string(),
                );
            }
        } else if value_name.is_none()
            && !piece.is_empty()
            && !piece.starts_with('-')
            && piece != ","
            && piece != "|"
            && piece != "/"
            && piece != "or"
        {
            let clean = piece.trim_end_matches(',');
            if !clean.is_empty() {
                value_name = Some(clean.to_string());
            }
        }
    }

    if let Some(ref s) = short {
        if !is_valid_flag_name(s) {
            short = None;
        }
    }

    let mut longs = if !real_longs.is_empty() {
        real_longs
    } else {
        fallback_longs
    };
    longs.retain(|l| is_valid_flag_name(l));

    if num_args.is_none() {
        let mut num_values = 0;
        let mut seen_any_flag = false;
        for &piece in &pieces {
            if piece.starts_with('-') {
                seen_any_flag = true;
                num_values = 0;
            } else if seen_any_flag && is_like_value_name(piece) {
                num_values += 1;
            } else if seen_any_flag
                && (piece == "," || piece == "|" || piece == "/" || piece == "or")
            {
                // separator
            } else {
                if seen_any_flag {
                    break;
                }
            }
        }
        if num_values > 0 {
            let first_val = pieces.iter().filter(|&p| is_like_value_name(p)).next();
            if num_values == 1
                && first_val.map_or(false, |p| p.starts_with('[') && p.ends_with(']'))
            {
                num_args = Some("?".to_string());
            } else {
                num_args = Some(num_values.to_string());
            }
        } else if value_name.is_some() {
            num_args = Some("1".to_string());
        }
    }

    (short, longs, value_name, num_args)
}

fn detect_description_column(lines: &[&str]) -> Option<usize> {
    use std::collections::HashMap;
    let mut counts = HashMap::new();
    for line in lines {
        let trimmed = line.trim_start();
        if trimmed.starts_with('-') {
            if let Some(pos) = line.find("  ") {
                let mut desc_start = pos;
                let chars: Vec<char> = line.chars().collect();
                while desc_start < chars.len() && chars[desc_start].is_whitespace() {
                    desc_start += 1;
                }
                if desc_start < chars.len() {
                    *counts.entry(desc_start).or_insert(0) += 1;
                }
            }
        }
    }
    counts
        .into_iter()
        .max_by_key(|&(_, count)| count)
        .map(|(col, _)| col)
}

fn is_flag_declaration_line(line: &str) -> bool {
    let trimmed = line.trim();
    if !trimmed.starts_with('-') {
        return false;
    }
    let (token_part, _) = split_option_line(trimmed);
    let (short, longs, _, _) = parse_flag_tokens(token_part);
    short.is_some() || !longs.is_empty()
}

/// Collect continuation lines: lines whose indent > `base_indent` (or blank).
/// Returns the combined description string.
fn collect_continuation<'a>(
    lines: &'a [&'a str],
    start: usize,
    base_indent: usize,
    desc_col: Option<usize>,
) -> (String, usize) {
    let mut desc_parts = Vec::new();
    let mut i = start;
    while i < lines.len() {
        let line = lines[i];
        if line.trim().is_empty() {
            let mut next_is_continuation = false;
            let mut j = i + 1;
            while j < lines.len() {
                let next_line = lines[j];
                if next_line.trim().is_empty() {
                    j += 1;
                    continue;
                }
                let ind = indent_of(next_line);
                let is_aligned = if let Some(col) = desc_col {
                    ind >= col.saturating_sub(2) && ind > base_indent
                } else {
                    ind > base_indent
                };
                if is_aligned && !is_flag_declaration_line(next_line) {
                    next_is_continuation = true;
                }
                break;
            }
            if next_is_continuation {
                i = j;
                continue;
            } else {
                break;
            }
        }
        let ind = indent_of(line);
        let is_aligned = if let Some(col) = desc_col {
            ind >= col.saturating_sub(2) && ind > base_indent
        } else {
            ind > base_indent
        };
        if !is_aligned {
            break;
        }
        // A deeper-indented line that starts with `-` is another flag entry,
        // not description text. This handles tools like cargo that mix indent
        // levels within a single Options section.
        if is_flag_declaration_line(line) {
            break;
        }
        desc_parts.push(line.trim().to_string());
        i += 1;
    }
    (desc_parts.join(" "), i)
}

/// Parse clap-style `--help` output.
pub fn parse_help_clap(help: &str) -> Command {
    let lines: Vec<&str> = help.lines().collect();
    let desc_col = detect_description_column(&lines);
    let mut cmd = Command::default();

    if let Some(usage_pos) = lines.iter().position(|l| {
        let lower = l.trim_start().to_lowercase();
        lower.starts_with("usage:") || lower.starts_with("usage of ")
    }) {
        let mut full_usage = lines[usage_pos].trim_start().to_string();
        let mut j = usage_pos + 1;
        while j < lines.len() && !lines[j].trim().is_empty() && indent_of(lines[j]) > 0 {
            let trimmed_next = lines[j].trim();
            if trimmed_next.starts_with('-') {
                break;
            }
            full_usage.push(' ');
            full_usage.push_str(trimmed_next);
            j += 1;
        }

        let after = if full_usage.to_lowercase().starts_with("usage:") {
            &full_usage["usage:".len()..]
        } else if full_usage.to_lowercase().starts_with("usage of ") {
            &full_usage["usage of ".len()..]
        } else {
            &full_usage
        };
        let after = after.trim().trim_end_matches(':').trim();
        if let Some(name_part) = after.split_whitespace().next() {
            cmd.name = Some(name_part.trim_end_matches(':').to_string());
        } else {
            for next_line in &lines[usage_pos + 1..] {
                let t = next_line.trim();
                if !t.is_empty() {
                    if let Some(name_part) = t.split_whitespace().next() {
                        cmd.name = Some(name_part.trim_end_matches(':').to_string());
                    }
                    break;
                }
            }
        }
    }

    let usage_pos = lines
        .iter()
        .position(|l| {
            let lower = l.trim_start().to_lowercase();
            lower.starts_with("usage:") || lower.starts_with("usage of ")
        })
        .unwrap_or(0);
    for line in &lines[..usage_pos] {
        let t = line.trim();
        if !t.is_empty() {
            let is_header = t.starts_with("***")
                || t.contains(" version ")
                || t.contains(" v1.")
                || t.contains(" v2.")
                || t.contains(" v0.")
                || t.contains("by ")
                || t.contains("Copyright");
            if !is_header {
                cmd.description = Some(t.to_string());
                break;
            }
        }
    }

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim();

        let lower = trimmed.to_lowercase();
        let is_commands_section = trimmed == "Commands:"
            || trimmed == "Subcommands:"
            || trimmed == "Available Commands:"
            || (lower.contains("common") && lower.contains("commands"))
            || lower.contains("commands used in")
            || (lower.contains("commands")
                && ((trimmed.ends_with(':') && trimmed.split_whitespace().count() <= 3)
                    || lower.contains("commands are")
                    || (trimmed
                        .chars()
                        .all(|c| c.is_uppercase() || c.is_whitespace() || c == '-')
                        && !trimmed.is_empty())));

        if is_commands_section {
            i += 1;
            while i < lines.len() && lines[i].trim().is_empty() {
                i += 1;
            }
            let mut first_indent = None;
            let section_start_line = i;

            while i < lines.len() {
                let line = lines[i];
                if line.trim().is_empty() {
                    let mut has_more = false;
                    for next_line in &lines[i + 1..] {
                        let trimmed_next = next_line.trim();
                        if trimmed_next.is_empty() {
                            continue;
                        }
                        let next_indent = indent_of(next_line);
                        if next_indent > 0 {
                            has_more = true;
                        } else {
                            // If we encounter a line with 0 indent, check if it's a known section
                            let lower_next = trimmed_next.to_lowercase();
                            if lower_next.contains("options")
                                || lower_next.contains("flags")
                                || lower_next.contains("usage:")
                            {
                                has_more = false;
                            } else {
                                // Probably a group header, keep going
                                has_more = true;
                            }
                        }
                        break;
                    }
                    if !has_more {
                        i += 1;
                        break;
                    } else {
                        i += 1;
                        continue;
                    }
                }

                if indent_of(line) == 0 && !line.trim().is_empty() && i > section_start_line {
                    // Check if it's a known non-command section like "Options:" or "Usage:"
                    let t = line.trim().to_lowercase();
                    if t.contains("options") || t.contains("flags") || t.contains("usage:") {
                        break;
                    }
                }

                let indent = indent_of(line);
                if first_indent.is_none() {
                    // The first non-empty line after the commands section header
                    // might be a group header if it is not indented.
                    if indent > 0 {
                        first_indent = Some(indent);
                    } else {
                        i += 1;
                        continue;
                    }
                } else if indent < first_indent.unwrap() {
                    // Possible group header or end of section.
                    // If it's not indented or less indented, it might be a group header.
                    // We skip it and keep looking for indented subcommands.
                    i += 1;
                    continue;
                } else if indent > first_indent.unwrap() {
                    // More indented than subcommands, might be a continuation of description
                    i += 1;
                    continue;
                }
                let trimmed_line = line.trim();
                let mut parts = trimmed_line.splitn(2, "  ");
                let sub_names_part = parts.next().unwrap_or("").trim();
                let sub_desc = parts.next().map(|s| s.trim().to_string());
                if !sub_names_part.is_empty() {
                    let name_parts: Vec<String> = sub_names_part
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .collect();
                    if let Some(first_name) = name_parts.first() {
                        if !first_name.is_empty() {
                            let mut first_name_clean = first_name.trim_end_matches(':').to_string();
                            let mut sub_desc = sub_desc;
                            if first_name_clean.contains(" - ") {
                                let (name, desc) = {
                                    let mut parts = first_name_clean.splitn(2, " - ");
                                    let name = parts.next().unwrap().trim().to_string();
                                    let desc = parts.next().map(|s| s.trim().to_string());
                                    (name, desc)
                                };
                                first_name_clean = name;
                                if sub_desc.is_none() {
                                    sub_desc = desc;
                                }
                            }
                            if let Some(space_pos) = first_name_clean
                                .find(|c: char| c.is_whitespace() || c == '<' || c == '[')
                            {
                                first_name_clean = first_name_clean[..space_pos].trim().to_string();
                            }
                            if first_name_clean != "..."
                                && !first_name_clean.is_empty()
                                && is_valid_subcommand_name(&first_name_clean)
                            {
                                if sub_desc.is_none() && name_parts.len() > 1 {
                                    // Treat all comma-separated names as separate subcommands (e.g. npm)
                                    cmd.subcommands.push(Command {
                                        name: Some(first_name_clean),
                                        ..Command::default()
                                    });
                                    for alias in name_parts.iter().skip(1) {
                                        let mut alias_clean =
                                            alias.trim_end_matches(':').to_string();
                                        if alias_clean.contains(" - ") {
                                            let mut parts = alias_clean.splitn(2, " - ");
                                            alias_clean = parts.next().unwrap().trim().to_string();
                                        }
                                        if let Some(space_pos) = alias_clean.find(|c: char| {
                                            c.is_whitespace() || c == '<' || c == '['
                                        }) {
                                            alias_clean =
                                                alias_clean[..space_pos].trim().to_string();
                                        }
                                        if !alias_clean.is_empty()
                                            && is_valid_subcommand_name(&alias_clean)
                                        {
                                            cmd.subcommands.push(Command {
                                                name: Some(alias_clean),
                                                ..Command::default()
                                            });
                                        }
                                    }
                                } else {
                                    let aliases: Vec<String> = name_parts
                                        .iter()
                                        .skip(1)
                                        .filter(|s| !s.is_empty())
                                        .map(|s| {
                                            let mut a = s.trim_end_matches(':').to_string();
                                            if a.contains(" - ") {
                                                if let Some(first) = a.split(" - ").next() {
                                                    a = first.trim().to_string();
                                                }
                                            }
                                            if let Some(space_pos) = a.find(|c: char| {
                                                c.is_whitespace() || c == '<' || c == '['
                                            }) {
                                                a = a[..space_pos].trim().to_string();
                                            }
                                            a
                                        })
                                        .filter(|s| !s.is_empty() && is_valid_subcommand_name(s))
                                        .collect();
                                    cmd.subcommands.push(Command {
                                        name: Some(first_name_clean),
                                        aliases,
                                        description: sub_desc,
                                        ..Command::default()
                                    });
                                }
                            }
                        }
                    }
                }
                i += 1;
            }
            continue;
        }

        let is_options_section = (trimmed.ends_with(':')
            || (trimmed
                .chars()
                .all(|c| c.is_uppercase() || c.is_whitespace() || c == '-')
                && !trimmed.is_empty())
            || {
                let lower = trimmed.to_lowercase();
                lower == "options" || lower == "flags" || lower == "arguments" || lower == "args"
            })
            && {
                let lower = trimmed.to_lowercase();
                lower.contains("options")
                    || lower.contains("flags")
                    || lower.contains("arguments")
                    || lower.contains("args")
                    || lower.contains("builder")
                    || lower.contains("parameters")
                    || lower.contains("settings")
                    || lower.contains("control")
                    || lower.contains("selection")
                    || lower.contains("miscellaneous")
                    || lower.contains("interpretation")
                    || lower.starts_with("usage of ")
            };

        if is_options_section {
            i += 1;
            while i < lines.len() {
                let line = lines[i];
                if line.trim().is_empty() {
                    i += 1;
                    continue;
                }
                if indent_of(line) == 0 {
                    let trimmed = line.trim();
                    if !trimmed.starts_with('-') && !trimmed.starts_with('[') {
                        break;
                    }
                }
                let flag_indent = indent_of(line);
                let flag_part = line.trim();

                if !flag_part.starts_with('-') && !flag_part.starts_with('[') {
                    i += 1;
                    continue;
                }

                let (token_part, inline_desc) = split_option_line(flag_part);
                let (short, longs, value_name, num_args) = parse_flag_tokens(token_part);

                if short.is_some() || !longs.is_empty() || flag_part.starts_with('[') {
                    let (cont_desc, next_i) =
                        collect_continuation(&lines, i + 1, flag_indent, desc_col);
                    i = next_i;

                    let mut description = match (inline_desc, cont_desc.as_str()) {
                        (Some(d), "") => Some(d),
                        (None, d) if !d.is_empty() => Some(d.to_string()),
                        (Some(d), rest) => Some(format!("{} {}", d, rest)),
                        (None, _) => None,
                    };

                    if let Some(bracket_idx) = token_part.find('[') {
                        let bracketed_part = &token_part[bracket_idx..];
                        description = Some(match description {
                            Some(desc) => format!("{} {}", bracketed_part, desc),
                            None => bracketed_part.to_string(),
                        });
                    }

                    let mut first_long = None;
                    let mut extra_longs = Vec::new();
                    if !longs.is_empty() {
                        first_long = Some(longs[0].clone());
                        extra_longs = longs[1..].to_vec();
                    }

                    cmd.args.push(Arg {
                        short,
                        long: first_long,
                        description: description.clone(),
                        value_name: value_name.clone(),
                        num_args: num_args.clone(),
                        ..Default::default()
                    });

                    for extra_long in extra_longs {
                        cmd.args.push(Arg {
                            short: None,
                            long: Some(extra_long),
                            description: description.clone(),
                            value_name: value_name.clone(),
                            num_args: num_args.clone(),
                            ..Default::default()
                        });
                    }
                } else {
                    i += 1;
                }
            }
            continue;
        }

        i += 1;
    }

    cmd
}

/// Parse Python argparse-style `--help` output.
pub fn parse_help_argparse(help: &str) -> Command {
    let lines: Vec<&str> = help.lines().collect();
    let desc_col = detect_description_column(&lines);
    let mut cmd = Command::default();

    if let Some(usage_line) = lines
        .iter()
        .find(|l| l.trim_start().to_lowercase().starts_with("usage:"))
    {
        let after = usage_line
            .trim_start_matches(|c: char| c.is_whitespace())
            .to_lowercase();
        let after = after.strip_prefix("usage:").unwrap_or(&after).trim();
        if let Some(name) = after.split_whitespace().next() {
            cmd.name = Some(name.to_string());
        }
    }

    let usage_pos = lines
        .iter()
        .position(|l| l.trim_start().to_lowercase().starts_with("usage:"))
        .unwrap_or(0);
    let mut found_blank = false;
    for line in &lines[usage_pos + 1..] {
        if line.trim().is_empty() {
            found_blank = true;
        } else if found_blank {
            let t = line.trim();
            if !t.ends_with(':') {
                cmd.description = Some(t.to_string());
            }
            break;
        }
    }

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim();

        let is_args_section = trimmed == "positional arguments:"
            || trimmed == "optional arguments:"
            || trimmed == "options:"
            || trimmed.starts_with("named arguments:");

        if is_args_section {
            i += 1;
            while i < lines.len() {
                let line = lines[i];
                if line.trim().is_empty() {
                    i += 1;
                    break;
                }
                if indent_of(line) == 0 && line.trim().ends_with(':') {
                    break;
                }
                let flag_indent = indent_of(line);
                let flag_part = line.trim();

                let (token_part, inline_desc) = split_option_line(flag_part);
                let (short, longs, value_name, num_args) = if flag_part.starts_with('-') {
                    parse_flag_tokens(token_part)
                } else {
                    let name_token = token_part.split_whitespace().next().unwrap_or("");
                    (None, vec![name_token.to_string()], None, None)
                };

                if short.is_some() || !longs.is_empty() || !flag_part.starts_with('-') {
                    let (cont_desc, next_i) =
                        collect_continuation(&lines, i + 1, flag_indent, desc_col);
                    i = next_i;

                    let mut description = match (inline_desc, cont_desc.as_str()) {
                        (Some(d), "") => Some(d),
                        (None, d) if !d.is_empty() => Some(d.to_string()),
                        (Some(d), rest) => Some(format!("{} {}", d, rest)),
                        (None, _) => None,
                    };

                    if let Some(bracket_idx) = token_part.find('[') {
                        let bracketed_part = &token_part[bracket_idx..];
                        description = Some(match description {
                            Some(desc) => format!("{} {}", bracketed_part, desc),
                            None => bracketed_part.to_string(),
                        });
                    }

                    let mut first_long = None;
                    let mut extra_longs = Vec::new();
                    if !longs.is_empty() {
                        first_long = Some(longs[0].clone());
                        extra_longs = longs[1..].to_vec();
                    }

                    cmd.args.push(Arg {
                        short,
                        long: first_long,
                        description: description.clone(),
                        value_name: value_name.clone(),
                        num_args: num_args.clone(),
                        ..Default::default()
                    });

                    for extra_long in extra_longs {
                        cmd.args.push(Arg {
                            short: None,
                            long: Some(extra_long),
                            description: description.clone(),
                            value_name: value_name.clone(),
                            num_args: num_args.clone(),
                            ..Default::default()
                        });
                    }
                } else {
                    i += 1;
                }
            }
            continue;
        }

        i += 1;
    }

    cmd
}

/// Fallback parser for unrecognised help formats.
pub fn parse_help_generic(help: &str) -> Command {
    let lines: Vec<&str> = help.lines().collect();
    let desc_col = detect_description_column(&lines);
    let mut cmd = Command::default();

    for line in &lines {
        let lower = line.trim().to_lowercase();
        if lower.starts_with("usage:") {
            let after = line
                .trim()
                .trim_start_matches(|c: char| c.is_alphabetic() || c == ':')
                .trim();
            if let Some(name) = after.split_whitespace().next() {
                cmd.name = Some(name.to_string());
                break;
            }
        }
    }

    for line in &lines {
        let t = line.trim();
        if !t.is_empty() && !t.starts_with('-') && !t.to_lowercase().starts_with("usage:") {
            cmd.description = Some(t.to_string());
            break;
        }
    }

    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];
        let flag_part = line.trim();

        if flag_part.starts_with('-') {
            let flag_indent = indent_of(line);
            let (token_part, inline_desc) = split_option_line(flag_part);
            let (short, longs, value_name, num_args) = parse_flag_tokens(token_part);

            if short.is_some() || !longs.is_empty() {
                let (cont_desc, next_i) =
                    collect_continuation(&lines, i + 1, flag_indent, desc_col);
                i = next_i;

                let mut description = match (inline_desc, cont_desc.as_str()) {
                    (Some(d), "") => Some(d),
                    (None, d) if !d.is_empty() => Some(d.to_string()),
                    (Some(d), rest) => Some(format!("{} {}", d, rest)),
                    (None, _) => None,
                };

                if let Some(bracket_idx) = token_part.find('[') {
                    let bracketed_part = &token_part[bracket_idx..];
                    description = Some(match description {
                        Some(desc) => format!("{} {}", bracketed_part, desc),
                        None => bracketed_part.to_string(),
                    });
                }

                let mut first_long = None;
                let mut extra_longs = Vec::new();
                if !longs.is_empty() {
                    first_long = Some(longs[0].clone());
                    extra_longs = longs[1..].to_vec();
                }

                cmd.args.push(Arg {
                    short,
                    long: first_long,
                    description: description.clone(),
                    value_name: value_name.clone(),
                    num_args: num_args.clone(),
                    ..Default::default()
                });

                for extra_long in extra_longs {
                    cmd.args.push(Arg {
                        short: None,
                        long: Some(extra_long),
                        description: description.clone(),
                        value_name: value_name.clone(),
                        num_args: num_args.clone(),
                        ..Default::default()
                    });
                }
                continue;
            }
        }

        i += 1;
    }

    cmd
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::*;
    use crate::{SynthesisStrategy, ValueHint, synthesize_completion};

    fn long_names(cmd: &Command) -> Vec<&str> {
        cmd.args.iter().filter_map(|a| a.long.as_deref()).collect()
    }

    fn short_names(cmd: &Command) -> Vec<&str> {
        cmd.args.iter().filter_map(|a| a.short.as_deref()).collect()
    }

    fn subcommand_names(cmd: &Command) -> Vec<&str> {
        cmd.subcommands
            .iter()
            .filter_map(|s| s.name.as_deref())
            .collect()
    }

    fn arg_by_long<'a>(cmd: &'a Command, long: &str) -> Option<&'a Arg> {
        cmd.args.iter().find(|a| a.long.as_deref() == Some(long))
    }

    fn subcommand_by_name<'a>(cmd: &'a Command, name: &str) -> Option<&'a Command> {
        cmd.subcommands
            .iter()
            .find(|s| s.name.as_deref() == Some(name))
    }

    #[test]
    fn test_flyline_help_clap() {
        let cmd = parse_help(&read_fixture(&["flyline"]));
        assert_eq!(cmd.name.as_deref(), Some("flyline"));

        assert_contains_subcommands(
            &cmd,
            &[
                ("set-agent-mode", "Configure AI agent mode."),
                ("dump-logs", "Dump in-memory logs to file."),
                (
                    "stream-logs",
                    "Dump current logs to PATH and append new logs.",
                ),
                (
                    "run-tutorial",
                    "Run the interactive tutorial for first-time users.",
                ),
            ],
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show version information",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--log-level".to_string()),
                        value_name: Some("LEVEL".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "error".to_string(),
                            "warn".to_string(),
                            "info".to_string(),
                            "debug".to_string(),
                            "trace".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "logging level",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--show-animations".to_string()),
                        value_name: Some("SHOW_ANIMATIONS".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec!["true".to_string(), "false".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--show-inline-history".to_string()),
                        value_name: Some("SHOW_INLINE_HISTORY".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec!["true".to_string(), "false".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--auto-close-chars".to_string()),
                        value_name: Some("AUTO_CLOSE_CHARS".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec!["true".to_string(), "false".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--enable-extended-key-codes".to_string()),
                        value_name: Some("ENABLE_EXTENDED_KEY_CODES".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec!["true".to_string(), "false".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "",
                },
            ],
        );
    }

    #[test]
    fn test_flyline_create_anim_help_clap() {
        let cmd = parse_help(&read_fixture(&["flyline", "create-anim"]));
        assert_eq!(cmd.name.as_deref(), Some("flyline"));
        assert!(
            cmd.description
                .as_deref()
                .unwrap_or("")
                .contains("animation")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--name".to_string()),
                        value_name: Some("NAME".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "animation placeholder",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--fps".to_string()),
                        value_name: Some("FPS".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "frames per second",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--ping-pong".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Reverse direction",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print help",
                },
            ],
        );
    }

    #[test]
    fn test_cargo_help_clap() {
        let cmd = parse_help(&read_fixture(&["cargo"]));
        assert_eq!(cmd.name.as_deref(), Some("cargo"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print version info",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Do not print cargo log messages",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--explain".to_string()),
                        value_name: Some("CODE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Run `rustc --explain CODE`",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--color".to_string()),
                        value_name: Some("WHEN".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Coloring",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print help",
                },
            ],
        );

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"build"));
        assert!(subs.contains(&"check"));
        assert!(subs.contains(&"clean"));

        let build_sub = subcommand_by_name(&cmd, "build").unwrap();
        assert_eq!(build_sub.aliases, vec!["b".to_string()]);
        assert_eq!(
            build_sub.description.as_deref(),
            Some("Compile the current package")
        );

        let check_sub = subcommand_by_name(&cmd, "check").unwrap();
        assert_eq!(check_sub.aliases, vec!["c".to_string()]);
        assert_eq!(
            check_sub.description.as_deref(),
            Some("Analyze the current package and report errors, but don't build object files")
        );
    }

    #[test]
    fn test_python_help_generic() {
        let cmd = parse_help(&read_fixture(&["python"]));
        assert_eq!(cmd.name.as_deref(), Some("python3"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print this help message",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        ..Default::default()
                    },
                    description_contains: "verbose",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the Python version number",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        ..Default::default()
                    },
                    description_contains: "don't print version and copyright",
                },
            ],
        );
    }

    #[test]
    fn test_argparse_example() {
        let cmd = parse_help(&read_fixture(&["argparse_example"]));
        assert_eq!(cmd.name.as_deref(), Some("prog.py"));
        assert!(
            cmd.description
                .as_deref()
                .unwrap_or("")
                .contains("argparse")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("bar".to_string()),
                        ..Default::default()
                    },
                    description_contains: "bar argument",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--foo".to_string()),
                        value_name: Some("FOO".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "foo value",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show this help message",
                },
            ],
        );
    }

    #[test]
    fn test_argparse_subparsers() {
        let cmd = parse_help(&read_fixture(&["argparse_subparsers"]));
        assert_eq!(cmd.name.as_deref(), Some("myapp"));
        assert!(cmd.description.as_deref().unwrap_or("").contains("My"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show this help message",
                },
            ],
        );
    }

    #[test]
    fn test_click_help() {
        let cmd = parse_help(&read_fixture(&["click"]));
        assert_eq!(cmd.name.as_deref(), Some("cli"));

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"hello"));
        assert!(subs.contains(&"goodbye"));
        assert_eq!(
            subcommand_by_name(&cmd, "hello").and_then(|s| s.description.as_deref()),
            Some("Greet someone.")
        );
        assert_eq!(
            subcommand_by_name(&cmd, "goodbye").and_then(|s| s.description.as_deref()),
            Some("Say goodbye.")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--name".to_string()),
                        value_name: Some("TEXT".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "The person to greet",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--count".to_string()),
                        value_name: Some("INTEGER".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Number of greetings",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show this message and exit",
                },
            ],
        );
    }

    #[test]
    fn test_argh_help() {
        let cmd = parse_help(&read_fixture(&["argh"]));
        assert_eq!(cmd.name.as_deref(), Some("myapp"));
        assert!(cmd.description.as_deref().unwrap_or("").contains("argh"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("name".to_string()),
                        ..Default::default()
                    },
                    description_contains: "the name argument",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "enable verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show this help message and exit",
                },
            ],
        );
    }

    #[test]
    fn test_yargs_help() {
        let cmd = parse_help(&read_fixture(&["yargs"]));
        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"serve"));
        assert!(subs.contains(&"build"));
        assert!(subs.contains(&"test"));

        assert!(
            subcommand_by_name(&cmd, "serve")
                .and_then(|s| s.description.as_deref())
                .unwrap_or("")
                .contains("development server")
        );
        assert!(
            subcommand_by_name(&cmd, "build")
                .and_then(|s| s.description.as_deref())
                .unwrap_or("")
                .contains("production")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show help",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show version number",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--port".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Port to listen on",
                },
            ],
        );
    }

    #[test]
    fn test_commander_help() {
        let cmd = parse_help(&read_fixture(&["commander"]));
        assert_eq!(cmd.name.as_deref(), Some("program"));

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"start"));
        assert!(subs.contains(&"stop"));
        assert!(subs.contains(&"status"));
        assert_eq!(
            subcommand_by_name(&cmd, "start").and_then(|s| s.description.as_deref()),
            Some("Start the server")
        );
        assert_eq!(
            subcommand_by_name(&cmd, "stop").and_then(|s| s.description.as_deref()),
            Some("Stop the server")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output the version number",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display help for command",
                },
            ],
        );
    }

    #[test]
    fn test_cobra_help() {
        let cmd = parse_help(&read_fixture(&["cobra"]));
        assert_eq!(cmd.name.as_deref(), Some("myapp"));
        assert!(
            cmd.description
                .as_deref()
                .unwrap_or("")
                .contains("application")
        );

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"serve"));
        assert!(subs.contains(&"version"));
        assert_eq!(
            subcommand_by_name(&cmd, "serve").and_then(|s| s.description.as_deref()),
            Some("Start the server")
        );
        assert!(
            subcommand_by_name(&cmd, "completion")
                .and_then(|s| s.description.as_deref())
                .unwrap_or("")
                .contains("autocompletion")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "help for myapp",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--toggle".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Help message for toggle",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--config".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "config file",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--log-level".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Log level",
                },
            ],
        );
    }

    #[test]
    fn test_docopt_help() {
        let cmd = parse_help(&read_fixture(&["docopt"]));
        assert_eq!(cmd.name.as_deref(), Some("naval_fate"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show this screen",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show version",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--speed".to_string()),
                        value_name: Some("kn".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Speed in knots",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--moored".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Moored",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--drifting".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Drifting mine",
                },
            ],
        );
    }

    #[test]
    fn test_git_help() {
        let cmd = parse_help(&read_fixture(&["git"]));
        assert_eq!(cmd.name.as_deref(), Some("git"));

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"clone"));
        assert!(subs.contains(&"commit"));
        assert!(subs.contains(&"log"));
        assert!(subs.contains(&"diff"));
        assert!(subs.contains(&"push"));
        assert!(subs.contains(&"pull"));
        assert!(subs.contains(&"branch"));
        assert!(subs.contains(&"status"));

        assert_eq!(
            subcommand_by_name(&cmd, "clone").and_then(|s| s.description.as_deref()),
            Some("Clone a repository into a new directory")
        );
        assert_eq!(
            subcommand_by_name(&cmd, "commit").and_then(|s| s.description.as_deref()),
            Some("Record changes to the repository")
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-C".to_string()),
                        value_name: Some("path".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::AnyPath,
                        ..Default::default()
                    },
                    description_contains: "started in",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        value_name: Some("name>=<value".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Pass a configuration parameter",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the Git suite version",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print help",
                },
            ],
        );
    }

    #[test]
    fn test_git_log_help() {
        let cmd = parse_help(&read_fixture(&["git", "log"]));
        assert_eq!(cmd.name.as_deref(), Some("git"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Suppress diff output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Be more verbose",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--max-count".to_string()),
                        value_name: Some("n".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Limit the number of commits",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--since".to_string()),
                        value_name: Some("date".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "recent than a specific date",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--author".to_string()),
                        value_name: Some("pattern".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "matching author",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--graph".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show the commit graph as ASCII art",
                },
            ],
        );
    }

    #[test]
    fn test_git_commit_help() {
        let cmd = parse_help(&read_fixture(&["git", "commit"]));
        assert_eq!(cmd.name.as_deref(), Some("git"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Suppress summary",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show diff in commit message",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--message".to_string()),
                        value_name: Some("message".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Commit message",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-F".to_string()),
                        long: Some("--file".to_string()),
                        value_name: Some("file".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Read message from file",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--amend".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Amend previous commit",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--squash".to_string()),
                        value_name: Some("commit".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::GitRevision,
                        ..Default::default()
                    },
                    description_contains: "squash specified commit",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--fixup".to_string()),
                        value_name: Some("commit".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::GitRevision,
                        ..Default::default()
                    },
                    description_contains: "fixup specified commit",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--env-var".to_string()),
                        value_name: Some("var".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::EnvVar,
                        ..Default::default()
                    },
                    description_contains: "Environment variable to use",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--iface".to_string()),
                        value_name: Some("interface".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::NetworkInterface,
                        ..Default::default()
                    },
                    description_contains: "Bind network interface",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--service".to_string()),
                        value_name: Some("unit".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::SystemdUnit,
                        ..Default::default()
                    },
                    description_contains: "Start systemd unit service",
                },
            ],
        );
    }

    #[test]
    fn test_git_diff_help() {
        let cmd = parse_help(&read_fixture(&["git", "diff"]));
        assert_eq!(cmd.name.as_deref(), Some("git"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--patch".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show patch",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--no-patch".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Suppress diff output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-U".to_string()),
                        long: Some("--unified".to_string()),
                        value_name: Some("n".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "lines of context",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-W".to_string()),
                        long: Some("--function-context".to_string()),
                        ..Default::default()
                    },
                    description_contains: "surrounding functions",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--cached".to_string()),
                        ..Default::default()
                    },
                    description_contains: "changes staged for",
                },
            ],
        );
    }

    #[test]
    fn test_subcommand_synthesis_overlay() {
        let help_runner = |args: &[&str]| -> anyhow::Result<String> {
            let text = match args {
                [] => read_fixture(&["git"]),
                ["log"] => read_fixture(&["git", "log"]),
                ["commit"] => read_fixture(&["git", "commit"]),
                ["diff"] => read_fixture(&["git", "diff"]),
                _ => "".to_string(),
            };
            Ok(text)
        };
        let top = synthesize_completion("git", help_runner, SynthesisStrategy::RunHelp, 5).unwrap();

        assert!(subcommand_names(&top).contains(&"log"));
        assert!(subcommand_names(&top).contains(&"commit"));

        let log_sub = subcommand_by_name(&top, "log").expect("log subcommand should exist");
        assert!(long_names(log_sub).contains(&"--oneline"));
        assert!(long_names(log_sub).contains(&"--graph"));
        assert!(long_names(log_sub).contains(&"--since"));

        let commit_sub =
            subcommand_by_name(&top, "commit").expect("commit subcommand should exist");
        assert!(long_names(commit_sub).contains(&"--amend"));
        assert!(long_names(commit_sub).contains(&"--message"));
        assert!(long_names(commit_sub).contains(&"--no-verify"));

        let diff_sub = subcommand_by_name(&top, "diff").expect("diff subcommand should exist");
        assert!(long_names(diff_sub).contains(&"--cached"));
        assert!(long_names(diff_sub).contains(&"--stat"));
    }

    #[test]
    fn test_nested_subcommand_synthesis_simulation() {
        let help_runner = |args: &[&str]| -> anyhow::Result<String> {
            let mut path_parts = vec!["git"];
            path_parts.extend(args);
            let path_str = path_parts.join("/");
            let file_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests")
                .join("help_texts")
                .join(format!("{}/help.txt", path_str));
            if file_path.exists() {
                Ok(std::fs::read_to_string(file_path)?)
            } else {
                Ok("".to_string())
            }
        };
        let top = synthesize_completion("git", help_runner, SynthesisStrategy::RunHelp, 5).unwrap();

        let remote =
            subcommand_by_name(&top, "remote").expect("remote subcommand should be present");
        assert!(long_names(remote).contains(&"--verbose"));

        let remote_add =
            subcommand_by_name(remote, "add").expect("remote add subcommand should be present");
        assert!(long_names(remote_add).contains(&"--fetch"));
        assert!(short_names(remote_add).contains(&"-f"));
        assert_eq!(
            arg_by_long(remote_add, "--track").and_then(|a| a.value_name.as_deref()),
            Some("branch")
        );
        assert_eq!(
            arg_by_long(remote_add, "--track").map(|a| a.value_hint),
            Some(ValueHint::GitBranch)
        );

        let remote_set_url = subcommand_by_name(remote, "set-url")
            .expect("remote set-url subcommand should be present");
        assert!(long_names(remote_set_url).contains(&"--push"));
        assert!(long_names(remote_set_url).contains(&"--delete"));
    }

    #[test]
    fn test_readelf_help() {
        let cmd = parse_test_help("readelf");
        assert_eq!(cmd.name.as_deref(), Some("readelf"));

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--all".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Equivalent to",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--file-header".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the ELF file header",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--program-headers".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the program headers",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--section-headers".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the sections' header",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--relocs".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the relocations",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--dynamic".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the dynamic section",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--notes".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the contents of note sections",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-W".to_string()),
                        long: Some("--wide".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Allow output width to exceed",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display this information",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display the version number",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--hex-dump".to_string()),
                        value_name: Some("number|name".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Dump the contents of section",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-w".to_string()),
                        long: Some("--debug-dump".to_string()),
                        value_name: Some("links".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "abbrev".to_string(),
                            "addr".to_string(),
                            "aranges".to_string(),
                            "cu_index".to_string(),
                            "decodedline".to_string(),
                            "frames".to_string(),
                            "frames-interp".to_string(),
                            "gdb_index".to_string(),
                            "info".to_string(),
                            "loc".to_string(),
                            "macro".to_string(),
                            "pubnames".to_string(),
                            "pubtypes".to_string(),
                            "Ranges".to_string(),
                            "rawline".to_string(),
                            "str".to_string(),
                            "str-offsets".to_string(),
                            "trace_abbrev".to_string(),
                            "trace_aranges".to_string(),
                            "trace_info".to_string(),
                            "links".to_string(),
                            "follow-links".to_string(),
                            "no-follow-links".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Display the contents of DWARF debug sections",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-U".to_string()),
                        long: Some("--unicode".to_string()),
                        value_name: Some(
                            "[default|locale|escape|hex|highlight|invalid]".to_string(),
                        ),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec![
                            "default".to_string(),
                            "locale".to_string(),
                            "escape".to_string(),
                            "hex".to_string(),
                            "highlight".to_string(),
                            "invalid".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Display unicode characters",
                },
            ],
        );
    }

    #[test]
    fn test_parse_flag_tokens_ignores_multi_character_short_forms() {
        let (short, longs, value_name, num_args) = parse_flag_tokens("-wk --debug-dump=links");
        assert_eq!(short, None);
        assert_eq!(longs, vec!["--debug-dump".to_string()]);
        assert_eq!(value_name.as_deref(), Some("links"));
        assert_eq!(num_args.as_deref(), Some("1"));

        let (short, longs, value_name, num_args) =
            parse_flag_tokens("-U[dlexhi] --unicode=[default|locale|escape|hex|highlight|invalid]");
        assert_eq!(short, Some("-U".to_string()));
        assert_eq!(longs, vec!["--unicode".to_string()]);
        assert_eq!(
            value_name.as_deref(),
            Some("[default|locale|escape|hex|highlight|invalid]")
        );
        assert_eq!(num_args.as_deref(), Some("?"));
    }
    #[test]
    fn test_zstd_help() {
        let cmd = parse_test_help("zstd");

        // Check overall commands info
        assert_eq!(
            cmd.description.as_deref(),
            Some(
                "Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided."
            )
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-o".to_string()),
                        value_name: Some("OUTPUT".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Write output to a single file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-k".to_string()),
                        long: Some("--keep".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Preserve INPUT file(s)",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--rm".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Remove INPUT file(s) after successful",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-#".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Desired compression level",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--decompress".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Perform decompression",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-D".to_string()),
                        value_name: Some("DICT".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Use DICT as the dictionary",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--force".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Disable input and output checks",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--stdout".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Write to STDOUT",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--trace".to_string()),
                        value_name: Some("LOG".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Log tracing information to LOG",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--filelist".to_string()),
                        value_name: Some("LIST".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Read a list of files",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--output-dir-flat".to_string()),
                        value_name: Some("DIR".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "Store processed files in DIR",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--check".to_string()),
                        value_name: None,
                        num_args: None,
                        value_enum: None,
                        ..Default::default()
                    },
                    description_contains: "Add XXH64 integrity checksums",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--fast".to_string()),
                        value_name: Some("#".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "very fast compression levels",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--long".to_string()),
                        value_name: Some("#".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable long distance matching",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-T#".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Spawn # compression threads",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--auto-threads".to_string()),
                        value_name: Some("{physical|logical}".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec!["physical".to_string(), "logical".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "Use physical/logical cores",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--format".to_string()),
                        value_name: Some("zstd".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "zstd".to_string(),
                            "gzip".to_string(),
                            "xz".to_string(),
                            "lzma".to_string(),
                            "lz4".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Compress files to the",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--mmap-dict".to_string()),
                        value_name: None,
                        num_args: None,
                        value_enum: None,
                        ..Default::default()
                    },
                    description_contains: "Memory-map dictionary file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print information about Zstandard-compressed",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--test".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Test compressed file integrity",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--train".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Create a dictionary from a training set",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--train-cover".to_string()),
                        value_name: Some("k=#,d=#,steps=#,split=#,shrink[=#]".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use the cover algorithm",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Output one benchmark result per input file",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--priority".to_string()),
                        value_name: Some("rt".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec!["rt".to_string()]),
                        ..Default::default()
                    },
                    description_contains: "Set process priority to real-time",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--progress".to_string()),
                        ..Default::default()
                    },
                    description_contains: "progress counter",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--no-progress".to_string()),
                        ..Default::default()
                    },
                    description_contains: "progress counter",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--asyncio".to_string()),
                        ..Default::default()
                    },
                    description_contains: "asynchronous IO",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--no-asyncio".to_string()),
                        ..Default::default()
                    },
                    description_contains: "asynchronous IO",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--check".to_string()),
                        ..Default::default()
                    },
                    description_contains: "XXH64 integrity checksums",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--no-check".to_string()),
                        ..Default::default()
                    },
                    description_contains: "XXH64 integrity checksums",
                },
            ],
        );
    }

    #[test]
    fn test_expand_no_options_in_help() {
        const HELP: &str = r#"Usage: mytool [OPTIONS]

Options:
  --[no-]color             Enable or disable color output.
  --[no]nocolor            Enable or disable nocolor option.
"#;
        let cmd = parse_help(HELP);
        let args = &cmd.args;

        // --[no-]color should expand to --color and --no-color
        assert!(args.iter().any(|a| a.long.as_deref() == Some("--color")));
        assert!(args.iter().any(|a| a.long.as_deref() == Some("--no-color")));

        // --[no]nocolor should expand to --nocolor and --nonocolor
        assert!(args.iter().any(|a| a.long.as_deref() == Some("--nocolor")));
        assert!(
            args.iter()
                .any(|a| a.long.as_deref() == Some("--nonocolor"))
        );
    }

    #[test]
    fn test_cargo_help_with_ellipsis() {
        const HELP: &str = r#"Rust's package manager

Usage: cargo [+toolchain] [OPTIONS] [COMMAND]

Options:
  -v, --verbose...               Use verbose output
  -h, --help                     Print help

Commands:
    build, b    Compile the current package
    check, c    Analyze the current package
    ...         See all commands with --list
"#;
        let cmd = parse_help(HELP);
        assert_eq!(cmd.name.as_deref(), Some("cargo"));

        // Check flags: --verbose... should become --verbose
        let verbose = cmd
            .args
            .iter()
            .find(|a| a.short.as_deref() == Some("-v"))
            .expect("verbose flag found");
        assert_eq!(verbose.long.as_deref(), Some("--verbose"));

        // Check subcommands: ... should be skipped
        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"build"));
        assert!(subs.contains(&"check"));
        assert!(!subs.contains(&"..."));
        assert_eq!(subs.len(), 2);
    }

    fn parse_test_help(name: &str) -> Command {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("help_texts")
            .join(format!("{}/help.txt", name));
        let content = std::fs::read_to_string(path).unwrap();
        parse_help(&content)
    }

    fn read_fixture(path: &[&str]) -> String {
        let path_str = path.join("/");
        let filepath = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("help_texts")
            .join(format!("{}/help.txt", path_str));
        std::fs::read_to_string(filepath).unwrap()
    }

    #[test]
    fn test_ip_help() {
        let cmd = parse_test_help("ip");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "address",
            "addrlabel",
            "amt",
            "fou",
            "help",
            "ila",
            "ioam",
            "l2tp",
            "link",
            "macsec",
            "maddress",
            "monitor",
            "mptcp",
            "mroute",
            "mrule",
            "neighbor",
            "neighbour",
            "netconf",
            "netns",
            "nexthop",
            "ntable",
            "ntbl",
            "route",
            "rule",
            "sr",
            "tap",
            "tcpmetrics",
            "token",
            "tunnel",
            "tuntap",
            "vrf",
            "xfrm",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        ..Default::default()
                    },
                    description_contains: "",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        ..Default::default()
                    },
                    description_contains: "",
                },
            ],
        );
    }

    #[test]
    fn test_docker_help() {
        let cmd = parse_test_help("docker");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "run", "exec", "ps", "build", "images", "pull", "push", "rm", "rmi", "logs",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--config".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Location of client config files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--context".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Name of the context to use",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-D".to_string()),
                        long: Some("--debug".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable debug mode",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--host".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Daemon socket to connect to",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--log-level".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Set the logging level",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--tls".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Use TLS",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--tlscacert".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Trust certs signed only by this CA",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--tlscert".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Path to TLS certificate file",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--tlskey".to_string()),
                        value_name: Some("string".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Path to TLS key file",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--tlsverify".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Use TLS and verify the remote",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print version information and quit",
                },
            ],
        );
    }

    #[test]
    fn test_npm_help() {
        let cmd = parse_test_help("npm");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "access",
            "adduser",
            "audit",
            "bugs",
            "cache",
            "ci",
            "completion",
            "config",
            "dedupe",
            "deprecate",
            "diff",
            "dist-tag",
            "docs",
            "doctor",
            "edit",
            "exec",
            "explain",
            "explore",
            "find-dupes",
            "fund",
            "get",
            "help",
            "hook",
            "init",
            "install",
            "install-ci-test",
            "install-test",
            "link",
            "ll",
            "login",
            "logout",
            "ls",
            "org",
            "outdated",
            "owner",
            "pack",
            "ping",
            "pkg",
            "prefix",
            "profile",
            "prune",
            "publish",
            "query",
            "rebuild",
            "repo",
            "restart",
            "root",
            "run-script",
            "search",
            "set",
            "shrinkwrap",
            "star",
            "stars",
            "start",
            "stop",
            "team",
            "test",
            "token",
            "uninstall",
            "unpublish",
            "unstar",
            "update",
            "version",
            "view",
            "whoami",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_expected_args(&cmd, &[]);
    }

    #[test]
    fn test_systemctl_help() {
        let cmd = parse_test_help("systemctl");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "list-units",
            "start",
            "stop",
            "status",
            "enable",
            "disable",
            "daemon-reload",
            "restart",
            "reload",
            "is-active",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--host".to_string()),
                        value_name: Some("[USER@]HOST".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Hostname,
                        ..Default::default()
                    },
                    description_contains: "Operate on remote host",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-M".to_string()),
                        long: Some("--machine".to_string()),
                        value_name: Some("CONTAINER".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Operate on a local container",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--property".to_string()),
                        value_name: Some("NAME".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show only properties by this name",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--all".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show all properties",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--full".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Don't ellipsize unit names on output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--recursive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show unit list of host and local containers",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--root".to_string()),
                        value_name: Some("PATH".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "specified root directory",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--lines".to_string()),
                        value_name: Some("INTEGER".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Number of journal entries to show",
                },
            ],
        );
    }

    #[test]
    fn test_apt_help() {
        let cmd = parse_test_help("apt");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "list",
            "search",
            "show",
            "install",
            "reinstall",
            "remove",
            "autoremove",
            "update",
            "upgrade",
            "full-upgrade",
            "edit-sources",
            "satisfy",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_expected_args(&cmd, &[]);
    }

    #[test]
    fn test_pip_help() {
        let cmd = parse_test_help("pip");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "install",
            "uninstall",
            "list",
            "show",
            "config",
            "download",
            "freeze",
            "check",
            "search",
            "cache",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Give more output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show version and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Give less output",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--log".to_string()),
                        value_name: Some("path".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::AnyPath,
                        ..Default::default()
                    },
                    description_contains: "Path to a verbose appending log",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--proxy".to_string()),
                        value_name: Some("proxy".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Specify a proxy",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--trusted-host".to_string()),
                        value_name: Some("hostname".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Hostname,
                        ..Default::default()
                    },
                    description_contains: "Mark this host or host:port pair as trusted",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--cert".to_string()),
                        value_name: Some("path".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::AnyPath,
                        ..Default::default()
                    },
                    description_contains: "Path to PEM-encoded CA certificate bundle",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--cache-dir".to_string()),
                        value_name: Some("dir".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "Store the cache data in",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--exists-action".to_string()),
                        value_name: Some("action".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "s".to_string(),
                            "i".to_string(),
                            "w".to_string(),
                            "b".to_string(),
                            "a".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Default action when a path already exists",
                },
            ],
        );
    }

    #[test]
    fn test_go_help() {
        let cmd = parse_test_help("go");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "build", "run", "test", "fmt", "get", "version", "clean", "doc", "env", "fix",
            "generate", "install", "list", "mod", "work", "tool", "vet",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_expected_args(&cmd, &[]);
    }

    #[test]
    fn test_gh_help() {
        let cmd = parse_test_help("gh");
        let subs = subcommand_names(&cmd);
        let expected_subs = vec![
            "auth",
            "pr",
            "repo",
            "issue",
            "run",
            "gist",
            "alias",
            "api",
            "completion",
            "config",
        ];
        for sub in expected_subs {
            assert!(subs.contains(&sub), "Missing subcommand: {}", sub);
        }

        assert_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show help for command",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show gh version",
                },
            ],
        );
    }

    #[test]
    fn test_curl_help() {
        let cmd = parse_test_help("curl");

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--data".to_string()),
                        value_name: Some("data".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "HTTP POST data",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--fail".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Fail fast with no output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-o".to_string()),
                        long: Some("--output".to_string()),
                        value_name: Some("file".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Write to file instead of stdout",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-u".to_string()),
                        long: Some("--user".to_string()),
                        value_name: Some("user:password".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Server user and password",
                },
            ],
        );
    }

    #[test]
    fn test_tar_help() {
        let cmd = parse_test_help("tar");

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--create".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Create a new archive",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--extract".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Extract files from an archive",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--list".to_string()),
                        ..Default::default()
                    },
                    description_contains: "List the contents of an archive",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--file".to_string()),
                        value_name: Some("ARCHIVE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "archive file or device ARCHIVE",
                },
            ],
        );
    }

    #[test]
    fn test_git_real_top_help() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("help_texts")
            .join("git_real/top.txt");
        let content = std::fs::read_to_string(path).unwrap();
        let cmd = parse_help(&content);
        assert_eq!(cmd.name.as_deref(), Some("git"));

        let subs = subcommand_names(&cmd);
        assert!(subs.contains(&"clone"), "Missing clone. Found: {:?}", subs);
        assert!(subs.contains(&"init"));
        assert!(subs.contains(&"add"));
        assert!(subs.contains(&"commit"));
        assert!(subs.contains(&"push"));

        assert_eq!(
            subcommand_by_name(&cmd, "clone").and_then(|s| s.description.as_deref()),
            Some("Clone a repository into a new directory")
        );
    }

    #[test]
    fn test_git_real_commit_help() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("help_texts")
            .join("git_real/commit.txt");
        let content = std::fs::read_to_string(path).unwrap();
        let cmd = parse_help(&content);

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "suppress summary",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-F".to_string()),
                        long: Some("--file".to_string()),
                        value_name: Some("file".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "read message from file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--message".to_string()),
                        value_name: Some("message".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "commit message",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-u".to_string()),
                        long: Some("--untracked-files".to_string()),
                        value_name: Some("mode".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show untracked files",
                },
            ],
        );

        // Verify that the [no-] expansion worked properly on real Git flags.
        // E.g., --[no-]quiet should expand to --quiet and --no-quiet.
        assert!(
            cmd.args
                .iter()
                .any(|a| a.long.as_deref() == Some("--quiet"))
        );
        assert!(
            cmd.args
                .iter()
                .any(|a| a.long.as_deref() == Some("--no-quiet"))
        );

        assert!(cmd.args.iter().any(|a| a.long.as_deref() == Some("--file")));
        assert!(
            cmd.args
                .iter()
                .any(|a| a.long.as_deref() == Some("--no-file"))
        );

        assert!(
            cmd.args
                .iter()
                .any(|a| a.long.as_deref() == Some("--verbose"))
        );
        assert!(
            cmd.args
                .iter()
                .any(|a| a.long.as_deref() == Some("--no-verbose"))
        );
    }

    #[test]
    fn test_grep_help() {
        let cmd = parse_test_help("grep");
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-A".to_string()),
                        long: Some("--after-context".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "print NUM lines of trailing context",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-B".to_string()),
                        long: Some("--before-context".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "print NUM lines of leading context",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-C".to_string()),
                        long: Some("--context".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "print NUM lines of output context",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--max-count".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "stop after NUM selected lines",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "suppress all normal output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--silent".to_string()),
                        ..Default::default()
                    },
                    description_contains: "suppress all normal output",
                },
            ],
        );
    }

    #[test]
    fn test_fd_help() {
        let cmd = parse_test_help("fd");
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--max-results".to_string()),
                        value_name: Some("count".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Limit the number of search results",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-j".to_string()),
                        long: Some("--threads".to_string()),
                        value_name: Some("num".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Set number of threads to use",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--search-path".to_string()),
                        value_name: Some("search-path".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::AnyPath,
                        ..Default::default()
                    },
                    description_contains: "Provide paths to search as an alternative",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--hidden".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Include hidden directories and files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-I".to_string()),
                        long: Some("--no-ignore".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show search results from files and directories that would otherwise be ignored",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-g".to_string()),
                        long: Some("--glob".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Perform a glob-based search instead of a regular expression search",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--regex".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Perform a regular-expression based search",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-F".to_string()),
                        long: Some("--fixed-strings".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Treat the pattern as a literal string",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--absolute-path".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Shows the full path starting from the root",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--follow".to_string()),
                        ..Default::default()
                    },
                    description_contains: "symbolic links are also traversed",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--full-path".to_string()),
                        ..Default::default()
                    },
                    description_contains: "pattern is matched against the full",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-0".to_string()),
                        long: Some("--print0".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Separate search results by the null character",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-E".to_string()),
                        long: Some("--exclude".to_string()),
                        value_name: Some("pattern".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Exclude files/directories that match the given glob pattern",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-e".to_string()),
                        long: Some("--extension".to_string()),
                        value_name: Some("ext".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "filter search results by their file extension",
                },
            ],
        );
    }

    #[test]
    fn test_rsync_help() {
        let cmd = parse_test_help("rsync");
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--port".to_string()),
                        value_name: Some("PORT".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "specify double-colon alternate port number",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--files-from".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "read list of source-file names from FILE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "increase verbosity",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "suppress non-error messages",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--checksum".to_string()),
                        ..Default::default()
                    },
                    description_contains: "skip based on checksum",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--archive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "archive mode is",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--recursive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "recurse into directories",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-R".to_string()),
                        long: Some("--relative".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use relative path names",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-b".to_string()),
                        long: Some("--backup".to_string()),
                        ..Default::default()
                    },
                    description_contains: "make backups",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--backup-dir".to_string()),
                        value_name: Some("DIR".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "make backups into hierarchy based in DIR",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--exclude".to_string()),
                        value_name: Some("PATTERN".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "exclude files matching PATTERN",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--exclude-from".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "read exclude patterns from FILE",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--include".to_string()),
                        value_name: Some("PATTERN".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "don't exclude files matching PATTERN",
                },
                ExpectedArg {
                    arg: Arg {
                        long: Some("--include-from".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "read include patterns from FILE",
                },
            ],
        );
    }

    #[test]
    fn test_ffmpeg_help() {
        let cmd = parse_test_help("ffmpeg");
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "show license",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--loglevel".to_string()),
                        value_name: Some("loglevel".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set logging level",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: None,
                        value_name: Some("loglevel".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set logging level",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-y".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "overwrite output files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "never overwrite output files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: None,
                        value_name: Some("fmt".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "force format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: None,
                        value_name: Some("codec".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "codec name",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--codec".to_string()),
                        value_name: Some("codec".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "codec name",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: None,
                        value_name: Some("duration".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "record or transcode",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--fs".to_string()),
                        value_name: Some("limit_size".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set the limit file size in bytes",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--filter_script".to_string()),
                        value_name: Some("filename".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "read stream filtergraph description from a file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--vn".to_string()),
                        ..Default::default()
                    },
                    description_contains: "disable video",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--an".to_string()),
                        ..Default::default()
                    },
                    description_contains: "disable audio",
                },
            ],
        );
    }

    #[test]
    fn test_df_help() {
        let cmd = parse_test_help("df");
        assert_eq!(cmd.name.as_deref(), Some("df"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--all".to_string()),
                        ..Default::default()
                    },
                    description_contains: "include pseudo, duplicate, inaccessible file systems",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-B".to_string()),
                        long: Some("--block-size".to_string()),
                        value_name: Some("SIZE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "scale sizes by SIZE before printing them",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--human-readable".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print sizes in powers of 1024",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--si".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print sizes in powers of 1000",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--inodes".to_string()),
                        ..Default::default()
                    },
                    description_contains: "list inode information instead of block usage",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-k".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "like --block-size=1K",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--local".to_string()),
                        ..Default::default()
                    },
                    description_contains: "limit listing to local file systems",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--no-sync".to_string()),
                        ..Default::default()
                    },
                    description_contains: "do not invoke sync before getting usage info",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--output".to_string()),
                        value_name: Some("FIELD_LIST".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use the output format defined by FIELD_LIST",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-P".to_string()),
                        long: Some("--portability".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use the POSIX output format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--sync".to_string()),
                        ..Default::default()
                    },
                    description_contains: "invoke sync before getting usage info",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--total".to_string()),
                        ..Default::default()
                    },
                    description_contains: "produce a grand total",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--type".to_string()),
                        value_name: Some("TYPE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "limit listing to file systems of type TYPE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-T".to_string()),
                        long: Some("--print-type".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print file system type",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--exclude-type".to_string()),
                        value_name: Some("TYPE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "limit listing to file systems not of type TYPE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "(ignored)",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_du_help() {
        let cmd = parse_test_help("du");
        assert_eq!(cmd.name.as_deref(), Some("du"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-0".to_string()),
                        long: Some("--null".to_string()),
                        ..Default::default()
                    },
                    description_contains: "end each output line with NUL",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--all".to_string()),
                        ..Default::default()
                    },
                    description_contains: "write counts for all files, not just directories",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--apparent-size".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print apparent sizes rather than device usage",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-B".to_string()),
                        long: Some("--block-size".to_string()),
                        value_name: Some("SIZE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "scale sizes by SIZE before printing them",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-b".to_string()),
                        long: Some("--bytes".to_string()),
                        ..Default::default()
                    },
                    description_contains: "equivalent to '--apparent-size --block-size=1'",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--total".to_string()),
                        ..Default::default()
                    },
                    description_contains: "produce a grand total",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-D".to_string()),
                        long: Some("--dereference-args".to_string()),
                        ..Default::default()
                    },
                    description_contains: "dereference only symlinks that are listed",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--max-depth".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "print the total for a directory",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--files0-from".to_string()),
                        value_name: Some("F".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "summarize device usage of the NUL-terminated file names",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "equivalent to --dereference-args",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--human-readable".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print sizes in human readable format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--inodes".to_string()),
                        ..Default::default()
                    },
                    description_contains: "list inode usage information",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-k".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "like --block-size=1K",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--dereference".to_string()),
                        ..Default::default()
                    },
                    description_contains: "dereference all symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--count-links".to_string()),
                        ..Default::default()
                    },
                    description_contains: "count sizes many times if hard linked",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "like --block-size=1M",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-P".to_string()),
                        long: Some("--no-dereference".to_string()),
                        ..Default::default()
                    },
                    description_contains: "don't follow any symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--separate-dirs".to_string()),
                        ..Default::default()
                    },
                    description_contains: "for directories do not include size of subdirectories",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--si".to_string()),
                        ..Default::default()
                    },
                    description_contains: "like -h, but use powers of 1000",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--summarize".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display only a total for each argument",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--threshold".to_string()),
                        value_name: Some("SIZE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "exclude entries smaller than SIZE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--time".to_string()),
                        value_name: Some("WORD".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show time of the last modification",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--time-style".to_string()),
                        value_name: Some("STYLE".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "full-iso".to_string(),
                            "long-iso".to_string(),
                            "iso".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "show times using STYLE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-X".to_string()),
                        long: Some("--exclude-from".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "exclude files that match any pattern in FILE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--exclude".to_string()),
                        value_name: Some("PATTERN".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "exclude files that match PATTERN",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--one-file-system".to_string()),
                        ..Default::default()
                    },
                    description_contains: "skip directories on different file systems",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_xargs_help() {
        let cmd = parse_test_help("xargs");
        assert_eq!(cmd.name.as_deref(), Some("xargs"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-0".to_string()),
                        long: Some("--null".to_string()),
                        ..Default::default()
                    },
                    description_contains: "items are separated by a null, not whitespace",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--arg-file".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "read arguments from FILE",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--delimiter".to_string()),
                        value_name: Some("CHARACTER".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "items in input stream are separated by CHARACTER",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-E".to_string()),
                        long: None,
                        value_name: Some("END".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set logical EOF string",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-e".to_string()),
                        long: Some("--eof".to_string()),
                        value_name: Some("END".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "equivalent to -E END",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-I".to_string()),
                        long: None,
                        value_name: Some("R".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "same as --replace=R",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--replace".to_string()),
                        value_name: Some("R".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "replace R in INITIAL-ARGS",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--max-lines".to_string()),
                        value_name: Some("MAX-LINES".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use at most MAX-LINES",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: None,
                        value_name: Some("MAX-LINES".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "similar to -L but defaults",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--max-args".to_string()),
                        value_name: Some("MAX-ARGS".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use at most MAX-ARGS",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-o".to_string()),
                        long: Some("--open-tty".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Reopen stdin as /dev/tty",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-P".to_string()),
                        long: Some("--max-procs".to_string()),
                        value_name: Some("MAX-PROCS".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "run at most MAX-PROCS",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--interactive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "prompt before running commands",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--process-slot-var".to_string()),
                        value_name: Some("VAR".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set environment variable VAR",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--no-run-if-empty".to_string()),
                        ..Default::default()
                    },
                    description_contains: "if there are no arguments, then do not run",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--max-chars".to_string()),
                        value_name: Some("MAX-CHARS".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "limit length of command line to MAX-CHARS",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--show-limits".to_string()),
                        ..Default::default()
                    },
                    description_contains: "show limits on command-line length",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print commands before executing them",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--exit".to_string()),
                        ..Default::default()
                    },
                    description_contains: "exit if the size",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_fzf_help() {
        let cmd = parse_test_help("fzf");
        assert_eq!(cmd.name.as_deref(), Some("fzf"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-e".to_string()),
                        long: Some("--exact".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable exact-match",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--ignore-case".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Case-insensitive match",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--smart-case".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Smart-case match",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--scheme".to_string()),
                        value_name: Some("SCHEME".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Scoring scheme",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--nth".to_string()),
                        value_name: Some("N[,..]".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Comma-separated list of field index expressions",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--with-nth".to_string()),
                        value_name: Some("N[,..]".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Transform the presentation of each line",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--delimiter".to_string()),
                        value_name: Some("STR".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Field delimiter regex",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--tail".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Maximum number of items to keep in memory",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--tiebreak".to_string()),
                        value_name: Some("CRI[,..]".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "length".to_string(),
                            "chunk".to_string(),
                            "pathname".to_string(),
                            "begin".to_string(),
                            "end".to_string(),
                            "index".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Comma-separated list of sort criteria",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--read0".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Read input delimited by ASCII NUL",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--tmux".to_string()),
                        value_name: Some("OPTS".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec![
                            "center".to_string(),
                            "top".to_string(),
                            "bottom".to_string(),
                            "left".to_string(),
                            "right".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Start fzf in a tmux popup",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--border".to_string()),
                        value_name: Some("STYLE".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec![
                            "rounded".to_string(),
                            "sharp".to_string(),
                            "bold".to_string(),
                            "block".to_string(),
                            "thinblock".to_string(),
                            "double".to_string(),
                            "horizontal".to_string(),
                            "vertical".to_string(),
                            "top".to_string(),
                            "bottom".to_string(),
                            "left".to_string(),
                            "right".to_string(),
                            "line".to_string(),
                            "none".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Draw border around the finder",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--border-label".to_string()),
                        value_name: Some("LABEL".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Label to print on the border",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--border-label-pos".to_string()),
                        value_name: Some("COL".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec!["0".to_string(), "center".to_string()]),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Position of the border label",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--multi".to_string()),
                        value_name: Some("MAX".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Enable multi-select",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--wrap-sign".to_string()),
                        value_name: Some("STR".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Indicator for wrapped lines",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--freeze-left".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Number of fields to freeze on the left",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--pointer".to_string()),
                        value_name: Some("STR".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Pointer to the current line",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--marker".to_string()),
                        value_name: Some("STR".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Multi-select marker",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--list-border".to_string()),
                        value_name: Some("STYLE".to_string()),
                        num_args: Some("?".to_string()),
                        value_enum: Some(vec![
                            "rounded".to_string(),
                            "sharp".to_string(),
                            "bold".to_string(),
                            "block".to_string(),
                            "thinblock".to_string(),
                            "double".to_string(),
                            "horizontal".to_string(),
                            "vertical".to_string(),
                            "top".to_string(),
                            "bottom".to_string(),
                            "left".to_string(),
                            "right".to_string(),
                            "none".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Draw border around the list section",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--list-label-pos".to_string()),
                        value_name: Some("COL".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec!["0".to_string(), "center".to_string()]),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Position of the list label",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--info-command".to_string()),
                        value_name: Some("COMMAND".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandName,
                        ..Default::default()
                    },
                    description_contains: "Command to generate info line",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--preview".to_string()),
                        value_name: Some("COMMAND".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandName,
                        ..Default::default()
                    },
                    description_contains: "Command to preview highlighted line",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--preview-window".to_string()),
                        value_name: Some("OPT".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "up".to_string(),
                            "down".to_string(),
                            "left".to_string(),
                            "right".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "Preview window layout",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--walker".to_string()),
                        value_name: Some("OPTS".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "file".to_string(),
                            "follow".to_string(),
                            "hidden".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "default: file,follow,hidden",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--walker-root".to_string()),
                        value_name: Some("DIR".to_string()),
                        num_args: Some("?".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "List of directories to walk",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--history".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "File to store fzf search history",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--history-size".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Maximum number of entries to keep",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Display version information and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show this message",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--man".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show man page",
                },
            ],
        );
    }

    #[test]
    fn test_wc_help() {
        let cmd = parse_test_help("wc");
        assert_eq!(cmd.name.as_deref(), Some("wc"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--bytes".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the byte counts",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--chars".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the character counts",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--lines".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the newline counts",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--files0-from".to_string()),
                        value_name: Some("F".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "read input from the files specified by NUL-terminated names",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--max-line-length".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the maximum display width",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-w".to_string()),
                        long: Some("--words".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the word counts",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--total".to_string()),
                        value_name: Some("WHEN".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec![
                            "auto".to_string(),
                            "always".to_string(),
                            "only".to_string(),
                            "never".to_string(),
                        ]),
                        ..Default::default()
                    },
                    description_contains: "when to print a line with total counts",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_ln_help() {
        let cmd = parse_test_help("ln");
        assert_eq!(cmd.name.as_deref(), Some("ln"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--backup".to_string()),
                        value_name: Some("CONTROL".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "make a backup of each existing destination file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-b".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "like --backup but does not accept an argument",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-F".to_string()),
                        long: Some("--directory".to_string()),
                        ..Default::default()
                    },
                    description_contains: "allow the superuser to attempt to hard link directories",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--force".to_string()),
                        ..Default::default()
                    },
                    description_contains: "remove existing destination files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--interactive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "prompt whether to remove destinations",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--logical".to_string()),
                        ..Default::default()
                    },
                    description_contains: "dereference TARGETs that are symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--no-dereference".to_string()),
                        ..Default::default()
                    },
                    description_contains: "treat LINK_NAME as a normal file if it is a symbolic link",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-P".to_string()),
                        long: Some("--physical".to_string()),
                        ..Default::default()
                    },
                    description_contains: "make hard links directly to symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--relative".to_string()),
                        ..Default::default()
                    },
                    description_contains: "create links relative to link location",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--symbolic".to_string()),
                        ..Default::default()
                    },
                    description_contains: "make symbolic links instead of hard links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--suffix".to_string()),
                        value_name: Some("SUFFIX".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "override the usual backup suffix",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--target-directory".to_string()),
                        value_name: Some("DIRECTORY".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "specify the DIRECTORY in which to create the links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-T".to_string()),
                        long: Some("--no-target-directory".to_string()),
                        ..Default::default()
                    },
                    description_contains: "treat LINK_NAME as a normal file always",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print name of each linked file",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_env_help() {
        let cmd = parse_test_help("env");
        assert_eq!(cmd.name.as_deref(), Some("env"));
        assert_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--ignore-environment".to_string()),
                        ..Default::default()
                    },
                    description_contains: "start with an empty environment",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-0".to_string()),
                        long: Some("--null".to_string()),
                        ..Default::default()
                    },
                    description_contains: "end each output line with NUL",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-u".to_string()),
                        long: Some("--unset".to_string()),
                        value_name: Some("NAME".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::EnvVar,
                        ..Default::default()
                    },
                    description_contains: "remove variable from the environment",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-C".to_string()),
                        long: Some("--chdir".to_string()),
                        value_name: Some("DIR".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::DirPath,
                        ..Default::default()
                    },
                    description_contains: "change working directory to DIR",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--split-string".to_string()),
                        value_name: Some("S".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "process and split S into separate arguments",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--block-signal".to_string()),
                        value_name: Some("SIG".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "block delivery of SIG",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--default-signal".to_string()),
                        value_name: Some("SIG".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "reset handling of SIG",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--ignore-signal".to_string()),
                        value_name: Some("SIG".to_string()),
                        num_args: Some("?".to_string()),
                        ..Default::default()
                    },
                    description_contains: "set handling of SIG",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--list-signal-handling".to_string()),
                        ..Default::default()
                    },
                    description_contains: "list non default signal handling",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--debug".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print verbose information",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_h5dump_help() {
        let cmd = parse_test_help("h5dump");
        assert_eq!(cmd.name.as_deref(), Some("h5dump"));
        assert_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print a usage message and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print version number and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--enable-error-stack".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Prints messages from the HDF5 error stack",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--contents".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print a list of the file contents and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-B".to_string()),
                        long: Some("--superblock".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the content of the super block",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-H".to_string()),
                        long: Some("--header".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the header only; no data is displayed",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--filedriver".to_string()),
                        value_name: Some("D".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Specify which driver to open the file with",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-o".to_string()),
                        long: Some("--output".to_string()),
                        value_name: Some("F".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Output raw data into file F",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-b".to_string()),
                        long: Some("--binary".to_string()),
                        value_name: Some("B".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Binary file output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-O".to_string()),
                        long: Some("--ddl".to_string()),
                        value_name: Some("F".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Output ddl text into file F",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--s3-cred".to_string()),
                        value_name: Some("cred".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Supply S3 authentication information",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--hdfs-attrs".to_string()),
                        value_name: Some("attrs".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Supply configuration information for HDFS file access",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--attribute".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the specified attribute",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--dataset".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the specified dataset",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-g".to_string()),
                        long: Some("--group".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the specified group and all members",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--soft-link".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the value(s) of the specified soft link",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: Some("--datatype".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the specified named datatype",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-N".to_string()),
                        long: Some("--any_path".to_string()),
                        value_name: Some("P".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print any attribute, dataset, group",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-A".to_string()),
                        long: Some("--onlyattr".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the header and value of attributes",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--vds-view-first-missing".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Set the VDS bounds to first missing mapped elements",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--vds-gap-size".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Set the missing file gap size",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--object-ids".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the object ids",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--properties".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print dataset filters, storage layout and fill value",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-M".to_string()),
                        long: Some("--packedbits".to_string()),
                        value_name: Some("L".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Print packed bits as unsigned integers",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-R".to_string()),
                        long: Some("--region".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print dataset pointed by region references",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-e".to_string()),
                        long: Some("--escape".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Escape non printing characters",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--string".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print 1-byte integer datasets as ASCII",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-y".to_string()),
                        long: Some("--noindex".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Do not print array indices with the data",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--format".to_string()),
                        value_name: Some("T".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Set the floating point output format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--sort_by".to_string()),
                        value_name: Some("Q".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Sort groups and attributes by index Q",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-z".to_string()),
                        long: Some("--sort_order".to_string()),
                        value_name: Some("Z".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Sort groups and attributes by order Z",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--no-compact-subset".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Disable compact form of subsetting",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-w".to_string()),
                        long: Some("--width".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Set the number of columns of output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--xml".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Output in XML using Schema",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-u".to_string()),
                        long: Some("--use-dtd".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Output in XML using DTD",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-D".to_string()),
                        long: Some("--xml-dtd".to_string()),
                        value_name: Some("U".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use the DTD or schema at U",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-X".to_string()),
                        long: Some("--xml-ns".to_string()),
                        value_name: Some("S".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use qualified names n the XML",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--start".to_string()),
                        value_name: Some("START".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Offset of start of subsetting selection",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--stride".to_string()),
                        value_name: Some("STRIDE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Hyperslab stride",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--count".to_string()),
                        value_name: Some("COUNT".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Number of blocks to include in selection",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-k".to_string()),
                        long: Some("--block".to_string()),
                        value_name: Some("BLOCK".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Size of block in hyperslab",
                },
            ],
        );
    }

    #[test]
    fn test_h5ls_help() {
        let cmd = parse_test_help("h5ls");
        assert_eq!(cmd.name.as_deref(), Some("h5ls"));
        assert_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print a usage message and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--address".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print raw data address",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--data".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the values of datasets",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--enable-error-stack".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Prints messages from the HDF5 error stack",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--follow-symlinks".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Follow symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--no-dangling-links".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Check for any symbolic links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: Some("--full".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print full path names",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-g".to_string()),
                        long: Some("--group".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show information about a group",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-l".to_string()),
                        long: Some("--label".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Label members of compound datasets",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--recursive".to_string()),
                        ..Default::default()
                    },
                    description_contains: "List all groups recursively",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--string".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print 1-byte integer datasets",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--simple".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use a machine-readable output format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-w".to_string()),
                        long: Some("--width".to_string()),
                        value_name: Some("N".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "Set the number of columns of output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Generate more verbose output",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print version number and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--vfd".to_string()),
                        value_name: Some("DRIVER".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Use the specified virtual file driver",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-x".to_string()),
                        long: Some("--hexdump".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show raw data in hexadecimal format",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-E".to_string()),
                        long: Some("--external".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Follow external links",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-e".to_string()),
                        long: Some("--errors".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Show all HDF5 error reporting",
                },
            ],
        );
    }

    #[test]
    fn test_uname_help() {
        let cmd = parse_test_help("uname");
        assert_eq!(cmd.name.as_deref(), Some("uname"));
        assert_eq!(
            cmd.description.as_deref(),
            Some("Print certain system information.  With no OPTION, same as -s.")
        );
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: Some("--all".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print all information",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--kernel-name".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the kernel name",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--nodename".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the network node hostname",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--kernel-release".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the kernel release",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--kernel-version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the kernel version",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--machine".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the machine hardware name",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--processor".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the processor type",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--hardware-platform".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the hardware platform",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-o".to_string()),
                        long: Some("--operating-system".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the operating system",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_touch_help() {
        let cmd = parse_test_help("touch");
        assert_eq!(cmd.name.as_deref(), Some("touch"));
        assert_eq!(
            cmd.description.as_deref(),
            Some("Update the access and modification times of each FILE to the current time.")
        );
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-a".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "change only the access time",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--no-create".to_string()),
                        ..Default::default()
                    },
                    description_contains: "do not create any files",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-d".to_string()),
                        long: Some("--date".to_string()),
                        value_name: Some("STRING".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "parse STRING and use it instead",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-f".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "(ignored)",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--no-dereference".to_string()),
                        ..Default::default()
                    },
                    description_contains: "affect each symbolic link",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "change only the modification time",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--reference".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "use this file's times instead",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-t".to_string()),
                        long: None,
                        value_name: Some("STAMP".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "use [[CC]YY]MMDDhhmm",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--time".to_string()),
                        value_name: Some("WORD".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "change the specified time",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_head_help() {
        let cmd = parse_test_help("head");
        assert_eq!(cmd.name.as_deref(), Some("head"));
        assert_eq!(
            cmd.description.as_deref(),
            Some("Print the first 10 lines of each FILE to standard output.")
        );
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--bytes".to_string()),
                        value_name: Some("[-]NUM".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the first NUM bytes",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--lines".to_string()),
                        value_name: Some("[-]NUM".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "print the first NUM lines",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-q".to_string()),
                        long: Some("--quiet".to_string()),
                        ..Default::default()
                    },
                    description_contains: "never print headers",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--silent".to_string()),
                        ..Default::default()
                    },
                    description_contains: "never print headers",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-v".to_string()),
                        long: Some("--verbose".to_string()),
                        ..Default::default()
                    },
                    description_contains: "always print headers",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-z".to_string()),
                        long: Some("--zero-terminated".to_string()),
                        ..Default::default()
                    },
                    description_contains: "line delimiter is NUL",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "display this help and exit",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "output version information and exit",
                },
            ],
        );
    }

    #[test]
    fn test_hyperfine_norc_description_is_not_parsed_as_flag() {
        let help_text = r#"
USAGE:
    hyperfine [OPTIONS] <command>...

OPTIONS:
    -S, --shell <SHELL>
            Set the shell to use. This can be a full command line
            like "bash --norc". It can also be set to "default".
"#;
        let cmd = parse_help(help_text);
        assert_eq!(cmd.args.len(), 1);
        let arg = &cmd.args[0];
        assert_eq!(arg.long.as_deref(), Some("--shell"));
        assert_eq!(arg.short.as_deref(), Some("-S"));
        assert!(arg.description.as_deref().unwrap().contains("--norc"));
    }

    #[test]
    fn test_hyperfine_help() {
        let cmd = parse_test_help("hyperfine");
        assert_eq!(cmd.name.as_deref(), Some("hyperfine"));
        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        short: Some("-w".to_string()),
                        long: Some("--warmup".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "warmup runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-m".to_string()),
                        long: Some("--min-runs".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "at least NUM runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-M".to_string()),
                        long: Some("--max-runs".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "at most NUM runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-r".to_string()),
                        long: Some("--runs".to_string()),
                        value_name: Some("NUM".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::Integral,
                        ..Default::default()
                    },
                    description_contains: "exactly NUM runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-s".to_string()),
                        long: Some("--setup".to_string()),
                        value_name: Some("CMD".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandName,
                        ..Default::default()
                    },
                    description_contains: "Execute CMD before each set of timing runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-p".to_string()),
                        long: Some("--prepare".to_string()),
                        value_name: Some("CMD".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandName,
                        ..Default::default()
                    },
                    description_contains: "Execute CMD before each timing run",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--cleanup".to_string()),
                        value_name: Some("CMD".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandName,
                        ..Default::default()
                    },
                    description_contains: "Execute CMD after the completion",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-P".to_string()),
                        long: Some("--parameter-scan".to_string()),
                        value_name: Some("VAR".to_string()),
                        num_args: Some("3".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Perform benchmark runs",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-D".to_string()),
                        long: Some("--parameter-step-size".to_string()),
                        value_name: Some("DELTA".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "requires --parameter-scan",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-L".to_string()),
                        long: Some("--parameter-list".to_string()),
                        value_name: Some("VAR".to_string()),
                        num_args: Some("2".to_string()),
                        ..Default::default()
                    },
                    description_contains: "comma-separated list",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--style".to_string()),
                        value_name: Some("TYPE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Set output style type",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-S".to_string()),
                        long: Some("--shell".to_string()),
                        value_name: Some("SHELL".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::CommandString,
                        ..Default::default()
                    },
                    description_contains: "Set the shell to use",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-N".to_string()),
                        long: None,
                        ..Default::default()
                    },
                    description_contains: "alias for '--shell=none'",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-i".to_string()),
                        long: Some("--ignore-failure".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Ignore non-zero exit codes",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-u".to_string()),
                        long: Some("--time-unit".to_string()),
                        value_name: Some("UNIT".to_string()),
                        num_args: Some("1".to_string()),
                        value_enum: Some(vec!["millisecond".to_string(), "second".to_string()]),
                        value_hint: ValueHint::Unknown,
                        ..Default::default()
                    },
                    description_contains: "Set the time unit to be used",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--export-asciidoc".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Export the timing summary statistics as an AsciiDoc table",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--export-csv".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Export the timing summary statistics as CSV",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--export-json".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Export the timing summary statistics and timings of individual runs as JSON",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--export-markdown".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Export the timing summary statistics as a Markdown table",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--export-orgmode".to_string()),
                        value_name: Some("FILE".to_string()),
                        num_args: Some("1".to_string()),
                        value_hint: ValueHint::FilePath,
                        ..Default::default()
                    },
                    description_contains: "Export the timing summary statistics as a Emacs org-mode table",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--show-output".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print the stdout and stderr",
                },
                ExpectedArg {
                    arg: Arg {
                        short: None,
                        long: Some("--output".to_string()),
                        value_name: Some("WHERE".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Control where the output of the benchmark is redirected",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-n".to_string()),
                        long: Some("--command-name".to_string()),
                        value_name: Some("NAME".to_string()),
                        num_args: Some("1".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Give a meaningful name to a command",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-h".to_string()),
                        long: Some("--help".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Print help",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-V".to_string()),
                        long: Some("--version".to_string()),
                        ..Default::default()
                    },
                    description_contains: "version information",
                },
            ],
        );
    }

    #[test]
    fn test_agy_help() {
        let cmd = parse_help(&read_fixture(&["agy"]));
        assert_eq!(cmd.name.as_deref(), Some("agy"));

        assert_contains_subcommands(
            &cmd,
            &[
                ("changelog", "Show changelog and release notes"),
                ("help", "Show help for subcommands"),
                ("install", "Configure environment paths and shell settings"),
                ("models", "List available models"),
                (
                    "plugin",
                    "Manage plugins (install, uninstall, list, enable, disable)",
                ),
                ("plugins", "Alias for plugin"),
                ("update", "Update CLI"),
            ],
        );

        assert_contains_expected_args(
            &cmd,
            &[
                ExpectedArg {
                    arg: Arg {
                        long: Some("--add-dir".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Add a directory to the workspace",
                },
                ExpectedArg {
                    arg: Arg {
                        short: Some("-c".to_string()),
                        long: Some("--continue".to_string()),
                        ..Default::default()
                    },
                    description_contains: "Continue the most recent conversation",
                },
            ],
        );
    }
}
