#!/usr/bin/env bash
# Survey /mnt/DataDisk media library for pending organization work.
#   bash organize_pending.sh           # dry-run: report only (safe)
#   bash organize_pending.sh --apply   # actually perform the moves
# Rules:
#   1) Loose mp4 in 待处理 with no same-name .aria2 -> own folder (basename, no ext).
#   2) 待处理 subfolder holding same-name mp4 + .funscript -> move to 已完成.
set -u

BASE="/mnt/DataDisk"
PENDING="$BASE/待处理"
DONE="$BASE/已完成"
APPLY=0
[ "${1:-}" = "--apply" ] && APPLY=1

echo "== aria2 leftovers (incomplete downloads; 0 = all done) =="
find "$BASE" -name "*.aria2" | wc -l

echo
echo "== Rule 1: loose mp4 in $PENDING =="
while IFS= read -r f; do
    [ -n "$f" ] || continue
    base="${f%.mp4}"
    if [ -f "$base.aria2" ]; then
        echo "SKIP (still downloading): $(basename "$f")"
        continue
    fi
    target="$PENDING/$(basename "$base")"
    if [ -e "$target" ]; then
        echo "SKIP (folder already exists): $(basename "$f")"
        continue
    fi
    echo "FOLD: $(basename "$f") -> $target/"
    if [ "$APPLY" = 1 ]; then
        mkdir -p "$target"
        mv "$f" "$target/"
        echo "  moved."
    fi
done < <(find "$PENDING" -maxdepth 1 -type f -name "*.mp4")

echo
echo "== Rule 2: pending subfolders with mp4 + funscript pair =="
for d in "$PENDING"/*/; do
    [ -d "$d" ] || continue
    mp4=$(find "$d" -maxdepth 1 -type f -name "*.mp4" | head -1)
    fs=$(find "$d" -maxdepth 1 -type f -iname "*.funscript" | head -1)
    if [ -n "$mp4" ] && [ -n "$fs" ]; then
        name=$(basename "$d")
        if [ -e "$DONE/$name" ]; then
            echo "CONFLICT (skip): $name already exists in $DONE"
            continue
        fi
        echo "COMPLETE: $name -> $DONE/"
        if [ "$APPLY" = 1 ]; then
            mv "$d" "$DONE/"
            echo "  moved."
        fi
    fi
done

echo
echo "== done (dry-run unless --apply was passed) =="
