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

# ── File Processor Template ──
# Handles: input resolution, validation, file discovery, iteration, summary.
# The task only needs to define: EXTENSIONS and process_file().
#
# Slots to fill before this template:
#   EXTENSIONS="flac|wav|ogg"          — pipe-separated list of file extensions to match
#   process_file() { ... }            — receives $1 (input path), returns 0 on success

# ── Input resolution ──
TARGET="${1:-${INPUT_FILE_PATH:-}}"

if [[ -z "$TARGET" ]]; then
  echo "Error: No file or directory path provided" >&2
  exit 1
fi

if [[ ! -e "$TARGET" ]]; then
  echo "Error: Path does not exist: $TARGET" >&2
  exit 1
fi

# ── Execution ──
converted=0
failed=0

if [[ -f "$TARGET" ]]; then
  if process_file "$TARGET"; then
    converted=$((converted + 1))
  else
    failed=$((failed + 1))
  fi
elif [[ -d "$TARGET" ]]; then
  while IFS= read -r -d '' file; do
    if process_file "$file"; then
      converted=$((converted + 1))
    else
      failed=$((failed + 1))
    fi
  done < <(find "$TARGET" -type f -regextype posix-extended -iregex ".*\.($EXTENSIONS)" -print0 | sort -z)

  if [[ $converted -eq 0 && $failed -eq 0 ]]; then
    echo "No matching files found in: $TARGET"
    exit 0
  fi
else
  echo "Error: Not a file or directory: $TARGET" >&2
  exit 1
fi

echo ""
echo "Summary: $converted processed, $failed failed"
