#!/usr/bin/env bash
set -u

echo "SafeDisk AI approved cleanup beta"
echo "This helper moves approved items to Trash only."
echo "It does not permanently delete files and it refuses paths outside your home folder."
echo

timestamp="$(date +%Y%m%d-%H%M%S)"
log="$HOME/Desktop/safedisk-approved-cleanup-$timestamp.txt"
plan="${1:-}"

find_latest_plan() {
  find "$HOME/Downloads" "$HOME/Desktop" -maxdepth 1 -type f -name "safedisk-approved-cleanup-*.json" 2>/dev/null |
    sort |
    tail -1
}

if [ -z "$plan" ]; then
  plan="$(find_latest_plan)"
fi

if [ -z "$plan" ] || [ ! -f "$plan" ]; then
  echo "Drag a safedisk-approved-cleanup-*.json file into this window, then press Enter:"
  read -r plan
fi

if [ ! -f "$plan" ]; then
  echo "Plan file not found: $plan"
  read -r -p "Press Enter to close this window."
  exit 1
fi

extract_items() {
  jxa_file="$(mktemp "${TMPDIR:-/tmp}/safedisk-plan-parse.XXXXXX.js")"
  cat > "$jxa_file" <<'JXA'
function run(argv) {
const app = Application.currentApplication();
app.includeStandardAdditions = true;
const path = argv[0];
const text = app.read(Path(path));
const plan = JSON.parse(text);
if (plan.generated_by !== "SafeDisk AI" || plan.plan_type !== "approved_cleanup_beta") {
  throw new Error("This is not a SafeDisk approved cleanup beta plan.");
}
const items = Array.isArray(plan.items) ? plan.items : [];
const lines = [];
for (const item of items) {
  const action = String(item.action || "");
  const pathValue = String(item.path || "");
  const category = String(item.category || "");
  const size = String(item.size_gb || "");
  const reason = String(item.reason || "").replace(/\s+/g, " ");
  lines.push([action, pathValue, category, size, reason].join("\t"));
}
return lines.join("\n");
}
JXA
  osascript -l JavaScript "$jxa_file" "$plan"
  status=$?
  rm -f "$jxa_file"
  return "$status"
}

items="$(extract_items 2>/tmp/safedisk-plan-error.txt)"
if [ $? -ne 0 ]; then
  echo "Could not read the cleanup plan."
  cat /tmp/safedisk-plan-error.txt
  read -r -p "Press Enter to close this window."
  exit 1
fi

if [ -z "$items" ]; then
  echo "This plan has no approved Trash actions."
  read -r -p "Press Enter to close this window."
  exit 0
fi

{
  echo "# SafeDisk Approved Cleanup Log"
  echo "Generated: $(date)"
  echo "Plan: $plan"
  echo
  echo "This helper moves approved items to Trash only."
  echo
} > "$log"

echo "Plan:"
echo "$items" | awk -F '\t' '{printf "- %s: %s GB at %s\n  %s\n", $3, $4, $2, $5}'
echo
echo "Type MOVE TO TRASH to continue. Anything else cancels."
read -r confirm

if [ "$confirm" != "MOVE TO TRASH" ]; then
  echo "Canceled."
  echo "Canceled by user." >> "$log"
  read -r -p "Press Enter to close this window."
  exit 0
fi

expand_path() {
  value="$1"
  case "$value" in
    "~/"*) printf "%s/%s" "$HOME" "${value#~/}" ;;
    "\$HOME/"*) printf "%s/%s" "$HOME" "${value#\$HOME/}" ;;
    *) printf "%s" "$value" ;;
  esac
}

refuse_path() {
  target="$1"
  case "$target" in
    "$HOME" | "$HOME/" | "/" | "/Users" | "/Users/" | "" ) return 0 ;;
  esac
  case "$target" in
    "$HOME"/*) ;;
    *) return 0 ;;
  esac
  case "$target" in
    *".."*) return 0 ;;
  esac
  return 1
}

trash_one() {
  target="$1"
  if [ ! -e "$target" ]; then
    echo "Missing, skipped: $target" | tee -a "$log"
    return 0
  fi
  if refuse_path "$target"; then
    echo "Refused unsafe path: $target" | tee -a "$log"
    return 0
  fi
  SAFEDISK_TARGET="$target" osascript <<'APPLESCRIPT' >/dev/null
set targetPath to system attribute "SAFEDISK_TARGET"
tell application "Finder"
  delete POSIX file targetPath
end tell
APPLESCRIPT
  if [ $? -eq 0 ]; then
    echo "Moved to Trash: $target" | tee -a "$log"
  else
    echo "Could not move to Trash: $target" | tee -a "$log"
  fi
}

printf "%s\n" "$items" | while IFS="$(printf '\t')" read -r action raw_path category size_gb reason; do
  target="$(expand_path "$raw_path")"
  case "$action" in
    trash_path)
      trash_one "$target"
      ;;
    trash_children)
      if [ ! -d "$target" ]; then
        echo "Missing directory, skipped: $target" | tee -a "$log"
        continue
      fi
      if refuse_path "$target"; then
        echo "Refused unsafe directory: $target" | tee -a "$log"
        continue
      fi
      found=0
      while IFS= read -r child; do
        found=1
        trash_one "$child"
      done < <(find "$target" -mindepth 1 -maxdepth 1 -print 2>/dev/null)
      if [ "$found" -eq 0 ]; then
        echo "Directory already empty: $target" | tee -a "$log"
      fi
      ;;
    *)
      echo "Unsupported action, skipped: $action $target" | tee -a "$log"
      ;;
  esac
done

echo
echo "Done. Cleanup log:"
echo "$log"
echo
echo "Open apps and projects before emptying Trash. Empty Trash only after everything still works."

if command -v open >/dev/null 2>&1; then
  open -R "$log" >/dev/null 2>&1 || true
fi

read -r -p "Press Enter to close this window."
