#!/bin/bash

# Check if a file is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <markdown-file>"
    exit 1
fi

# Function to count words in a line
count_words() {
    echo "$1" | wc -w
}

# Variables
section_word_count=0
in_code_block=false
file="$1"

# Read the Markdown file line by line
while IFS= read -r line; do
    if [[ "$line" == \`\`\`* ]]; then
        in_code_block=!$in_code_block
        continue
    fi

    $in_code_block && continue

    # Ignore empty lines
    if [[ -z "$line" ]]; then
        continue
    fi

    # Process level 1 headings
    if [[ "$line" =~ ^\#\  ]]; then
        if [ "$section_word_count" -ne 0 ]; then
            echo "$current_section total: $section_word_count words"
        fi
        current_section=$(echo "$line" | sed 's/^# //')
        section_word_count=0
    else
        line_word_count=$(count_words "$line")
        section_word_count=$((section_word_count + line_word_count))
    fi
done < "$file"

# Print the last section's word count
if [ "$section_word_count" -ne 0 ]; then
    echo "$current_section total: $section_word_count words"
fi

exit 0