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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
APPLY="false"
OLDER_THAN_DAYS="1"
ARCHIVE_TAG_DEFAULT="$(date +%Y%m%d_%H%M%S)"
ARCHIVE_TAG="${ARCHIVE_TAG_DEFAULT}"

PATTERN_PATHS=(
  "logs/e2e-automation/run_*.log"
  "logs/e2e-automation/report_*.md"
  "logs/prd-review/review_*.md"
  "logs/prd-review/claude_apply_*.md"
  "logs/prd-review/execution_report_*.md"
  "logs/prd-review/optimization_report_*.md"
)

usage() {
  cat <<'EOF'
Usage:
  ./scripts/ci/archive-logs.sh [--apply] [--older-than-days N] [--archive-tag TAG]

Options:
  --apply              Execute archive move. Without this flag, script runs in dry-run mode.
  --older-than-days N  Archive files older than N days. Default: 1
  --archive-tag TAG    Archive subdir tag under logs/archive/. Default: timestamp
  -h, --help           Show help

Examples:
  ./scripts/ci/archive-logs.sh
  ./scripts/ci/archive-logs.sh --apply
  ./scripts/ci/archive-logs.sh --apply --older-than-days 2 --archive-tag weekly_20260323
EOF
}

log() { echo "[archive-logs] $*"; }

run_cmd() {
  if [[ "${APPLY}" == "true" ]]; then
    "$@"
  else
    log "DRY-RUN: $*"
  fi
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --apply)
      APPLY="true"
      shift
      ;;
    --older-than-days)
      OLDER_THAN_DAYS="${2:-}"
      shift 2
      ;;
    --archive-tag)
      ARCHIVE_TAG="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if ! [[ "${OLDER_THAN_DAYS}" =~ ^[0-9]+$ ]]; then
  echo "Invalid --older-than-days: ${OLDER_THAN_DAYS}" >&2
  exit 1
fi

ARCHIVE_DIR="${ROOT_DIR}/logs/archive/${ARCHIVE_TAG}"
CUTOFF_EPOCH="$(date -d "${OLDER_THAN_DAYS} days ago" +%s)"

log "root=${ROOT_DIR}"
log "apply=${APPLY} older_than_days=${OLDER_THAN_DAYS} archive_dir=${ARCHIVE_DIR}"
log "cutoff=$(date -d "@${CUTOFF_EPOCH}" '+%Y-%m-%d %H:%M:%S')"

if [[ "${APPLY}" == "true" ]]; then
  mkdir -p "${ARCHIVE_DIR}"
fi

shopt -s nullglob
moved_count=0
for pattern in "${PATTERN_PATHS[@]}"; do
  for abs in "${ROOT_DIR}"/${pattern}; do
    [[ -f "${abs}" ]] || continue

    mtime_epoch="$(stat -c %Y "${abs}")"
    if [[ "${mtime_epoch}" -ge "${CUTOFF_EPOCH}" ]]; then
      continue
    fi

    rel="${abs#${ROOT_DIR}/}"
    dest="${ARCHIVE_DIR}/${rel}"
    run_cmd mkdir -p "$(dirname "${dest}")"
    run_cmd mv "${abs}" "${dest}"
    log "ARCHIVE ${rel} -> ${dest}"
    moved_count=$((moved_count + 1))
  done
done
shopt -u nullglob

log "done: archived=${moved_count}"
if [[ "${APPLY}" != "true" ]]; then
  log "dry-run completed. Use --apply to execute."
fi
