#!/usr/bin/env bash
set -euo pipefail

# Simple embedmd replacement for syncing code snippets in markdown
# Usage: embedmd.sh [-c|--check] <markdown-file>

check_mode=false
if [[ "${1:-}" == "-c" ]] || [[ "${1:-}" == "--check" ]]; then
    check_mode=true
    shift
fi

markdown_file="${1:-README.md}"

if [[ ! -f "$markdown_file" ]]; then
    echo "Error: File not found: $markdown_file" >&2
    exit 1
fi

# Create temp file
temp_file=$(mktemp)
trap 'rm -f "$temp_file"' EXIT

# Process the markdown file
in_code_block=false
code_file=""
code_lang=""
skip_next_block=false

while IFS= read -r line || [[ -n "$line" ]]; do
    # Check for embed-readme directive: [embed-readme]:# (path [language])
    if [[ "$line" =~ ^\[embed-readme\]:#[[:space:]]*\(([^[:space:]]+)([[:space:]]+([^\)]+))?\) ]]; then
        code_file="${BASH_REMATCH[1]}"
        code_lang="${BASH_REMATCH[3]:-}"
        
        # Write the directive line
        echo "$line" >> "$temp_file"
        
        # Check if the file exists
        if [[ ! -f "$code_file" ]]; then
            echo "Error: Referenced file not found: $code_file" >&2
            exit 1
        fi
        
        # Write the code block with the file contents
        echo "\`\`\`${code_lang}" >> "$temp_file"
        cat "$code_file" >> "$temp_file"
        echo "\`\`\`" >> "$temp_file"
        
        skip_next_block=true
        continue
    fi
    
    # Skip the existing code block after embedmd directive
    if $skip_next_block; then
        if [[ "$line" =~ ^\`\`\` ]]; then
            if $in_code_block; then
                # End of code block - skip and reset
                in_code_block=false
                skip_next_block=false
            else
                # Start of code block - skip
                in_code_block=true
            fi
            continue
        fi
        
        # Skip lines inside the code block
        if $in_code_block; then
            continue
        fi
    fi
    
    # Write all other lines as-is
    echo "$line" >> "$temp_file"
done < "$markdown_file"

# Check mode: compare and return error if different
if $check_mode; then
    if ! diff -q "$markdown_file" "$temp_file" > /dev/null 2>&1; then
        echo "Error: $markdown_file is out of sync. Run 'bin/embedmd.sh $markdown_file' to update." >&2
        diff -u "$markdown_file" "$temp_file" || true
        exit 1
    fi
    echo "✓ $markdown_file is in sync"
    exit 0
fi

# Update mode: replace the original file
mv "$temp_file" "$markdown_file"
echo "✓ Updated $markdown_file"
