#!/usr/bin/env bash
# SWLGUISIGN — Local build script (macOS ARM / Intel)
# Usage:
#   ./install.sh                        → build .dmg (with obfuscation)
#   ./install.sh --no-obf               → build .dmg (skip obfuscation)
#   ./install.sh --run                  → dev server only (php artisan native:run)
#   ./install.sh --php /path/to/php-8.4 → specify PHP path
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

OBF=true
RUN=false
PHP_PATH=""
while [[ $# -gt 0 ]]; do
  case $1 in
    --no-obf) OBF=false; shift ;;
    --run)    RUN=true;  shift ;;
    --php)    PHP_PATH="${2:-}"; shift 2 ;;
    --php=*)  PHP_PATH="${1#*=}"; shift ;;
    *)        shift ;;
  esac
done

# ── colours ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
info()    { echo -e "${CYAN}▶ $*${NC}"; }
success() { echo -e "${GREEN}✔ $*${NC}"; }
warn()    { echo -e "${YELLOW}⚠ $*${NC}"; }
die()     { echo -e "${RED}✘ $*${NC}" >&2; exit 1; }

echo ""
echo -e "${CYAN}╔══════════════════════════════════════╗"
echo -e "║       SWLGUISIGN — Build Script      ║"
echo -e "╚══════════════════════════════════════╝${NC}"
echo ""

# ── 1. Prerequisites ──────────────────────────────────────────────────────────
info "Checking prerequisites..."

check_version() {
  local name="$1" cmd="$2" min="$3"
  if ! command -v "$cmd" &>/dev/null; then
    die "$name not found. Install it and retry.\n  macOS: brew install $cmd"
  fi
  success "$name found: $($cmd --version 2>&1 | head -1)"
}

# PHP 8.4+ — use --php if given, otherwise auto-detect from PATH
PHP=""
if [[ -n "$PHP_PATH" ]]; then
  if [[ -x "$PHP_PATH/php" ]]; then
    PHP="$PHP_PATH/php"
  elif [[ -x "$PHP_PATH" ]]; then
    PHP="$PHP_PATH"
  else
    die "php not found at: $PHP_PATH"
  fi
else
  command -v php &>/dev/null || die "PHP not found. Install: brew install php@8.4\n  Or specify one: ./install.sh --php /opt/homebrew/opt/php@8.4/bin"
  PHP="$(command -v php)"
fi

PHP_VER=$("$PHP" -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
if [[ "$(echo "$PHP_VER 8.3" | awk '{print ($1 < $2)}')" == "1" ]]; then
  die "PHP 8.3+ required, found $PHP_VER at $PHP\n  Specify another: ./install.sh --php /opt/homebrew/opt/php@8.4/bin"
fi
success "PHP $PHP_VER found at $PHP"

# Prepend PHP dir to PATH so all child processes (composer, node, electron-builder)
# that call a bare `php` resolve to the same binary
PHP_DIR="$(cd "$(dirname "$PHP")" && pwd)"
export PATH="$PHP_DIR:$PATH"

# Node 22+
if ! command -v node &>/dev/null; then
  die "Node.js not found. Install: brew install node"
fi
NODE_VER=$(node -e 'process.stdout.write(process.version.slice(1))')
NODE_MAJOR=$(echo "$NODE_VER" | cut -d. -f1)
if [[ "$NODE_MAJOR" -lt 22 ]]; then
  die "Node 22+ required, found $NODE_VER"
fi
success "Node $NODE_VER found"

# Composer — invoke through the selected PHP so its shebang can't pick another one
if ! command -v composer &>/dev/null; then
  die "Composer not found. Install: brew install composer"
fi
COMPOSER_BIN="$(command -v composer)"
COMPOSER_HEAD="$(head -c 200 "$COMPOSER_BIN" 2>/dev/null || true)"
if [[ "$COMPOSER_HEAD" == *php* ]]; then
  composer_run() { "$PHP" "$COMPOSER_BIN" "$@"; }
else
  composer_run() { "$COMPOSER_BIN" "$@"; }
fi
success "Composer $(composer_run --version --no-ansi 2>/dev/null | awk '{print $3}') found at $COMPOSER_BIN"

echo ""

# ── Dev mode only ─────────────────────────────────────────────────────────────
if $RUN; then
  info "Installing dependencies for dev server..."
  composer_run install --no-interaction 2>&1 | tail -3
  npm install --silent
  [[ ! -f .env ]] && cp .env.example .env && "$PHP" artisan key:generate --quiet
  echo ""
  info "Starting native dev server (Ctrl+C to stop)..."
  exec "$PHP" artisan native:run
fi

# ── 2. Composer install ───────────────────────────────────────────────────────
info "Installing Composer dependencies (--no-dev)..."
composer_run install --no-dev --optimize-autoloader --no-interaction 2>&1 | tail -5
success "Composer done"

# ── 3. NPM install ────────────────────────────────────────────────────────────
info "Installing NPM dependencies..."
npm install --silent
success "NPM done"

# ── 4. Environment ────────────────────────────────────────────────────────────
if [[ ! -f .env ]]; then
  info "Creating .env from .env.example..."
  cp .env.example .env
  success ".env created"
else
  warn ".env already exists — keeping it"
fi

# APP_KEY is checked separately: an existing .env may still have an empty key,
# and the build bakes .env straight into resources/build/app/.env, so the
# installed app dies with MissingAppKeyException. --force is required because
# APP_ENV=production makes key:generate ask for confirmation.
if grep -q '^APP_KEY=base64:' .env; then
  success "APP_KEY present"
else
  info "Generating APP_KEY..."
  "$PHP" artisan key:generate --force || die "key:generate failed"
  grep -q '^APP_KEY=base64:' .env || die "APP_KEY still empty in .env"
  success "APP_KEY generated"
fi

# ── 5. Obfuscation (--obf only) ───────────────────────────────────────────────
if $OBF; then
  info "Obfuscating PHP source with yakpro-po..."
  OBF_DIR="app_yak"
  OBF_OUT="$OBF_DIR/yakpro-po/obfuscated"

  # -d memory_limit=1024M: yakpro-po holds a rename map for the whole codebase
  # in memory at once, and a stock php.ini's 128M default isn't enough for
  # this app -- without this it dies with "Allowed memory size exhausted"
  # partway through (harmless here since `set -e` stops the script before
  # app/ gets touched below, but the build fails).
  "$PHP" -d memory_limit=1024M tools/yakpro-po/yakpro-po.php app/ -o "$OBF_DIR/"

  # Fallback: copy any file yakpro-po skipped
  find app -type f | while read -r src; do
    rel="${src#app/}"
    dest="$OBF_OUT/$rel"
    if [[ ! -f "$dest" ]]; then
      mkdir -p "$(dirname "$dest")"
      cp "$src" "$dest"
      echo "  fallback: $rel"
    fi
  done

  rm -rf app/
  mv "$OBF_OUT" app/
  rm -rf "$OBF_DIR"
  success "Obfuscation complete"
else
  warn "Skipping obfuscation (--no-obf flag set)"
fi

# ── 6. Build Vite assets ──────────────────────────────────────────────────────
info "Building frontend assets..."
npm run build 2>&1 | tail -8
success "Assets built"

# ── 7. Pre-extract PHP binary ─────────────────────────────────────────────────
info "Extracting PHP binary for Electron build..."

# Detect arch
ARCH=$(uname -m)
if [[ "$ARCH" == "arm64" ]]; then
  PHP_ZIP="vendor/nativephp/php-bin/bin/mac/arm64/php-8.4.zip"
  NATIVE_ARCH="arm64"
else
  PHP_ZIP="vendor/nativephp/php-bin/bin/mac/x64/php-8.4.zip"
  NATIVE_ARCH="x64"
fi

PHP_DEST="vendor/nativephp/desktop/resources/build/php"
mkdir -p "$PHP_DEST"
unzip -o "$PHP_ZIP" -d "$PHP_DEST" >/dev/null
chmod +x "$PHP_DEST/php"
"$PHP_DEST/php" --version | head -1
success "PHP binary extracted ($ARCH)"

# ── 8. Patch electron-builder.mjs (no-op beforePack) ─────────────────────────
info "Patching electron-builder.mjs..."
node scripts/patch-electron-builder.mjs
success "electron-builder.mjs patched"

# ── 9. Build .dmg ─────────────────────────────────────────────────────────────
echo ""
info "Building macOS .dmg ($NATIVE_ARCH)..."
echo ""

NATIVEPHP_APP_ID=th.co.spn.guisign \
NATIVEPHP_APP_VERSION=1.0.0 \
NATIVEPHP_APP_AUTHOR=SPN \
ELECTRON_SKIP_BINARY_DOWNLOAD=1 \
CHROMEDRIVER_SKIP_DOWNLOAD=1 \
PUPPETEER_SKIP_DOWNLOAD=1 \
  "$PHP" artisan native:build mac "$NATIVE_ARCH" --no-interaction

echo ""
# ── 10. Output ────────────────────────────────────────────────────────────────
DMG=$(find nativephp/electron/dist -name "*.dmg" 2>/dev/null | head -1)
if [[ -n "$DMG" ]]; then
  SIZE=$(du -sh "$DMG" | cut -f1)
  success "Build complete!"
  echo ""
  echo -e "  ${GREEN}Output:${NC} $DMG  (${SIZE})"
  echo ""
else
  die "Build finished but no .dmg found in nativephp/electron/dist/"
fi
