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

DIR="${1:-.}"
JOBS="${JOBS:-$(command -v nproc >/dev/null 2>&1 && nproc || echo 4)}"
PNG_QUALITY="${PNG_QUALITY:-30-70}"
WEBP_QUALITY="${WEBP_QUALITY:-80}"
CONVERT_TO_WEBP="${CONVERT_TO_WEBP:-1}"
FORCE="${FORCE:-0}"

export PNG_QUALITY WEBP_QUALITY

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

  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")
  before=$(get_size "$file")

  case "$mime" in
    image/jpeg)
      if [ "$CONVERT_TO_WEBP" = "1" ] && command -v cwebp >/dev/null 2>&1; then
        tmp="$dir/.${base%.jpg}.webp.$$"
        if cwebp -q "$WEBP_QUALITY" -m 6 "$file" -o "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$FORCE" = "1" ] || [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$dir/${base%.jpg}.webp"
            rm -f "$file"
            echo "OK|webp|$before|$after|$dir/${base%.jpg}.webp"
          else
            rm -f "$tmp"
            echo "SKIP|webp|$before|$before|$file"
          fi
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|webp|$before|$before|$file"
        fi
      elif command -v jpegoptim >/dev/null 2>&1; then
        if jpegoptim --strip-all --preserve "$file" >/dev/null 2>&1; then
          after=$(get_size "$file")
          if [ "$after" -lt "$before" ]; then
            echo "OK|jpeg|$before|$after|$file"
          else
            echo "SKIP|jpeg|$before|$after|$file"
          fi
        else
          echo "FAIL|jpeg|$before|$before|$file"
        fi
      elif command -v magick >/dev/null 2>&1; then
        tmp="$dir/.${base}.tmp.$$"
        if magick "$file" -strip "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$FORCE" = "1" ] || [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$file"
            echo "OK|jpeg|$before|$after|$file"
          else
            rm -f "$tmp"
            echo "SKIP|jpeg|$before|$after|$file"
          fi
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|jpeg|$before|$before|$file"
        fi
      else
        echo "SKIP|jpeg|$before|$before|$file"
      fi
      ;;
    image/png)
      if [ "$CONVERT_TO_WEBP" = "1" ] && command -v cwebp >/dev/null 2>&1; then
        tmp="$dir/.${base%.png}.webp.$$"
        if cwebp -q "$WEBP_QUALITY" -m 6 "$file" -o "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$FORCE" = "1" ] || [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$dir/${base%.png}.webp"
            rm -f "$file"
            echo "OK|webp|$before|$after|$dir/${base%.png}.webp"
          else
            rm -f "$tmp"
            echo "SKIP|webp|$before|$before|$file"
          fi
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|webp|$before|$before|$file"
        fi
      elif command -v optipng >/dev/null 2>&1; then
        tmp="$dir/.${base}.tmp.$$"
        if cp -f "$file" "$tmp" && optipng -o3 -strip all "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$file"
            echo "OK|png|$before|$after|$file"
          else
            rm -f "$tmp"
            echo "SKIP|png|$before|$after|$file"
          fi
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|png|$before|$before|$file"
        fi
      elif command -v pngquant >/dev/null 2>&1; then
        tmp="$dir/.${base}.tmp.$$"
        if pngquant --force --skip-if-larger --output "$tmp" --quality "$PNG_QUALITY" --strip -- "$file" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$file"
            echo "OK|png|$before|$after|$file"
          else
            rm -f "$tmp"
            echo "SKIP|png|$before|$after|$file"
          fi
        else
          code=$?
          rm -f "$tmp" 2>/dev/null || true
          if [ "$code" -eq 98 ] || [ "$code" -eq 99 ]; then
            echo "SKIP|png|$before|$before|$file"
          else
            echo "FAIL|png|$before|$before|$file"
          fi
        fi
      elif command -v magick >/dev/null 2>&1; then
        tmp="$dir/.${base}.tmp.$$"
        if magick "$file" -strip "$tmp" >/dev/null 2>&1; then
          after=$(get_size "$tmp")
          if [ "$FORCE" = "1" ] || [ "$after" -lt "$before" ]; then
            mv -f "$tmp" "$file"
            echo "OK|png|$before|$after|$file"
          else
            rm -f "$tmp"
            echo "SKIP|png|$before|$after|$file"
          fi
        else
          rm -f "$tmp" 2>/dev/null || true
          echo "FAIL|png|$before|$before|$file"
        fi
      else
        echo "SKIP|png|$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 "done. total=$total success=$ok skip=$skip fail=$fail jobs=$JOBS"
