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

DIR="${1:-.}"
OUT_DIR="${2:-${DIR}/webp}"
JOBS="${JOBS:-$(command -v nproc >/dev/null 2>&1 && nproc || echo 4)}"
WEBP_QUALITY="${WEBP_QUALITY:-80}"

export WEBP_QUALITY OUT_DIR DIR

mkdir -p "$OUT_DIR"

process_one() {
  local file="$1"
  local mime dir base rel_path out_file tmp before after

  get_size() {
    stat -c%s "$1" 2>/dev/null || stat -f%z "$1" 2>/dev/null
  }

  mime=$(file --mime-type -b "$file")
  dir=$(dirname "$file")
  base=$(basename "$file")

  # 計算相對路徑，保持目錄結構
  rel_path="${file#$DIR/}"
  out_file="$OUT_DIR/${rel_path%.png}.webp"
  out_dir=$(dirname "$out_file")

  mkdir -p "$out_dir"

  before=$(get_size "$file")
  tmp="$out_dir/.${base}.tmp.$$"

  case "$mime" in
    image/jpeg|image/png)
      if command -v cwebp >/dev/null 2>&1; then
        if cwebp -q "$WEBP_QUALITY" -m 6 "$file" -o "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          mv -f "$tmp" "$out_file"
          echo "OK|webp|$before|$after|$out_file"
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|webp|$before|$before|$file"
        fi
      elif command -v magick >/dev/null 2>&1; then
        if magick "$file" -quality "$WEBP_QUALITY" "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          mv -f "$tmp" "$out_file"
          echo "OK|webp|$before|$after|$out_file"
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|webp|$before|$before|$file"
        fi
      else
        echo "SKIP|no-tool|$before|$before|$file"
      fi
      ;;
    *)
      echo "SKIP|other|$before|$before|$file"
      ;;
  esac
}

export -f process_one

find "$DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) -print0 |
xargs -0 -n1 -P "$JOBS" bash -c 'process_one "$1"' _ |
tee /tmp/compress_images_result.log

LOG_FILE="/tmp/compress_images_result.log"
ok=$(grep -c '^OK|' "$LOG_FILE" || true)
skip=$(grep -c '^SKIP|' "$LOG_FILE" || true)
fail=$(grep -c '^FAIL|' "$LOG_FILE" || true)
total=$((ok + skip + fail))

echo ""
echo "========================================"
echo "完成！輸出目錄：$OUT_DIR"
echo "總數：$total 成功：$ok 跳過：$skip 失敗：$fail"
echo "========================================"
