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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MODE="dry-run"

BUILD_LOG_DAYS="${BUILD_LOG_DAYS:-90}"
UNREAL_LOG_DAYS="${UNREAL_LOG_DAYS:-30}"
CRASH_DAYS="${CRASH_DAYS:-90}"
MATERIAL_STATS_DAYS="${MATERIAL_STATS_DAYS:-30}"
SHADER_DEBUG_DAYS="${SHADER_DEBUG_DAYS:-14}"

usage() {
  cat <<USAGE
Usage: $(basename "$0") [--dry-run|--apply]

Prunes generated Agrarian Unreal build/debug logs according to
Docs/Ops/BuildLogRetentionPolicy.md.

Environment overrides:
  BUILD_LOG_DAYS=$BUILD_LOG_DAYS
  UNREAL_LOG_DAYS=$UNREAL_LOG_DAYS
  CRASH_DAYS=$CRASH_DAYS
  MATERIAL_STATS_DAYS=$MATERIAL_STATS_DAYS
  SHADER_DEBUG_DAYS=$SHADER_DEBUG_DAYS
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      MODE="dry-run"
      ;;
    --apply)
      MODE="apply"
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      usage >&2
      exit 2
      ;;
  esac
  shift
done

log() {
  printf '[%s] %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*"
}

prune_files() {
  local label="$1"
  local dir="$2"
  local days="$3"

  if [[ ! -d "$dir" ]]; then
    log "Skipping $label; directory not found: $dir"
    return
  fi

  log "$label: files older than $days days in $dir"
  if [[ "$MODE" == "dry-run" ]]; then
    find "$dir" -type f -mtime +"$days" -print
  else
    find "$dir" -type f -mtime +"$days" -print -delete
  fi
}

prune_empty_dirs() {
  local dir="$1"
  if [[ ! -d "$dir" ]]; then
    return
  fi

  if [[ "$MODE" == "dry-run" ]]; then
    find "$dir" -mindepth 1 -type d -empty -print
  else
    find "$dir" -mindepth 1 -type d -empty -print -delete
  fi
}

log "Agrarian build log retention prune starting in $MODE mode"
log "Project root: $PROJECT_ROOT"

prune_files "Build/package logs" "$PROJECT_ROOT/Saved/BuildLogs" "$BUILD_LOG_DAYS"
prune_files "Unreal/editor/runtime logs" "$PROJECT_ROOT/Saved/Logs" "$UNREAL_LOG_DAYS"
prune_files "Crash reports" "$PROJECT_ROOT/Saved/Crashes" "$CRASH_DAYS"
prune_files "Material stats" "$PROJECT_ROOT/Saved/MaterialStats" "$MATERIAL_STATS_DAYS"
prune_files "Shader output" "$PROJECT_ROOT/Saved/Shaders" "$SHADER_DEBUG_DAYS"
prune_files "Shader debug info" "$PROJECT_ROOT/Saved/ShaderDebugInfo" "$SHADER_DEBUG_DAYS"

prune_empty_dirs "$PROJECT_ROOT/Saved/BuildLogs"
prune_empty_dirs "$PROJECT_ROOT/Saved/Logs"
prune_empty_dirs "$PROJECT_ROOT/Saved/Crashes"
prune_empty_dirs "$PROJECT_ROOT/Saved/MaterialStats"
prune_empty_dirs "$PROJECT_ROOT/Saved/Shaders"
prune_empty_dirs "$PROJECT_ROOT/Saved/ShaderDebugInfo"

log "Agrarian build log retention prune finished in $MODE mode"
