#!/bin/bash
# Fichier README.md
README="FILES.md"

# Temporary file for new list
TEMP_FILE=$(mktemp)

# Get all .md files in the repository except the README.md
find . -type f -name "*.md" ! -name "$README" | sort > "$TEMP_FILE"

# Function to get the title from a Markdown file
get_title() {
    local file="$1"
    grep -m 1 '^# ' "$file" | sed 's/^# //'
}

# Start with a clean README.md
echo "# Liste des fichiers Markdown" > "$README"

# Initialize variable to track the last directory
last_directory=""

# Read the list of files and append to README.md
while read -r file; do
    title=$(get_title "$file")
    # Convert file path to hierarchical levels
    IFS='/' read -r -a path_parts <<< "$file"
    indent=""
    for ((i=1; i<${#path_parts[@]}-1; i++)); do
        indent="$indent  "
    done
    # Determine the current directory name
    if [ ${#path_parts[@]} -gt 2 ]; then
        level="${path_parts[-2]}"
        capitalized_level=$(echo "$level" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
        
        # Only add the directory name if it's different from the last one
        if [ "$last_directory" != "$capitalized_level" ]; then
            echo "$indent- **${capitalized_level}**" >> "$README"
            last_directory="$capitalized_level"
        fi
        echo "$indent  - [$title]($file)" >> "$README"
    else
        echo "- [$title]($file)" >> "$README"
    fi
done < "$TEMP_FILE"

# Clean up
rm "$TEMP_FILE"

echo "$README has been updated."
