#!/usr/bin/env bash
# build_product_cutouts.sh
# Full pipeline: DB-sourced images → rembg → normalize → DB sync
#
# Usage:
#   bash scripts/build_product_cutouts.sh            # full run
#   bash scripts/build_product_cutouts.sh --dry-run  # preview sync only, no DB writes
#
# Steps:
#   1. Export primary product image paths from DB
#   2. Remove backgrounds with rembg (skip already-processed files)
#   3. Normalize each cutout canvas (crop, scale, center on 1000×1000)
#   4. Sync cutout paths into products.cutout_image_path

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
STORAGE_PUBLIC="$PROJECT_DIR/storage/app/public"
SOURCE_DIR="$STORAGE_PUBLIC/products"
CUTOUT_DIR="$STORAGE_PUBLIC/products-cutout-ai"
IMAGE_LIST="/tmp/poiana-db-product-images.txt"
CUTOUT_LIST="/tmp/poiana-db-cutout-images.txt"

DRY_RUN_FLAG=""
if [[ "${1:-}" == "--dry-run" ]]; then
    DRY_RUN_FLAG="--dry-run"
fi

cd "$PROJECT_DIR"

# ─── Step 1: Export primary product image paths from DB ───────────────────────
echo "=== Step 1: Exporting primary product image paths from DB ==="

php artisan tinker --execute="
App\Models\ProductImage::where('is_primary', true)->pluck('path')->each(fn(\$p) => print(\$p . PHP_EOL));
" 2>/dev/null \
  | sed "s|^/products/|${SOURCE_DIR}/|" \
  | grep -v '^$' \
  > "$IMAGE_LIST"

# Filter to files that actually exist on disk
filtered_list="/tmp/poiana-db-product-images-existing.txt"
while IFS= read -r path; do
    [[ -f "$path" ]] && echo "$path"
done < "$IMAGE_LIST" > "$filtered_list"
mv "$filtered_list" "$IMAGE_LIST"

total=$(wc -l < "$IMAGE_LIST")
echo "Found $total primary product images on disk"
echo ""

# ─── Step 2: Remove backgrounds ───────────────────────────────────────────────
echo "=== Step 2: Removing backgrounds (rembg, skip existing) ==="

python3 "$SCRIPT_DIR/remove_background_rembg.py" \
    --list-file "$IMAGE_LIST" \
    --source "$SOURCE_DIR" \
    --output "$CUTOUT_DIR" \
    --manifest "$PROJECT_DIR/storage/app/product-cutouts-ai-manifest.json" \
    --model birefnet-general \
    --model-dir "$PROJECT_DIR/storage/app/rembg-models" \
    --skip-existing \
    --no-alpha-matting

echo ""

# ─── Step 3: Build cutout path list and normalize ─────────────────────────────
echo "=== Step 3: Normalizing cutout canvas (crop + scale + center) ==="

> "$CUTOUT_LIST"
while IFS= read -r src; do
    # Convert source path → cutout path, changing extension to .png
    relative="${src#${SOURCE_DIR}/}"
    base="${relative%.*}"
    cutout="${CUTOUT_DIR}/${base}.png"
    if [[ -f "$cutout" ]]; then
        echo "$cutout"
    else
        echo "  [WARN] No cutout found for: $src" >&2
    fi
done < "$IMAGE_LIST" > "$CUTOUT_LIST"

normalize_count=$(grep -c . "$CUTOUT_LIST" || true)
echo "Normalizing $normalize_count cutout images..."

# Build --image arguments for the normalize script
image_args=()
while IFS= read -r path; do
    image_args+=(--image "$path")
done < "$CUTOUT_LIST"

python3 "$SCRIPT_DIR/normalize_cutout_canvas.py" \
    --source "$CUTOUT_DIR" \
    --output "$CUTOUT_DIR" \
    --manifest "$PROJECT_DIR/storage/app/product-cutouts-ai-normalized-manifest.json" \
    "${image_args[@]}"

echo ""

# ─── Step 4: Sync cutout paths into DB ────────────────────────────────────────
echo "=== Step 4: Syncing cutout paths to database $([[ -n $DRY_RUN_FLAG ]] && echo '(DRY RUN)') ==="
php artisan products:sync-cutouts $DRY_RUN_FLAG

echo ""
echo "=== Done ==="
