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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ARCHIVE_ROOT="${ROOT_DIR}/logs/archive"
OUTPUT_FILE="${ARCHIVE_ROOT}/README.md"
GENERATED_AT="$(date '+%Y-%m-%d %H:%M:%S %Z')"

fmt_epoch() {
  local epoch="$1"
  date -d "@${epoch}" '+%Y-%m-%d %H:%M:%S'
}

list_batches() {
  find "${ARCHIVE_ROOT}" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r
}

if [[ ! -d "${ARCHIVE_ROOT}" ]]; then
  mkdir -p "${ARCHIVE_ROOT}"
fi

{
  echo "# 日志归档索引"
  echo
  echo "本文件由 \`scripts/ci/update-log-archive-index.sh\` 自动生成。"
  echo
  echo "- 生成时间: ${GENERATED_AT}"
  echo "- 归档根目录: \`logs/archive/\`"
  echo

  mapfile -t batches < <(list_batches)
  if [[ "${#batches[@]}" -eq 0 ]]; then
    echo "当前没有可用归档批次。"
    exit 0
  fi

  echo "## 批次总览"
  echo
  echo "| 批次 | 文件数 | 体积 | 最早文件时间 | 最晚文件时间 |"
  echo "|---|---:|---:|---|---|"

  for batch in "${batches[@]}"; do
    batch_dir="${ARCHIVE_ROOT}/${batch}"
    file_count="$(find "${batch_dir}" -type f | wc -l)"
    size="$(du -sh "${batch_dir}" | awk '{print $1}')"

    if [[ "${file_count}" -eq 0 ]]; then
      earliest="-"
      latest="-"
    else
      read -r earliest_epoch latest_epoch < <(
        find "${batch_dir}" -type f -printf '%T@\n' | awk '
          NR == 1 { min = $1; max = $1 }
          { if ($1 < min) min = $1; if ($1 > max) max = $1 }
          END { printf "%d %d\n", min, max }
        '
      )
      earliest="$(fmt_epoch "${earliest_epoch}")"
      latest="$(fmt_epoch "${latest_epoch}")"
    fi

    echo "| \`${batch}\` | ${file_count} | ${size} | ${earliest} | ${latest} |"
  done

  echo
  echo "## 子系统明细"
  echo

  for batch in "${batches[@]}"; do
    batch_dir="${ARCHIVE_ROOT}/${batch}"
    logs_dir="${batch_dir}/logs"
    echo "### ${batch}"
    echo

    if [[ ! -d "${logs_dir}" ]]; then
      echo "_未发现 \`logs/\` 子目录_"
      echo
      continue
    fi

    echo "| 子系统目录 | 文件数 | 体积 |"
    echo "|---|---:|---:|"
    while IFS= read -r subdir; do
      sub_name="${subdir#${logs_dir}/}"
      sub_count="$(find "${subdir}" -type f | wc -l)"
      sub_size="$(du -sh "${subdir}" | awk '{print $1}')"
      echo "| \`${sub_name}\` | ${sub_count} | ${sub_size} |"
    done < <(find "${logs_dir}" -mindepth 1 -maxdepth 1 -type d | sort)
    echo
  done
} > "${OUTPUT_FILE}"

echo "[update-log-archive-index] generated ${OUTPUT_FILE}"
