#!/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
current_section="None"
word_count=0
file=$1

# Read the Markdown file line by line
while IFS= read -r line; do
    # Check for section heading
    if [[ $line == \#* ]]; then
        # Print the word count of the previous section
        if [ "$current_section" != "None" ]; then
            echo "$current_section: $word_count"
        fi
        # Reset word count and set new section
        word_count=0
        current_section=$(echo $line | sed 's/#* //')
    else
        # Ignore references and count words in other lines
        if [[ ! $line =~ ^\[.*\]: ]]; then
            line_word_count=$(count_words "$line")
            word_count=$((word_count + line_word_count))
        fi
    fi
done < "$file"

# Print the word count of the last section
echo "$current_section: $word_count"