#!/usr/bin/env bash
#
# SEOBot AI — Deployment Script
# Builds a production-ready ZIP for WordPress plugin installation.
#
# Usage:
#   ./deploy.sh              # Build zip with version from plugin header
#   ./deploy.sh 1.2.0        # Build zip with explicit version
#   ./deploy.sh --dry-run    # Show what would be included without building
#

set -euo pipefail

# ─────────────────────── Config ───────────────────────

PLUGIN_SLUG="seo-bot-ai"
PLUGIN_FILE="seobot-ai.php"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="${SCRIPT_DIR}/build"
DIST_DIR="${SCRIPT_DIR}/dist"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# ─────────────────────── Helpers ───────────────────────

log()   { echo -e "${GREEN}✓${NC} $1"; }
warn()  { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; exit 1; }
info()  { echo -e "${CYAN}→${NC} $1"; }

# Human-readable file size (portable — no dependency on numfmt/coreutils)
human_size() {
    local bytes=$1
    if   (( bytes >= 1073741824 )); then awk "BEGIN{printf \"%.1fGiB\", $bytes/1073741824}"
    elif (( bytes >= 1048576 ));    then awk "BEGIN{printf \"%.1fMiB\", $bytes/1048576}"
    elif (( bytes >= 1024 ));       then awk "BEGIN{printf \"%.1fKiB\", $bytes/1024}"
    else printf "%dB" "$bytes"
    fi
}

# ─────────────────────── Parse Args ───────────────────────

DRY_RUN=false
CUSTOM_VERSION=""

for arg in "$@"; do
    case "$arg" in
        --dry-run) DRY_RUN=true ;;
        --help|-h)
            echo "Usage: ./deploy.sh [version] [--dry-run]"
            echo ""
            echo "Options:"
            echo "  version      Override the version number (e.g. 1.2.0)"
            echo "  --dry-run    List files that would be included without building"
            echo "  -h, --help   Show this help message"
            exit 0
            ;;
        *) CUSTOM_VERSION="$arg" ;;
    esac
done

# ─────────────────────── Version ───────────────────────

cd "$SCRIPT_DIR"

if [[ -n "$CUSTOM_VERSION" ]]; then
    VERSION="$CUSTOM_VERSION"
else
    VERSION=$(grep -i "Version:" "$PLUGIN_FILE" | head -1 | sed 's/.*Version:\s*//' | tr -d '[:space:]')
fi

if [[ -z "$VERSION" ]]; then
    error "Could not determine plugin version. Pass it as an argument: ./deploy.sh 1.0.0"
fi

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║   SEOBot AI — Deployment Builder        ║${NC}"
echo -e "${BOLD}║   Version: ${CYAN}${VERSION}${NC}${BOLD}                              ║${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════════╝${NC}"
echo ""

# ─────────────────────── File Manifest ───────────────────────

# Files and directories to include in the ZIP
INCLUDE_FILES=(
    "seobot-ai.php"
    "uninstall.php"
    "readme.txt"
    "README.md"
)

INCLUDE_DIRS=(
    "includes"
    "templates"
    "assets"
    "languages"
)

# Files/patterns to exclude
EXCLUDE_PATTERNS=(
    ".git"
    ".gitignore"
    ".vscode"
    ".DS_Store"
    "Thumbs.db"
    "node_modules"
    "vendor"
    "build"
    "dist"
    "deploy.sh"
    "*.log"
    "*.map"
    ".editorconfig"
    ".phpcs.xml"
    "phpunit.xml"
    "composer.json"
    "composer.lock"
    "package.json"
    "package-lock.json"
    "webpack.config.js"
    "tests"
)

# ─────────────────────── Validation ───────────────────────

info "Validating project structure…"

# Check critical files exist
for f in "${INCLUDE_FILES[@]}"; do
    if [[ ! -f "$SCRIPT_DIR/$f" ]]; then
        error "Required file missing: $f"
    fi
done

# Check directories exist
for d in "${INCLUDE_DIRS[@]}"; do
    if [[ ! -d "$SCRIPT_DIR/$d" ]]; then
        error "Required directory missing: $d"
    fi
done

log "All required files and directories present."

# Check PHP syntax on all PHP files (skipped if php is not installed)
if command -v php &>/dev/null; then
    info "Checking PHP syntax…"
    PHP_ERRORS=0
    while IFS= read -r phpfile; do
        if ! php -l "$phpfile" > /dev/null 2>&1; then
            echo -e "  ${RED}✗ Syntax error:${NC} $phpfile"
            php -l "$phpfile" 2>&1 | head -3 | sed 's/^/    /'
            PHP_ERRORS=$((PHP_ERRORS + 1))
        fi
    done < <(find "$SCRIPT_DIR" -name "*.php" \
        -not -path "*/vendor/*" \
        -not -path "*/node_modules/*" \
        -not -path "*/build/*" \
        -not -path "*/dist/*")

    if [[ $PHP_ERRORS -gt 0 ]]; then
        error "$PHP_ERRORS PHP file(s) have syntax errors. Fix them before deploying."
    fi

    log "All PHP files pass syntax check."
else
    warn "PHP not found — skipping syntax check."
fi

# ─────────────────────── Inventory ───────────────────────

info "Building file inventory…"

FILE_COUNT=0
TOTAL_SIZE=0

echo ""
echo -e "${BOLD}  Files to include:${NC}"

for f in "${INCLUDE_FILES[@]}"; do
    SIZE=$(wc -c < "$SCRIPT_DIR/$f" | tr -d '[:space:]')
    TOTAL_SIZE=$((TOTAL_SIZE + SIZE))
    FILE_COUNT=$((FILE_COUNT + 1))
    printf "    %-50s %s\n" "$f" "$(human_size $SIZE)"
done

for d in "${INCLUDE_DIRS[@]}"; do
    while IFS= read -r f; do
        REL="${f#$SCRIPT_DIR/}"
        SIZE=$(wc -c < "$f" | tr -d '[:space:]')
        TOTAL_SIZE=$((TOTAL_SIZE + SIZE))
        FILE_COUNT=$((FILE_COUNT + 1))
        printf "    %-50s %s\n" "$REL" "$(human_size $SIZE)"
    done < <(find "$SCRIPT_DIR/$d" -type f \
        -not -name ".DS_Store" \
        -not -name "*.map" \
        | sort)
done

echo ""
HUMAN_SIZE=$(human_size $TOTAL_SIZE)
info "${FILE_COUNT} files, ${HUMAN_SIZE} total (uncompressed)"

# ─────────────────────── Dry Run Exit ───────────────────────

if $DRY_RUN; then
    echo ""
    warn "Dry run — no ZIP was created."
    exit 0
fi

# ─────────────────────── Build ───────────────────────

info "Cleaning previous build…"
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR/$PLUGIN_SLUG"
mkdir -p "$DIST_DIR"

info "Copying files…"

# Copy individual files
for f in "${INCLUDE_FILES[@]}"; do
    cp "$SCRIPT_DIR/$f" "$BUILD_DIR/$PLUGIN_SLUG/$f"
done

# Copy directories (preserving structure)
for d in "${INCLUDE_DIRS[@]}"; do
    mkdir -p "$BUILD_DIR/$PLUGIN_SLUG/$d"
    rsync -a --exclude='.DS_Store' --exclude='*.map' --exclude='icon-*.png' \
        "$SCRIPT_DIR/$d/" "$BUILD_DIR/$PLUGIN_SLUG/$d/"
done

log "Files copied to build directory."

# ─────────────────────── Version Stamp ───────────────────────

if [[ -n "$CUSTOM_VERSION" ]]; then
    info "Stamping version ${VERSION} into plugin header…"

    sed -i '' "s/^\( \* Version:\s*\).*/\1${VERSION}/" \
        "$BUILD_DIR/$PLUGIN_SLUG/$PLUGIN_FILE" 2>/dev/null || \
    sed -i "s/^\( \* Version:\s*\).*/\1${VERSION}/" \
        "$BUILD_DIR/$PLUGIN_SLUG/$PLUGIN_FILE"

    sed -i '' "s/define( 'WPSEOBOT_VERSION', '.*' )/define( 'WPSEOBOT_VERSION', '${VERSION}' )/" \
        "$BUILD_DIR/$PLUGIN_SLUG/$PLUGIN_FILE" 2>/dev/null || \
    sed -i "s/define( 'WPSEOBOT_VERSION', '.*' )/define( 'WPSEOBOT_VERSION', '${VERSION}' )/" \
        "$BUILD_DIR/$PLUGIN_SLUG/$PLUGIN_FILE"

    log "Version stamped."
fi

# ─────────────────────── Create ZIP ───────────────────────

ZIP_NAME="${PLUGIN_SLUG}-${VERSION}.zip"
ZIP_PATH="${DIST_DIR}/${ZIP_NAME}"

info "Creating ZIP archive…"

cd "$BUILD_DIR"
zip -rq "$ZIP_PATH" "$PLUGIN_SLUG/"

ZIP_SIZE=$(wc -c < "$ZIP_PATH" | tr -d '[:space:]')
HUMAN_ZIP=$(human_size $ZIP_SIZE)

log "ZIP created: ${ZIP_NAME} (${HUMAN_ZIP})"

# ─────────────────────── Checksum ───────────────────────

info "Generating checksums…"

cd "$DIST_DIR"
shasum -a 256 "$ZIP_NAME" > "${ZIP_NAME}.sha256"
MD5_HASH=$(md5 -q "$ZIP_PATH" 2>/dev/null || md5sum "$ZIP_PATH" | awk '{print $1}')

log "SHA-256: $(cat "${ZIP_NAME}.sha256" | awk '{print $1}')"
log "MD5:     ${MD5_HASH}"

# ─────────────────────── Cleanup ───────────────────────

info "Cleaning up build directory…"
rm -rf "$BUILD_DIR"
log "Build directory removed."

# ─────────────────────── Summary ───────────────────────

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║   ${GREEN}✓ Deployment package ready!${NC}${BOLD}                 ║${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${BOLD}Plugin:${NC}   ${PLUGIN_SLUG}"
echo -e "  ${BOLD}Version:${NC}  ${VERSION}"
echo -e "  ${BOLD}Package:${NC}  dist/${ZIP_NAME}"
echo -e "  ${BOLD}Size:${NC}     ${HUMAN_ZIP}"
echo -e "  ${BOLD}Files:${NC}    ${FILE_COUNT}"
echo ""
echo -e "  ${CYAN}Upload the ZIP via:${NC}"
echo -e "    WordPress Admin → Plugins → Add New → Upload Plugin"
echo ""
echo -e "  ${CYAN}Or deploy via WP-CLI:${NC}"
echo -e "    wp plugin install dist/${ZIP_NAME} --activate --force"
echo ""
