
# Excalidraw Update Script
# Downloads the latest Excalidraw standalone build and checks for updates
# Usage: ./scripts/update-excalidraw.sh [--force]

set -e

# Configuration
EXCALIDRAW_DIR="/Users/rpmbbu/LocalPHPStorm/m1_erp_web/public/assets/excalidraw"
CURRENT_VERSION_FILE="$EXCALIDRAW_DIR/.version"
EXCALIDRAW_CDN="https://unpkg.com/@excalidraw/excalidraw"
FORCE_UPDATE=false

# Parse arguments
if [[ "$1" == "--force" ]]; then
    FORCE_UPDATE=true
fi

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "================================================"
echo "Excalidraw Local Update Script"
echo "================================================"
echo ""

# Create directory if it doesn't exist
mkdir -p "$EXCALIDRAW_DIR"

# Function to get latest version from npm
get_latest_version() {
    echo "Checking latest version from npm..."
    LATEST_VERSION=$(curl -s https://registry.npmjs.org/@excalidraw/excalidraw/latest | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
    if [ -z "$LATEST_VERSION" ]; then
        echo -e "${RED}Error: Could not fetch latest version${NC}"
        exit 1
    fi
    echo -e "${GREEN}Latest version: $LATEST_VERSION${NC}"
}

# Function to get current version
get_current_version() {
    if [ -f "$CURRENT_VERSION_FILE" ]; then
        CURRENT_VERSION=$(cat "$CURRENT_VERSION_FILE")
        echo -e "${GREEN}Current version: $CURRENT_VERSION${NC}"
    else
        CURRENT_VERSION=""
        echo -e "${YELLOW}No current version found${NC}"
    fi
}

# Function to download Excalidraw
download_excalidraw() {
    local version=$1
    echo ""
    echo "Downloading Excalidraw v$version..."

    # Download main files
    echo "  → Downloading excalidraw.min.js..."
    curl -s -o "$EXCALIDRAW_DIR/excalidraw.min.js" \
        "$EXCALIDRAW_CDN@$version/dist/excalidraw.production.min.js"

    echo "  → Downloading excalidraw.min.css..."
    curl -s -o "$EXCALIDRAW_DIR/excalidraw.min.css" \
        "$EXCALIDRAW_CDN@$version/dist/excalidraw.min.css"

    # Download assets
    echo "  → Downloading fonts and assets..."
    mkdir -p "$EXCALIDRAW_DIR/fonts"

    # Download common fonts (these don't change often)
    curl -s -o "$EXCALIDRAW_DIR/fonts/Virgil.woff2" \
        "https://unpkg.com/@excalidraw/excalidraw@$version/dist/excalidraw-assets/Virgil.woff2" || true
    curl -s -o "$EXCALIDRAW_DIR/fonts/Cascadia.woff2" \
        "https://unpkg.com/@excalidraw/excalidraw@$version/dist/excalidraw-assets/Cascadia.woff2" || true

    # Save version
    echo "$version" > "$CURRENT_VERSION_FILE"

    echo -e "${GREEN}✓ Download complete!${NC}"
}

# Function to create wrapper
create_wrapper() {
    echo ""
    echo "Creating local wrapper..."

    cat > "$EXCALIDRAW_DIR/excalidraw-wrapper.js" << 'EOF'
/**
 * Excalidraw Local Wrapper
 * Provides a simple interface to initialize Excalidraw locally
 */

export function initExcalidraw(containerId, options = {}) {
    const container = typeof containerId === 'string'
        ? document.getElementById(containerId)
        : containerId;

    if (!container) {
        throw new Error('Container not found: ' + containerId);
    }

    // Load Excalidraw CSS
    const cssId = 'excalidraw-styles';
    if (!document.getElementById(cssId)) {
        const link = document.createElement('link');
        link.id = cssId;
        link.rel = 'stylesheet';
        link.href = '/assets/excalidraw/excalidraw.min.css';
        document.head.appendChild(link);
    }

    // Load Excalidraw script
    return new Promise((resolve, reject) => {
        const scriptId = 'excalidraw-script';
        if (window.ExcalidrawLib) {
            initExcalidrawInstance(container, options, resolve);
            return;
        }

        if (!document.getElementById(scriptId)) {
            const script = document.createElement('script');
            script.id = scriptId;
            script.src = '/assets/excalidraw/excalidraw.min.js';
            script.onload = () => {
                initExcalidrawInstance(container, options, resolve);
            };
            script.onerror = reject;
            document.head.appendChild(script);
        }
    });
}

function initExcalidrawInstance(container, options, callback) {
    const {
        initialData,
        theme = 'light',
        onChange,
        onReady
    } = options;

    // Wait for React and Excalidraw to be ready
    if (typeof window.React === 'undefined' || typeof window.ExcalidrawLib === 'undefined') {
        setTimeout(() => initExcalidrawInstance(container, options, callback), 100);
        return;
    }

    const React = window.React;
    const ReactDOM = window.ReactDOM;
    const { Excalidraw, MainMenu } = window.ExcalidrawLib;

    let excalidrawAPI = null;

    const excalidrawElement = React.createElement(Excalidraw, {
        initialData: initialData || { elements: [], appState: {} },
        theme: theme,
        onChange: (elements, appState, files) => {
            if (onChange) onChange(elements, appState, files);
        },
        ref: (api) => {
            if (api) {
                excalidrawAPI = api;
                if (onReady) onReady(api);
            }
        }
    });

    const root = ReactDOM.createRoot(container);
    root.render(excalidrawElement);

    callback({
        api: excalidrawAPI,
        root: root
    });
}
EOF

    echo -e "${GREEN}✓ Wrapper created${NC}"
}

# Main execution
get_latest_version
get_current_version

# Check if update is needed
if [ "$FORCE_UPDATE" = true ]; then
    echo -e "${YELLOW}Force update requested${NC}"
    download_excalidraw "$LATEST_VERSION"
    create_wrapper
elif [ "$CURRENT_VERSION" != "$LATEST_VERSION" ]; then
    echo -e "${YELLOW}Update available: $CURRENT_VERSION → $LATEST_VERSION${NC}"
    read -p "Update now? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        download_excalidraw "$LATEST_VERSION"
        create_wrapper
    else
        echo "Update skipped"
        exit 0
    fi
else
    echo -e "${GREEN}✓ Already up to date (v$CURRENT_VERSION)${NC}"

    # Check if files exist
    if [ ! -f "$EXCALIDRAW_DIR/excalidraw.min.js" ]; then
        echo -e "${YELLOW}Files missing, re-downloading...${NC}"
        download_excalidraw "$LATEST_VERSION"
        create_wrapper
    fi
fi

echo ""
echo "================================================"
echo -e "${GREEN}Excalidraw is ready for offline use!${NC}"
echo "Location: $EXCALIDRAW_DIR"
echo "Version: $(cat $CURRENT_VERSION_FILE)"
echo "================================================"