#!/bin/sh
# AskClean Xcode Storage Audit
# Read-only: this script measures paths and lists simctl state. It deletes nothing.

set -u

audit_root=${ASKCLEAN_AUDIT_ROOT:-$HOME}

human_size() {
  target_path=$1
  display_path=$2
  if [ -e "$target_path" ]; then
    size_kb=$(du -sk "$target_path" 2>/dev/null | awk '{print $1}')
    if [ -n "${size_kb:-}" ]; then
      awk -v kb="$size_kb" -v path="$display_path" '
        BEGIN {
          if (kb >= 1073741824) printf "%8.2f TB  %s\n", kb / 1073741824, path
          else if (kb >= 1048576) printf "%8.2f GB  %s\n", kb / 1048576, path
          else if (kb >= 1024) printf "%8.2f MB  %s\n", kb / 1024, path
          else printf "%8.0f KB  %s\n", kb, path
        }
      '
      return
    fi
  fi
  printf "%11s  %s\n" "not found" "$display_path"
}

printf '%s\n' "AskClean Xcode Storage Audit (read-only)"
printf '%s\n' "Generated: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
printf '\n%s\n' "Developer directories"

human_size "$audit_root/Library/Developer/Xcode/DerivedData" "~/Library/Developer/Xcode/DerivedData"
human_size "$audit_root/Library/Developer/Xcode/Archives" "~/Library/Developer/Xcode/Archives"
human_size "$audit_root/Library/Developer/Xcode/iOS DeviceSupport" "~/Library/Developer/Xcode/iOS DeviceSupport"
human_size "$audit_root/Library/Developer/CoreSimulator/Devices" "~/Library/Developer/CoreSimulator/Devices"
human_size "$audit_root/Library/Developer/CoreSimulator/Caches" "~/Library/Developer/CoreSimulator/Caches"
human_size "$audit_root/Library/Caches/org.swift.swiftpm" "~/Library/Caches/org.swift.swiftpm"
human_size "$audit_root/Library/Caches/CocoaPods" "~/Library/Caches/CocoaPods"

printf '\n%s\n' "Active developer directory"
if command -v xcode-select >/dev/null 2>&1; then
  xcode-select -p 2>/dev/null || printf '%s\n' "Xcode command-line tools are not configured."
else
  printf '%s\n' "xcode-select is unavailable."
fi

printf '\n%s\n' "Installed simulator runtimes"
if command -v xcrun >/dev/null 2>&1 && xcrun simctl help >/dev/null 2>&1; then
  xcrun simctl list runtimes
  printf '\n%s\n' "Unavailable simulator devices"
  xcrun simctl list devices | awk '
    /-- / { section=$0 }
    /\(unavailable/ {
      if (section != last_section) {
        print section
        last_section=section
      }
      print
      found=1
    }
    END {
      if (!found) print "None reported by simctl."
    }
  '
else
  printf '%s\n' "simctl is unavailable. Install or select Xcode, then run this audit again."
fi

printf '\n%s\n' "No files were changed. Compare this output before and after one cleanup action."
