#!/bin/bash
# Convert mdbook to Grav format in-place
# Usage: convert-mdbook-to-grav.sh <repo_path>

REPO="$1"
SRC="$REPO/src"

if [ ! -d "$SRC" ]; then
    echo "ERROR: No src/ directory in $REPO"
    exit 1
fi

cd "$REPO" || exit 1

echo "Converting: $REPO"

# Parse SUMMARY.md to get page order
SUMMARY="$SRC/SUMMARY.md"
if [ ! -f "$SUMMARY" ]; then
    echo "ERROR: No SUMMARY.md found"
    exit 1
fi

# Create Grav pages directory structure
# mdbook: src/chapter/file.md -> Grav: pages/02.chapter/file.md (with frontmatter)

# Step 1: Rename src/ to pages/ temporarily
mv src pages_tmp

# Step 2: Create proper Grav structure
mkdir -p pages

# Step 3: Process each markdown file
ORDER=1
find pages_tmp -name "*.md" -type f | while read MD_FILE; do
    REL_PATH="${MD_FILE#pages_tmp/}"
    DIRNAME=$(dirname "$REL_PATH")
    BASENAME=$(basename "$REL_PATH" .md)
    
    # Create numbered folder (01.home, 02.chapter, etc.)
    if [ "$BASENAME" = "introduction" ] || [ "$BASENAME" = "Introduction" ]; then
        FOLDER_NAME="01.home"
        ORDER=1
    elif [ "$BASENAME" = "SUMMARY" ]; then
        # Skip SUMMARY.md - Grav doesn't need it
        continue
    else
        ORDER=$((ORDER + 1))
        FOLDER_NAME=$(printf "%02d.%s" $ORDER "$BASENAME")
    fi
    
    mkdir -p "pages/$FOLDER_NAME"
    
    # Add Grav frontmatter if not present
    TARGET_FILE="pages/$FOLDER_NAME/default.md"
    
    # Get title from first heading or filename
    TITLE=$(grep -m1 "^#" "$MD_FILE" 2>/dev/null | sed 's/^#*\s*//' | head -1)
    [ -z "$TITLE" ] && TITLE="$BASENAME"
    
    # Check if file already has frontmatter
    if head -1 "$MD_FILE" | grep -q "^---"; then
        # Has frontmatter, copy as-is
        cp "$MD_FILE" "$TARGET_FILE"
    else
        # Add frontmatter
        {
            echo "---"
            echo "title: '$TITLE'"
            echo "menu: '$TITLE'"
            echo "---"
            echo ""
            cat "$MD_FILE"
        } > "$TARGET_FILE"
    fi
    
    echo "  Created: $FOLDER_NAME/default.md"
done

# Copy any non-md assets (images, etc.)
find pages_tmp -type f ! -name "*.md" | while read ASSET; do
    REL_PATH="${ASSET#pages_tmp/}"
    mkdir -p "pages/$(dirname "$REL_PATH")"
    cp "$ASSET" "pages/$REL_PATH"
    echo "  Copied asset: $REL_PATH"
done

# Cleanup
rm -rf pages_tmp

# Remove mdbook-specific files
rm -f book.toml

echo "Conversion complete for $REPO"
echo "Files now in: $REPO/pages/"
