#!/usr/bin/env bash
set -euo pipefail

###############################################################################
# build-jpegli-apenchev.sh
# Baut apenchev's jpegli-Fork als WebAssembly OHNE SharedArrayBuffer
#
# Anleitung: https://github.com/apenchev/jpegli/
# Basierend auf libjxl/doc/building_wasm.md
###############################################################################

# Farben
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info()    { echo -e "${BLUE}[INFO]${NC} $*"; }
log_success() { echo -e "${GREEN}[✓]${NC} $*"; }
log_warn()    { echo -e "${YELLOW}[!]${NC} $*"; }
log_error()   { echo -e "${RED}[✗]${NC} $*" >&2; }

# Konfiguration
OPT="${OPT:-$HOME}"
EMSDK_DIR="$OPT/emsdk"
JPEGLI_SRC_DIR="$OPT/jpegli"

# Argumente
CLEAN_ONLY=false
for arg in "$@"; do
  case $arg in
    --clean) CLEAN_ONLY=true; shift ;;
    --help|-h)
      echo "Usage: $0 [--clean] [--help]"
      echo "  --clean  Nur Build-Verzeichnis löschen"
      exit 0 ;;
  esac
done

if [ "$CLEAN_ONLY" = true ]; then
  rm -rf "$JPEGLI_SRC_DIR/build-wasm32"
  log_success "Cleanup abgeschlossen"
  exit 0
fi

# === Build-Tools installieren ===
log_info "=== Installiere Build-Tools ==="
sudo apt update
sudo apt install -y cmake ninja-build pkgconf

# === Emscripten SDK ===
log_info "=== Emscripten SDK ==="
if [ ! -d "$EMSDK_DIR" ]; then
  log_info "Klone Emscripten SDK nach $EMSDK_DIR"
  git clone "https://github.com/emscripten-core/emsdk.git" "$EMSDK_DIR"
fi

cd "$EMSDK_DIR"
log_info "Installiere Emscripten latest"
./emsdk install latest
./emsdk activate latest
# shellcheck disable=SC1091
source "$EMSDK_DIR/emsdk_env.sh"
cd -

# === apenchev's jpegli klonen ===
log_info "=== Klone apenchev/jpegli ==="
if [ ! -d "$JPEGLI_SRC_DIR" ]; then
  git clone "https://github.com/apenchev/jpegli.git" "$JPEGLI_SRC_DIR"
else
  log_info "Verwende bestehendes Verzeichnis: $JPEGLI_SRC_DIR"
  cd "$JPEGLI_SRC_DIR"
  git pull --ff-only || true
  cd -
fi

cd "$JPEGLI_SRC_DIR"

# === Dependencies installieren ===
log_info "=== Installiere Dependencies ==="
./deps.sh

# === Emscripten Environment aktivieren ===
log_info "=== Aktiviere Emscripten Environment ==="
# shellcheck disable=SC1091
source "$EMSDK_DIR/emsdk_env.sh"

# === Build ===
log_info "=== Build jpegli (wasm32 + SIMD) ==="
BUILD_TARGET=wasm32 ENABLE_WASM_SIMD=1 SKIP_TEST=1 emconfigure ./ci.sh release

# === Verifikation ===
log_info "=== Verifikation ==="
JS_FILE="$JPEGLI_SRC_DIR/build-wasm32/tools/cjpegli.js"
WASM_FILE="$JPEGLI_SRC_DIR/build-wasm32/tools/cjpegli.wasm"

echo ""
echo "Output:"
echo "  JS:   $JS_FILE"
echo "  WASM: $WASM_FILE"
echo ""

if [ ! -f "$JS_FILE" ] || [ ! -f "$WASM_FILE" ]; then
  log_error "Build-Dateien nicht gefunden!"
  log_error "Erwartet in: $JPEGLI_SRC_DIR/build-wasm32/tools/"
  log_error "Tatsächlich vorhanden:"
  ls -la "$JPEGLI_SRC_DIR/build-wasm32/tools/" 2>/dev/null || true
  exit 1
fi

# Prüfe auf shared:true (das ist das Problem-Flag)
SHARED_COUNT=$(grep -c 'shared:true' "$JS_FILE" || true)
PTHREAD_COUNT=$(grep -c 'PThread' "$JS_FILE" || true)
EXPORT_COUNT=$(grep -c 'export default' "$JS_FILE" || true)

if [ "$SHARED_COUNT" -eq 0 ]; then
  log_success "✓ shared:true NICHT vorhanden (korrekt für Thunderbird)"
else
  log_error "✗ shared:true gefunden ($SHARED_COUNT Vorkommen)"
fi

if [ "$PTHREAD_COUNT" -eq 0 ]; then
  log_success "✓ Kein PThread-Code"
else
  log_error "✗ PThread-Code gefunden ($PTHREAD_COUNT Vorkommen)"
fi

if [ "$EXPORT_COUNT" -gt 0 ]; then
  log_success "✓ Module-Export vorhanden"
else
  log_warn "⚠ Kein Export gefunden — evtl. manuell hinzufügen"
fi

echo ""
log_info "Dateigrößen:"
ls -lh "$JS_FILE" "$WASM_FILE"

echo ""
if [ "$SHARED_COUNT" -gt 0 ] || [ "$PTHREAD_COUNT" -gt 0 ]; then
  log_error "Build hat Probleme! shared:true oder PThread-Code vorhanden."
  log_error "Das Modul wird in Thunderbird XPI nicht funktionieren."
  exit 1
else
  log_success "Build erfolgreich! Das Modul sollte in Thunderbird funktionieren."
  log_info "Kopiere cjpegli.js und cjpegli.wasm in deine Extension."
fi
