#!/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() {
    cleaned_line=$(echo "$1" | sed -E 's/\[@[^]]*\]//g; s/\\[a-zA-Z]+//g; s/\!\[.*\]\(.*\)//g')
    echo "$cleaned_line" | wc -w
}

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

print_section_info() {
    echo "$1 total: $2 words"
}

# 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 markdown table lines
    if [[ "$line" =~ ^\|.*\|$ ]] || [[ "$line" =~ ^\|- ]]; then
        continue
    fi

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

    if [[ "$line" =~ ^\#[^#]* ]]; then
        if [ "$section_word_count" -ne 0 ]; then
            print_section_info "$current_section" $section_word_count
        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
    print_section_info "$current_section" $section_word_count
fi

exit 0