#!/bin/bash
set -euo pipefail

# ── Config ────────────────────────────────────────────────────────────────────
INPUT_DIR="./paperless-download"
OUTPUT_DIR="./paperless-flat"
# ─────────────────────────────────────────────────────────────────────────────

mkdir -p "$OUTPUT_DIR"

MOVED=0
SKIPPED=0

while IFS= read -r -d '' FILE; do
  BASENAME=$(basename "$FILE")

  # Strip leading date prefix: "YYYY-MM-DD " → ""
  NEWNAME=$(echo "$BASENAME" | sed -E 's/^[0-9]{4}-[0-9]{2}-[0-9]{2} //')

  DEST="$OUTPUT_DIR/$NEWNAME"

  if [ -e "$DEST" ]; then
    echo "Skipping (already exists): $NEWNAME" >&2
    SKIPPED=$((SKIPPED + 1))
    continue
  fi

  cp "$FILE" "$DEST"
  MOVED=$((MOVED + 1))
done < <(find "$INPUT_DIR" -mindepth 2 -name "*.pdf" -print0)

echo "Done. Copied $MOVED files to $OUTPUT_DIR/ ($SKIPPED skipped as duplicates)."
