#!/usr/bin/env bash
# Generate documentation for all scripts
# Extracts usage information from script headers

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

source "$SCRIPT_DIR/../lib/init.sh"

cd "$PROJECT_ROOT"

DOCS_DIR="$PROJECT_ROOT/docs/scripts"
mkdir -p "$DOCS_DIR"

log_section "Generating Script Documentation"

# Create index file
INDEX_FILE="$DOCS_DIR/INDEX.md"
cat > "$INDEX_FILE" <<'EOF'
# Script Documentation Index

This directory contains auto-generated documentation for all scripts in the project.

## Scripts by Category

EOF

# Process each script
process_script() {
    local script="$1"
    local rel_path="${script#$PROJECT_ROOT/}"
    local script_name=$(basename "$script")
    local script_dir=$(dirname "$rel_path")
    
    # Create directory structure in docs
    local doc_dir="$DOCS_DIR/$script_dir"
    mkdir -p "$doc_dir"
    
    local doc_file="$doc_dir/${script_name}.md"
    
    # Extract header information
    local description=""
    local usage=""
    local options=""
    local examples=""
    
    # Read script and extract header
    local in_header=false
    local header_lines=()
    
    while IFS= read -r line; do
        if [[ "$line" =~ ^#.*Script\ Name: ]]; then
            in_header=true
        fi
        
        if [ "$in_header" = true ]; then
            header_lines+=("$line")
            
            if [[ "$line" =~ ^[^#] ]] && [ -n "$line" ]; then
                break
            fi
        fi
    done < "$script"
    
    # Generate documentation
    cat > "$doc_file" <<EOF
# $script_name

**Path**: \`$rel_path\`

$(printf '%s\n' "${header_lines[@]}" | sed 's/^# //' | sed 's/^#//')

## Source Code

\`\`\`bash
$(head -50 "$script")
\`\`\`

EOF
    
    echo "- [$script_name]($script_dir/${script_name}.md)" >> "$INDEX_FILE"
}

# Find and process all scripts
log_info "Processing scripts..."

count=0
while IFS= read -r -d '' script; do
    process_script "$script"
    ((count++)) || true
done < <(find scripts -name "*.sh" -type f -print0)

log_success "Generated documentation for $count scripts"
log_info "Documentation available in: $DOCS_DIR"
