#!/bin/bash
# WordChat Pro Plugin Build Script
# Creates distributable ZIP file and uploads to Cloudflare R2

set -e  # Exit on error

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}==================================${NC}"
echo -e "${BLUE}WordChat Pro Plugin Builder${NC}"
echo -e "${BLUE}==================================${NC}"

# Get current version from plugin file
CURRENT_VERSION=$(grep -E "^\s*\*\s*Version:" wordchat-pro.php | sed -E 's/.*Version:[[:space:]]*([0-9.]+).*/\1/')
if [ -z "$CURRENT_VERSION" ]; then
    echo -e "${RED}Error: Could not extract version from wordchat-pro.php${NC}"
    exit 1
fi

echo -e "${BLUE}Current version: $CURRENT_VERSION${NC}"

# Auto-increment patch version (e.g., 0.1.28 → 0.1.29)
IFS='.' read -r major minor patch <<< "$CURRENT_VERSION"
NEW_PATCH=$((patch + 1))
VERSION="${major}.${minor}.${NEW_PATCH}"

echo -e "${GREEN}New version: $VERSION${NC}"
echo ""

# Update version in all 3 required locations
echo "Updating version numbers..."

# 1. Update wordchat-pro.php header
sed -i '' "s/\* Version: $CURRENT_VERSION/* Version: $VERSION/" wordchat-pro.php
echo "  ✓ Updated wordchat-pro.php header"

# 2. Update WORDCHAT_VERSION constant
sed -i '' "s/define('WORDCHAT_VERSION', '$CURRENT_VERSION');/define('WORDCHAT_VERSION', '$VERSION');/" wordchat-pro.php
echo "  ✓ Updated WORDCHAT_VERSION constant"

# 3. Update readme.txt stable tag
sed -i '' "s/Stable tag: .*/Stable tag: $VERSION/" readme.txt
echo "  ✓ Updated readme.txt"

echo -e "${GREEN}Version updated from $CURRENT_VERSION to $VERSION${NC}"
echo ""
echo -e "${GREEN}Building version: $VERSION${NC}"

# Build directory
BUILD_DIR="dist"
PLUGIN_DIR="$BUILD_DIR/wordchat-pro"
ZIP_NAME="wordchat-pro-${VERSION}.zip"

# Clean previous builds
echo "Cleaning previous build..."
rm -rf "$BUILD_DIR"
mkdir -p "$PLUGIN_DIR"

# Copy plugin files (exclude dev files)
echo "Copying plugin files..."
rsync -av \
    --exclude='dist' \
    --exclude='build.sh' \
    --exclude='.git' \
    --exclude='.github' \
    --exclude='docs' \
    --exclude='sql' \
    --exclude='node_modules' \
    --exclude='.DS_Store' \
    --exclude='*.log' \
    --exclude='.env' \
    --exclude='.vscode' \
    --exclude='*.md' \
    --exclude='*.zip' \
    --exclude='test' \
    --exclude='tests' \
    --exclude='wordchat.php' \
    --exclude='release.sh' \
    --exclude='update-version.sh' \
    ./ "$PLUGIN_DIR/"

# Verify required files exist
REQUIRED_FILES=(
    "wordchat-pro.php"
    "readme.txt"
    "includes/admin.php"
    "includes/api.php"
    "includes/register.php"
    "includes/updater.php"
    "includes/pro-updater.php"
    "includes/license-admin.php"
    "includes/api-proxy.php"
    "includes/content-writer.php"
    "includes/content-writer-ajax.php"
    "js/chat.js"
    "js/content-writer.js"
    "uninstall.php"
)

echo "Verifying required files..."
for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$PLUGIN_DIR/$file" ]; then
        echo -e "${RED}Error: Required file missing: $file${NC}"
        exit 1
    fi
done

# Create ZIP file
echo "Creating ZIP archive..."
cd "$BUILD_DIR"
zip -r "$ZIP_NAME" wordchat-pro/ -q

# Verify ZIP was created
if [ ! -f "$ZIP_NAME" ]; then
    echo -e "${RED}Error: Failed to create ZIP file${NC}"
    exit 1
fi

# Get ZIP size
ZIP_SIZE=$(du -h "$ZIP_NAME" | cut -f1)

# Move ZIP to dist root and clean up
mv "$ZIP_NAME" ../
cd ..
rm -rf "$BUILD_DIR/wordchat-pro"

echo -e "${GREEN}==================================${NC}"
echo -e "${GREEN}Build complete!${NC}"
echo -e "${GREEN}==================================${NC}"
echo -e "Version: ${BLUE}$VERSION${NC}"
echo -e "File: ${BLUE}$ZIP_NAME${NC}"
echo -e "Size: ${BLUE}$ZIP_SIZE${NC}"
echo ""

# Copy to Cloudflare Pages directory for auto-deployment
CLOUDFLARE_DIR="../word-chat-cloudflare/releases"
if [ -d "$CLOUDFLARE_DIR" ]; then
    echo -e "${BLUE}Copying to Cloudflare Pages directory...${NC}"

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

    # Copy versioned ZIP
    cp "$ZIP_NAME" "$CLOUDFLARE_DIR/"

    # Also copy as 'latest' for easy access
    cp "$ZIP_NAME" "$CLOUDFLARE_DIR/wordchat-pro-latest.zip"

    DOWNLOAD_URL="https://www.word.chat/releases/${ZIP_NAME}"

    echo -e "${GREEN}Copied to Cloudflare Pages!${NC}"
    echo -e "Download URL (after deploy): ${BLUE}$DOWNLOAD_URL${NC}"
    echo ""
    echo -e "${BLUE}Don't forget to commit and push the cloudflare folder!${NC}"
else
    echo -e "${RED}Warning: Cloudflare Pages directory not found at $CLOUDFLARE_DIR${NC}"
    echo "ZIP will remain in: $ZIP_NAME"
fi

# Update download page with new version
DOWNLOAD_PAGE="../word-chat-cloudflare/download.html"
if [ -f "$DOWNLOAD_PAGE" ]; then
    echo -e "${BLUE}Updating download page version numbers...${NC}"

    # Update version badge (v0.1.28 → v0.1.31)
    sed -i '' -E "s/v[0-9]+\.[0-9]+\.[0-9]+/v$VERSION/g" "$DOWNLOAD_PAGE"
    echo "  ✓ Updated version badge"

    # Update "Version X.X.X" text (without 'v' prefix)
    sed -i '' -E "s/Version [0-9]+\.[0-9]+\.[0-9]+/Version $VERSION/g" "$DOWNLOAD_PAGE"
    echo "  ✓ Updated version text"

    # Update download URL
    sed -i '' -E "s|https://www\.word\.chat/releases/wordchat-pro-[0-9]+\.[0-9]+\.[0-9]+\.zip|https://www.word.chat/releases/wordchat-pro-$VERSION.zip|g" "$DOWNLOAD_PAGE"
    echo "  ✓ Updated download URL"

    # Update ZIP filename in instructions
    sed -i '' -E "s/wordchat-pro-[0-9]+\.[0-9]+\.[0-9]+\.zip/wordchat-pro-$VERSION.zip/g" "$DOWNLOAD_PAGE"
    echo "  ✓ Updated ZIP filename references"

    # Update Google Analytics tracking event to include version
    # Need to handle both cases: already has version or doesn't have version
    sed -i '' -E "s/trackDownload\('direct_download(_v[0-9]+\.[0-9]+\.[0-9]+)?'\)/trackDownload('direct_download_v$VERSION')/g" "$DOWNLOAD_PAGE"
    echo "  ✓ Updated GA tracking event"

    echo -e "${GREEN}Download page updated to v$VERSION${NC}"
else
    echo -e "${YELLOW}Warning: Download page not found at $DOWNLOAD_PAGE${NC}"
fi

echo ""
echo -e "${BLUE}==================================${NC}"
echo -e "${BLUE}Build Complete! 🚀${NC}"
echo -e "${BLUE}==================================${NC}"
echo ""
echo "Next steps:"
echo "1. Test the plugin ZIP in a local WordPress installation"
echo ""
echo "2. Commit plugin version changes:"
echo "   git add wordchat-pro.php readme.txt"
echo "   # Note: old wordchat.php can be removed if still present"
echo "   git commit -m 'Bump version to $VERSION'"
echo ""
echo "3. Commit marketing site changes (releases folder and download.html):"
echo "   cd ../word-chat-cloudflare"
echo "   git add releases/$ZIP_NAME download.html"
echo "   git commit -m 'Release v$VERSION'"
echo "   git push origin main"
echo ""
echo "4. Push plugin changes and create git tag:"
echo "   cd ../wordchat-pro"
echo "   git push origin main"
echo "   git tag v$VERSION"
echo "   git push origin v$VERSION"
echo ""
echo "5. Plugin available at: https://www.word.chat/releases/$ZIP_NAME"
echo ""
