#!/bin/bash
# 批量升级 Dart / Flutter SDK 版本约束
#
# 无参数：从官方拉最新稳定版，Dart + Flutter 一起升级：
#   melos run sdk:bump
#
# 只升 Dart（Flutter 下限不变）：
#   melos run sdk:bump -- --dart 3.12.0
#
# 只升 Flutter 下限（Dart 不变）：
#   melos run sdk:bump -- --flutter 3.40.0
#
# 手动指定两者（CI 固定版本）：
#   melos run sdk:bump -- --dart 3.12.0 --flutter 3.40.0

set -euo pipefail

DART_VERSION=""
FLUTTER_VERSION=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dart)    DART_VERSION="$2";    shift 2 ;;
    --flutter) FLUTTER_VERSION="$2"; shift 2 ;;
    *) echo "Unknown argument: $1"; exit 1 ;;
  esac
done

# 无参数：从官方接口获取最新稳定版本，Dart + Flutter 一起升级
if [[ -z "$DART_VERSION" ]] && [[ -z "$FLUTTER_VERSION" ]]; then
  OS_TYPE="macos"
  if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS_TYPE="linux"
  fi

  RELEASES_URL="https://storage.googleapis.com/flutter_infra_release/releases/releases_${OS_TYPE}.json"
  echo "Fetching latest stable Flutter version from flutter.dev..."

  RELEASES_JSON=$(curl -sf "$RELEASES_URL") || {
    echo "Error: Failed to fetch Flutter releases from $RELEASES_URL"
    exit 1
  }

  read -r FLUTTER_VERSION DART_VERSION <<< "$(echo "$RELEASES_JSON" | python3 - <<'PY'
import json, sys, re
d = json.load(sys.stdin)
stable_hash = d["current_release"]["stable"]
release = next(r for r in d["releases"] if r["hash"] == stable_hash)
flutter_ver = release["version"].lstrip("v")
dart_ver = re.search(r"[\d]+\.[\d]+\.[\d]+", release["dart_sdk_version"]).group()
print(flutter_ver, dart_ver)
PY
)"
fi

PUBSPECS=$(find . \
  -name "pubspec.yaml" \
  ! -path "*/.dart_tool/*" \
  ! -path "*/build/*" \
  ! -path "*/.pub-cache/*")

if [[ -n "$DART_VERSION" ]]; then
  echo "Dart SDK    : ^$DART_VERSION"
  echo "$PUBSPECS" | xargs sed -i '' \
    "s/sdk: \^[0-9][0-9.]*[0-9]/sdk: ^$DART_VERSION/g"
fi

if [[ -n "$FLUTTER_VERSION" ]]; then
  echo "Flutter SDK : >=$FLUTTER_VERSION"
  echo "$PUBSPECS" | xargs sed -i '' \
    "s/flutter: '>=[0-9][0-9.]*[0-9]'/flutter: '>=$FLUTTER_VERSION'/g"
fi

echo ""
echo "Running dart pub get..."
dart pub get
echo "Done."
