#!/bin/bash

# ============================================
# Generate Hugo Playlist Pages from JSON
# ============================================

DATA_FILE="data/playlists/playlists.json"
CONTENT_DIR="content/playlists"

# Check if data file exists
if [ ! -f "$DATA_FILE" ]; then
    echo "❌ Error: $DATA_FILE not found. Run fetch-playlist.sh first."
    exit 1
fi

# Check if data file has content
if [ ! -s "$DATA_FILE" ]; then
    echo "❌ Error: $DATA_FILE is empty. Run fetch-playlist.sh first."
    exit 1
fi

# Create content directory
mkdir -p "$CONTENT_DIR"

# Create _index.md if it doesn't exist
if [ ! -f "$CONTENT_DIR/_index.md" ]; then
    cat > "$CONTENT_DIR/_index.md" << 'EOF'
---
title: "Playlists"
---
EOF
fi

# Clear old playlist pages (keep _index.md)
echo "Clearing old playlist pages..."
find "$CONTENT_DIR" -maxdepth 1 -type f -name "*.md" ! -name "_index.md" -delete

echo "Generating playlist pages..."

# Function to escape YAML strings
escape_yaml() {
    echo "$1" | sed 's/"/\\"/g' | sed 's/:/\\:/g' | tr -d '\n\r'
}

# Process each playlist
cat "$DATA_FILE" | jq -c '.playlists[]' 2>/dev/null | while read -r playlist; do
    # Skip if playlist is empty
    if [ -z "$playlist" ] || [ "$playlist" == "null" ]; then
        continue
    fi
    
    # Extract fields
    NAME=$(echo "$playlist" | jq -r '.name // "Untitled Playlist"')
    PLAYLIST_ID=$(echo "$playlist" | jq -r '.id // ""')
    DESCRIPTION=$(echo "$playlist" | jq -r '.description // ""')
    IMAGE=$(echo "$playlist" | jq -r '.image // ""')
    CREATED_AT=$(echo "$playlist" | jq -r '.created_at // 0')
    TRACKS=$(echo "$playlist" | jq -c '.tracks // []')
    
    # Escape YAML strings
    NAME_ESC=$(echo "$NAME" | sed 's/"/\\"/g')
    DESCRIPTION_ESC=$(echo "$DESCRIPTION" | sed 's/"/\\"/g' | tr -d '\n\r')
    IMAGE_ESC=$(echo "$IMAGE" | sed 's/"/\\"/g')
    
    # Skip if no name
    if [ -z "$NAME" ] || [ "$NAME" == "null" ]; then
        continue
    fi
    
    # Create URL-friendly slug
    SLUG=$(echo "$NAME" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
    if [ -z "$SLUG" ]; then
        SLUG="${PLAYLIST_ID:0:12}"
    fi
    
    # Convert created_at to date
    if [ "$CREATED_AT" != "null" ] && [ "$CREATED_AT" -gt 0 ] 2>/dev/null; then
        CREATED_DATE=$(date -d "@$CREATED_AT" "+%Y-%m-%d" 2>/dev/null || echo $(date "+%Y-%m-%d"))
    else
        CREATED_DATE=$(date "+%Y-%m-%d")
    fi
    
    # Write the markdown file with escaped values
    cat > "$CONTENT_DIR/$SLUG.md" <<EOF
---
title: "$NAME_ESC"
date: $CREATED_DATE
draft: false
playlist_id: "$PLAYLIST_ID"
playlist_description: "$DESCRIPTION_ESC"
playlist_image: "$IMAGE_ESC"
playlist_tracks: $TRACKS
playlist_created_at: $CREATED_AT
---
EOF
    
    echo "✅ Generated: $CONTENT_DIR/$SLUG.md"
done

echo ""
echo "📊 Generated playlist pages"