#!/bin/bash
# Generate docs/reference/cli.md from `irradiate --help` output.
# The clap #[arg] doc comments in src/main.rs are the source of truth.
#
# Usage: bash scripts/gen-cli-docs.sh [path/to/binary]
set -euo pipefail

BINARY="${1:-target/debug/irradiate}"

if [ ! -x "$BINARY" ]; then
    echo "Binary not found at $BINARY — run 'cargo build' first" >&2
    exit 1
fi

OUT="docs/reference/cli.md"

# Parse clap help into markdown table rows.
# Handles both single-line and multi-line clap formats:
#   Single: "  --flag <V>  Description [default: X]"
#   Multi:  "  --flag <V>\n          Description [default: X]"
help_to_table() {
    local help_text="$1"
    local current_flag=""
    local current_desc=""

    flush_row() {
        if [ -n "$current_flag" ]; then
            local default="--"
            if [[ "$current_desc" =~ \[default:\ ([^\]]+)\] ]]; then
                default="\`${BASH_REMATCH[1]}\`"
                current_desc=$(echo "$current_desc" | sed -E 's/ *\[default: [^]]+\]//')
            fi
            current_desc=$(echo "$current_desc" | sed 's/^ *//;s/ *$//')
            echo "| \`$current_flag\` | $default | $current_desc |"
        fi
    }

    while IFS= read -r line; do
        # Flag line: starts with spaces then - or --
        if [[ "$line" =~ ^[[:space:]]+(-[a-zA-Z,]|--[a-z]) ]]; then
            flush_row
            # Check if description is on the same line (single-line format).
            # Clap uses 2+ spaces to separate flag from description.
            local stripped=$(echo "$line" | sed 's/^ *//')
            # Use perl-style split: everything up to and including ">" or last flag char,
            # then 2+ spaces, then description.
            local flag_part desc_part
            flag_part=$(echo "$stripped" | perl -pe 's/^(.*?>|.*?[a-z-])  +.*/$1/' 2>/dev/null || echo "$stripped")
            desc_part=$(echo "$stripped" | perl -pe 's/^(?:.*?>|.*?[a-z-])  +//' 2>/dev/null || echo "")
            if [ "$flag_part" != "$stripped" ] && [ -n "$desc_part" ]; then
                current_flag="$flag_part"
                current_desc="$desc_part"
            else
                current_flag="$stripped"
                current_desc=""
            fi
        # Description continuation: deeply indented text (8+ spaces)
        elif [[ "$line" =~ ^[[:space:]]{8} ]] && [ -n "$current_flag" ]; then
            local text=$(echo "$line" | sed 's/^ *//')
            if [ -n "$current_desc" ]; then
                current_desc="$current_desc $text"
            else
                current_desc="$text"
            fi
        fi
    done <<< "$help_text"
    flush_row
}

# --- Generate ---

VERSION=$("$BINARY" --version 2>&1)
RUN_HELP=$("$BINARY" run --help 2>&1)
RESULTS_HELP=$("$BINARY" results --help 2>&1)
SHOW_HELP=$("$BINARY" show --help 2>&1)
GC_HELP=$("$BINARY" cache gc --help 2>&1)

cat > "$OUT" << HEADER
---
title: CLI Reference — irradiate
description: Complete command-line reference for irradiate. All commands, flags, and options for run, results, show, and cache.
---

<!-- Auto-generated by scripts/gen-cli-docs.sh from clap definitions in src/main.rs -->
<!-- Do not edit manually — run: bash scripts/gen-cli-docs.sh -->

# CLI Reference

## Global

\`\`\`
irradiate [OPTIONS] <COMMAND>
\`\`\`

| Flag        | Description   |
| ----------- | ------------- |
| \`--version\` | Print version ($VERSION) |
| \`--help\`    | Print help    |

## \`irradiate run\`

$(echo "$RUN_HELP" | head -1)

\`\`\`bash
irradiate run [OPTIONS] [PATHS]...
\`\`\`

### Options

| Flag | Default | Description |
| ---- | ------- | ----------- |
$(help_to_table "$RUN_HELP")

### Examples

\`\`\`bash
irradiate run                                    # basic run (auto-detects src/)
irradiate run src/mylib                          # mutate a specific path
irradiate run --diff main                        # incremental: changed functions only
irradiate run --fail-under 80                    # CI gate
irradiate run --report html -o report.html       # HTML report
irradiate run --isolate                          # full subprocess isolation
irradiate run --verify-survivors                 # re-check survivors after warm run
irradiate run --python .venv/bin/python          # specific interpreter
irradiate run --mutant mylib.x_add__irradiate_3  # test one specific mutant
irradiate run --workers 4 --covered-only         # tuning
irradiate run --sample 0.1                       # test 10% of mutants (fast CI)
irradiate run --sample 50 --sample-seed 42       # test exactly 50, reproducible
irradiate run --no-cache                         # ignore cache, re-test everything
irradiate run --ignore "src/vendor/*"            # exclude files from mutation
irradiate run --type-checker mypy                # filter mutants caught by type checker
irradiate run --pytest-args "--ignore=tests/e2e" # skip a test directory
\`\`\`

## \`irradiate results\`

$(echo "$RESULTS_HELP" | head -1)

\`\`\`bash
irradiate results [OPTIONS]
\`\`\`

| Flag | Default | Description |
| ---- | ------- | ----------- |
$(help_to_table "$RESULTS_HELP")

## \`irradiate show\`

$(echo "$SHOW_HELP" | head -1)

\`\`\`bash
irradiate show <MUTANT_NAME>
\`\`\`

| Argument        | Description                      |
| --------------- | -------------------------------- |
| \`<MUTANT_NAME>\` | e.g. \`mylib.x_func__irradiate_1\` |

## \`irradiate cache clean\`

Remove the local result cache.

\`\`\`bash
irradiate cache clean
\`\`\`

## \`irradiate cache gc\`

$(echo "$GC_HELP" | head -1)

\`\`\`bash
irradiate cache gc [OPTIONS]
\`\`\`

| Flag | Default | Description |
| ---- | ------- | ----------- |
$(help_to_table "$GC_HELP")

Defaults can be set in pyproject.toml via \`cache_max_age\` and \`cache_max_size\`. See [Remote Cache](../guide/remote-cache.md).

## Configuration

\`run\` options can also be set in \`pyproject.toml\` under \`[tool.irradiate]\`. CLI flags override config. See [Configuration](../getting-started/configuration.md).

## Mutant name format

| Python source              | Mutant name                    |
| -------------------------- | ------------------------------ |
| \`def add()\` in \`mylib\`     | \`mylib.x_add__irradiate_1\`     |
| \`class Foo\` method \`bar()\` | \`mylib.xǁFooǁbar__irradiate_1\` |

The \`x_\` prefix avoids collisions. The \`ǁ\` (U+01C1) separator encodes class membership.
HEADER

echo "Generated $OUT from $VERSION"
