#!/bin/bash
# =============================================================================
# MODPACK VERSION CHECKER - BUILD SCRIPT
# =============================================================================
#
# Handles TSX injection + frontend compilation ONLY.
# PHP files are deployed manually by Chronicler from the repo.
#
# @author      Firefrost Gaming / Frostystyle <dev@firefrostgaming.com>
# @version     1.1.0
# =============================================================================

set -e
set -u

echo "=========================================="
echo "ModpackChecker Build Script v1.1.0"
echo "=========================================="

# Determine the extension source directory
if [ -d ".blueprint/extensions/modpackchecker/views" ]; then
    EXT_DIR=".blueprint/extensions/modpackchecker"
elif [ -d ".blueprint/dev/views" ]; then
    EXT_DIR=".blueprint/dev"
else
    echo "ERROR: Cannot find extension views directory"
    exit 1
fi

echo "Using extension directory: $EXT_DIR"

# ===========================================
# 0. NODE VERSION DETECTION
# ===========================================
NODE_MAJOR_VERSION=$(node -v | grep -oE '[0-9]+' | head -1)
echo "Detected Node.js version: v$NODE_MAJOR_VERSION"

if [ "$NODE_MAJOR_VERSION" -lt 16 ]; then
    echo "ERROR: ModpackChecker requires Node.js 16 or higher."
    exit 1
fi

if [ "$NODE_MAJOR_VERSION" -ge 17 ]; then
    echo "Applying OpenSSL legacy provider for Node 17+ compatibility..."
    export NODE_OPTIONS=--openssl-legacy-provider
fi

# ===========================================
# 1. COPY TSX COMPONENTS (always — even on reinstall)
# ===========================================
echo ""
echo "--- Copy Components ---"

if [ -f "$EXT_DIR/views/server/wrapper.tsx" ]; then
    cp "$EXT_DIR/views/server/wrapper.tsx" resources/scripts/components/server/ModpackVersionCard.tsx
    echo "✓ Copied ModpackVersionCard.tsx"
else
    echo "⚠ wrapper.tsx not found"
fi

if [ -f "$EXT_DIR/views/server/ErrorBoundary.tsx" ]; then
    cp "$EXT_DIR/views/server/ErrorBoundary.tsx" resources/scripts/components/server/ModpackErrorBoundary.tsx
    echo "✓ Copied ModpackErrorBoundary.tsx"
else
    echo "⚠ ErrorBoundary.tsx not found"
fi

# ===========================================
# 2. INJECT INTO AFTERINFORMATION.TSX
# ===========================================
echo ""
echo "--- Console Widget Injection ---"

AFTER_INFO="resources/scripts/blueprint/components/Server/Terminal/AfterInformation.tsx"
if [ -f "$AFTER_INFO" ]; then
    # Step A: Add imports if missing
    if ! grep -q "ModpackVersionCard" "$AFTER_INFO" 2>/dev/null; then
        sed -i '/\/\* blueprint\/import \*\//a import ModpackVersionCard from "@/components/server/ModpackVersionCard";' "$AFTER_INFO"
        echo "✓ Added ModpackVersionCard import"
    fi
    if ! grep -q "ModpackErrorBoundary" "$AFTER_INFO" 2>/dev/null; then
        sed -i '/\/\* blueprint\/import \*\//a import ModpackErrorBoundary from "@/components/server/ModpackErrorBoundary";' "$AFTER_INFO"
        echo "✓ Added ModpackErrorBoundary import"
    fi

    # Step B: Add wrapped component if not present
    if ! grep -q "ModpackErrorBoundary" "$AFTER_INFO" 2>/dev/null || ! grep -q "<ModpackErrorBoundary>" "$AFTER_INFO" 2>/dev/null; then
        # Remove bare <ModpackVersionCard /> if it exists (upgrade path)
        sed -i 's|<ModpackVersionCard />||g' "$AFTER_INFO"
        # Inject wrapped version
        sed -i 's|{/\* blueprint/react \*/}|{/* blueprint/react */}\n      <ModpackErrorBoundary><ModpackVersionCard /></ModpackErrorBoundary>|' "$AFTER_INFO"
        echo "✓ Injected wrapped ModpackVersionCard into AfterInformation.tsx"
    else
        echo "○ ModpackVersionCard (with ErrorBoundary) already present"
    fi
else
    echo "⚠ AfterInformation.tsx not found, skipping injection"
fi

# ===========================================
# 3. DASHBOARD BADGE
# ===========================================
echo ""
echo "--- Dashboard Badge ---"

# Always copy the component file
if [ -f "$EXT_DIR/views/dashboard/UpdateBadge.tsx" ]; then
    mkdir -p resources/scripts/components/dashboard
    cp "$EXT_DIR/views/dashboard/UpdateBadge.tsx" resources/scripts/components/dashboard/UpdateBadge.tsx
    echo "✓ Copied UpdateBadge.tsx"
else
    echo "⚠ UpdateBadge.tsx not found"
fi

# Inject into ServerRow.tsx only if not already present
if ! grep -q "UpdateBadge" resources/scripts/components/dashboard/ServerRow.tsx 2>/dev/null; then
    sed -i '1i import UpdateBadge from "@/components/dashboard/UpdateBadge";' resources/scripts/components/dashboard/ServerRow.tsx
    sed -i 's|{server.name}</p>|{server.name}<UpdateBadge serverUuid={server.uuid} /></p>|' resources/scripts/components/dashboard/ServerRow.tsx
    echo "✓ Injected UpdateBadge into ServerRow.tsx"
else
    echo "○ UpdateBadge already present in ServerRow.tsx"
fi

# ===========================================
# 3. ADMIN CONTROLLER (Blueprint auto-generated)
# ===========================================
echo ""
echo "--- Admin Controller ---"

BP_CONTROLLER=$(find app/Http/Controllers/Admin/Extensions/modpackchecker -name "*Controller.php" 2>/dev/null | head -n 1)
if [ -n "$BP_CONTROLLER" ]; then
    cp "$EXT_DIR/admin/controller.php" "$BP_CONTROLLER"
    echo "✓ Overwrote Blueprint controller: $BP_CONTROLLER"
else
    echo "⚠ Blueprint controller not found — admin panel may need manual controller deploy"
fi

# ===========================================
# 4. CLEAR CACHES
# ===========================================
echo ""
echo "--- Cache Clear ---"
php artisan optimize:clear 2>/dev/null && echo "✓ Laravel caches cleared" || echo "⚠ Cache clear skipped (non-fatal)"

# ===========================================
# 5. TYPESCRIPT PRE-FLIGHT CHECK
# ===========================================
echo ""
echo "--- TypeScript Check ---"
if command -v yarn &>/dev/null; then
    yarn tsc --noEmit 2>&1 | head -20 || {
        echo "❌ TypeScript validation failed — aborting build"
        exit 1
    }
    echo "✓ TypeScript check passed"
fi

# ===========================================
# 6. COMPILE FRONTEND ASSETS
# ===========================================
echo ""
echo "--- Frontend Build ---"
if command -v yarn &>/dev/null; then
    echo "Running yarn build:production (this may take 2-5 minutes)..."
    yarn build:production 2>&1 && echo "✓ Frontend assets compiled" || {
        echo "⚠ Frontend build failed — dashboard badges and widget will not render"
        echo "  Admin panel + cron + license system still work fine"
    }
else
    echo "⚠ yarn not found — skipping frontend build"
fi

echo ""
echo "=========================================="
echo "ModpackChecker build complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "  1. Deploy PHP files from repo (Chronicler)"
echo "  2. Restart: systemctl restart php8.3-fpm"
echo "  3. Test cron: php artisan modpackchecker:check"
echo ""
