#!/bin/bash

# Script to generate a GitHub markdown table of all schema.json files
# and replace the existing table in README.md

README_FILE="README.md"
TEMP_FILE="temp_table.md"
TEMP_README="temp_readme.md"

# Function to extract version from $id in schema.json
extract_version() {
    local file="$1"
    # Extract the $id value and get the version number before /schema.json
    local id_value=$(grep -o '"$id"[[:space:]]*:[[:space:]]*"[^"]*"' "$file" 2>/dev/null | sed 's/.*":\s*"\([^"]*\)".*/\1/')
    if [[ "$id_value" =~ /([0-9]+\.[0-9]+\.[0-9]+)/schema\.json$ ]]; then
        echo "${BASH_REMATCH[1]}"
    else
        echo "N/A"
    fi
}

# Start building the markdown table
echo "## Schema Files" > "$TEMP_FILE"
echo "" >> "$TEMP_FILE"
echo "| Schema Path | Latest Version |" >> "$TEMP_FILE"
echo "|-------------|----------------|" >> "$TEMP_FILE"

# Find all schema.json files under schemas/ directory
find schemas/ -name "schema.json" -type f | sort | while read -r filepath; do
    # Extract the path between "schemas/" and "/schema.json"
    # Remove "schemas/" prefix and "/schema.json" suffix
    relative_path=$(echo "$filepath" | sed 's|^schemas/||' | sed 's|/schema.json$||')
    
    # Create the GitHub URL
    github_url="https://github.com/FabricTools/fabric-item-schemas/commits/main/schemas/${relative_path}"
    
    # Extract version from the schema file
    version=$(extract_version "$filepath")
    
    # Add row to the markdown table
    echo "| [$relative_path]($github_url) | $version |" >> "$TEMP_FILE"
done

# Check if the schema table section already exists in README.md
if grep -q "## Schema Files" "$README_FILE"; then
    # Find the line number where "## Schema Files" starts
    start_line=$(grep -n "## Schema Files" "$README_FILE" | cut -d: -f1)
    
    # Create new README with content before the schema section, preserving original spacing
    head -n $((start_line - 1)) "$README_FILE" > "$TEMP_README"
    
    # Ensure exactly one blank line before the schema section
    # Remove only the last line if it's blank, then add exactly one blank line
    if tail -n 1 "$TEMP_README" | grep -q '^[[:space:]]*$'; then
        # Last line is blank, keep the content as is
        cat "$TEMP_FILE" >> "$TEMP_README"
    else
        # Last line is not blank, add one blank line
        echo "" >> "$TEMP_README"
        cat "$TEMP_FILE" >> "$TEMP_README"
    fi
    
    # Replace the original README
    mv "$TEMP_README" "$README_FILE"
    
    echo "Schema Files section has been replaced in $README_FILE"
else
    # Check if README ends with a blank line, if not add one
    if ! tail -n 1 "$README_FILE" | grep -q '^[[:space:]]*$'; then
        echo "" >> "$README_FILE"
    fi
    
    # Append the table to README.md if section doesn't exist
    cat "$TEMP_FILE" >> "$README_FILE"
    echo "Schema table has been appended to $README_FILE"
fi

# Clean up temporary files
rm -f "$TEMP_FILE" "$TEMP_README"
