#!/bin/bash
# Utility script to download files (with caching support).
# 导入函数方法：source download_utils.sh

safe_download_with_cache()
{
  local url="$1" filename="$2"
  # 优先从缓存路径复制文件
  local return_code=0
  if [[ "$CACHE_PATH" != "null" && -d "$CACHE_PATH" ]]; then
    local cached_file="$CACHE_PATH/$(basename "$url")"
    cached_file="$(realpath -m "$cached_file")" # 规范化路径，顺便避免双斜杠

    if [[ -f "$cached_file" ]]; then
      echo "**从缓存复制文件: $cached_file -> $filename **"
      rsync -a "$cached_file" "$filename"
      return_code=$?
    else
      return_code=1
      if safe_download "$url" "$filename"; then
        echo "**将下载的文件复制到缓存: $filename -> $cached_file **"
        rsync -a "$filename" "$cached_file"
        return_code=$?
      fi
    fi
  else
    safe_download "$url" "$filename"
    return_code=$?
  fi
  return $return_code
}

safe_download()
{
  local url="$1" filename="$2"
  local max_retries=3 retry_count=0

  while [[ $retry_count -lt $max_retries ]]; do
    echo "**下载尝试 $((retry_count + 1))/$max_retries**: $filename"
    rm -f "$filename"

    echo "**使用 aria2c 进行多线程下载**"
    if aria2c --enable-color=false --show-console-readout=false -x 8 -s 8 -k 1M -d "$(dirname "$filename")" -o "$(basename "$filename")" "$url" && [[ -f "$filename" ]]; then
      echo "✅ **下载完成**: $filename"
      return 0
    fi

    retry_count=$((retry_count + 1))
  done

  echo "❌ **下载失败**: $filename"
  return 1
}
