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

BASE_URL="https://twpkinfo.com/images/poke1"
OUT_DIR="img"
START="${1:-1}"
END="${2:-1000}"
CONCURRENCY="${CONCURRENCY:-8}"  # 可調整並行數量

mkdir -p "$OUT_DIR"

seq "$START" "$END" | xargs -I{} -P "$CONCURRENCY" bash -c '
  i="$1"
  url="'$BASE_URL'/${i}.png"
  out="'$OUT_DIR'/${i}.png"

  # 已存在就跳過
  if [[ -s "$out" ]]; then
    echo "✅ skip (exists): $out"
    exit 0
  fi

  # 嘗試下載
  if curl -fsSL --retry 3 --connect-timeout 10 -A "Mozilla/5.0" -o "$out.part" "$url"; then
    mv "$out.part" "$out"
    echo "⬇️  ok: $url -> $out"
  else
    rm -f "$out.part"
    echo "❌ not found or failed: $url"
  fi
' _ {}

