#!/bin/bash

# Script to sync code blocks in README.md with actual file contents
# Usage: ./tools/docgen

README_FILE="README.md"
TEMP_FILE=$(mktemp)

# Check if README.md exists
if [ ! -f "$README_FILE" ]; then
    echo "Error: $README_FILE not found" >&2
    exit 1
fi

# Process the file line by line
in_code_block=0
code_block_lang=""
code_block_file=""
code_block_content=""

while IFS= read -r line || [ -n "$line" ]; do
    # Check for end of code block first (when already in a block)
    if [ $in_code_block -eq 1 ] && [[ "$line" =~ ^\`\`\`$ ]]; then
        # End of code block
        if [ -n "$code_block_file" ] && [ -f "$code_block_file" ]; then
            # Replace with actual file content
            while IFS= read -r file_line || [ -n "$file_line" ]; do
                echo "$file_line"
            done < "$code_block_file"
            echo "$line"
        else
            # Keep original content
            if [ -n "$code_block_content" ]; then
                echo -n "$code_block_content"
            fi
            echo "$line"
        fi
        in_code_block=0
        code_block_lang=""
        code_block_file=""
        code_block_content=""
        continue
    fi
    
    # Check for code block start (```language path/to/file or ```language)
    if [ $in_code_block -eq 0 ] && [[ "$line" =~ ^\`\`\`([^[:space:]]+)[[:space:]]+(.+)$ ]]; then
        code_block_lang="${BASH_REMATCH[1]}"
        code_block_file="${BASH_REMATCH[2]}"
        
        # Check if the second part looks like a file path (contains / or ends with common extensions)
        if [[ "$code_block_file" =~ ^[^/]+/ ]] || [[ "$code_block_file" =~ \.(zx|zig|ts|tsx|js|jsx|py|rs|go|java|cpp|h|hpp|md|sh|bash|zsh)$ ]]; then
            in_code_block=1
            code_block_content=""
            echo "$line"
            continue
        else
            # Not a file path, treat as regular code block
            in_code_block=1
            code_block_lang="${BASH_REMATCH[1]}"
            code_block_file=""
            code_block_content=""
            echo "$line"
            continue
        fi
    elif [ $in_code_block -eq 0 ] && [[ "$line" =~ ^\`\`\`([^[:space:]]*)$ ]]; then
        # Code block start without file path (just ``` or ```language)
        in_code_block=1
        code_block_lang="${BASH_REMATCH[1]}"
        code_block_file=""
        code_block_content=""
        echo "$line"
        continue
    fi
    
    if [ $in_code_block -eq 1 ]; then
        if [ -z "$code_block_file" ]; then
            # Regular code block without file path, accumulate content
            code_block_content+="$line"$'\n'
        fi
        # If we have a file path, skip accumulating (we'll replace with file content)
    else
        echo "$line"
    fi
done < "$README_FILE" > "$TEMP_FILE"

# Replace original file
mv "$TEMP_FILE" "$README_FILE"

echo "Synced code blocks in $README_FILE"