#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# SDK 版本号同步脚本
#
# 从 docs/CHANGELOG.md 读取最新版本号，同步到各端 sdkVersion() 函数体 +
# 构建配置值（gradle 回退值 / HAR_VERSION / MARKETING_VERSION）。
#
# 用法：
#   bash scripts/update-version.sh           # 从 CHANGELOG 读版本号
#   bash scripts/update-version.sh 1.2.3     # 手动指定版本号
#   bash scripts/update-version.sh --help    # 查看帮助
#
# 设计要点：
# - 版本号唯一真相源为 docs/CHANGELOG.md（复用 extract-version.sh）
# - sdkVersion() 函数体直接内嵌版本号，源码集成客户无需构建脚本即可获得正确版本
# - 构建配置值同步保持产物元数据（Info.plist / aar / har）正确，但运行时不依赖
# - 不触碰 Demo app 的 versionName / versionCode（独立维护）
# - 每处替换后 grep 校验命中，未命中即报错退出
# ------------------------------------------------------------------------------
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# ---- --help ------------------------------------------------------------------
case "${1:-}" in
  -h|--help)
    sed -n '2,18p' "${BASH_SOURCE[0]}"
    exit 0
    ;;
esac

# ---- 版本号 ------------------------------------------------------------------
# 默认从 CHANGELOG 读取，也可通过第一个参数手动指定
DEFAULT_VERSION="$("${SCRIPT_DIR}/extract-version.sh")"
VERSION="${1:-${DEFAULT_VERSION}}"

# 版本号格式校验（X.Y.Z 或 X.Y.Z-suffix）
if ! [[ "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-.][a-zA-Z0-9]+)*$ ]]; then
  echo "❌ 版本号格式不合法：${VERSION}" >&2
  echo "   期望格式：X.Y.Z 或 X.Y.Z-rc1 / X.Y.Z.beta 等" >&2
  exit 1
fi

echo "ℹ️  仓库根目录：${REPO_ROOT}"
echo "ℹ️  目标版本：  ${VERSION}"
echo ""

# ---- 替换函数 ----------------------------------------------------------------
# stamp <rel_path> <label> <sed_expr> <verify_re>
# 作用于仓库源码文件，替换后 grep -E 校验命中，未命中报错退出。
# 注意：sed_expr 里的分组如果已包含引号，替换部分不应再加引号（\1VER\2）；
#       如果分组不包含引号，替换部分需要加引号（\1"VER" 或 \1'VER'）。
stamp() {
  local rel="$1" label="$2" sed_expr="$3" verify_re="$4"
  local f="${REPO_ROOT}/${rel}"
  if [[ ! -f "${f}" ]]; then
    echo "   ⚠ 跳过 ${label}：文件不存在 ${rel}"
    return 0
  fi
  local tmp="${f}.update.tmp"
  sed -E "${sed_expr}" "${f}" > "${tmp}" && mv -f "${tmp}" "${f}"
  if ! grep -Eq "${verify_re}" "${f}"; then
    echo "❌ 版本替换未命中：${rel}（${label}）" >&2
    echo "   该文件版本字段格式可能已变更，请同步更新 update-version.sh 的替换规则" >&2
    exit 1
  fi
  echo "   ✓ ${label}"
}

# ---- 1. sdkVersion() 函数体版本字符串（5 处）--------------------------------
# 分组包含引号，替换部分为 \1${VERSION}\2（不加引号）
echo "▶ [1/2] 同步 sdkVersion() 函数体版本字符串..."

# Android Kotlin: public fun sdkVersion(): String = "X.Y.Z"
stamp \
  "android-kotlin/webview-container/src/main/kotlin/com/tencent/qian/webview/TencentQianWebView.kt" \
  "Android Kotlin sdkVersion()" \
  "s/(sdkVersion\\(\\): String = \")[^\"]*(\")/\\1${VERSION}\\2/" \
  "sdkVersion\\(\\): String = \"${VERSION}\""

# Android Java: return "X.Y.Z"; (within sdkVersion method, range-matched)
stamp \
  "android-java/webview-container/src/main/java/com/tencent/qian/webview/TencentQianWebView.java" \
  "Android Java sdkVersion()" \
  "/sdkVersion/,/return/s/(return \")[^\"]*(\";)/\\1${VERSION}\\2/" \
  "return \"${VERSION}\";"

# HarmonyOS: return 'X.Y.Z'; (within sdkVersion method, range-matched)
stamp \
  "harmonyos-arkts/tencentqianwebview/src/main/ets/TencentQianWebView.ets" \
  "HarmonyOS sdkVersion()" \
  "/sdkVersion/,/return/s/(return ')[^']*(')/\\1${VERSION}\\2/" \
  "return '${VERSION}'"

# iOS Swift: public static let sdkVersion: String = "X.Y.Z"
stamp \
  "ios-swift/TencentQianWebView/Sources/TencentQianWebView.swift" \
  "iOS Swift sdkVersion" \
  "s/(sdkVersion: String = \")[^\"]*(\")/\\1${VERSION}\\2/" \
  "sdkVersion: String = \"${VERSION}\""

# iOS OC: return @"X.Y.Z"; (within sdkVersion method, range-matched)
stamp \
  "ios-objective-c/TencentQianWebView/Sources/Public/TQWebView.m" \
  "iOS OC sdkVersion" \
  "/sdkVersion/,/return/s/(return @\")[^\"]*(\";)/\\1${VERSION}\\2/" \
  "return @\"${VERSION}\";"

# ---- 2. 构建配置值（5 处）---------------------------------------------------
# 分组不包含引号，替换部分需要加引号
echo ""
echo "▶ [2/2] 同步构建配置值（产物元数据，运行时不依赖）..."

# Android Kotlin gradle 回退值
stamp \
  "android-kotlin/webview-container/build.gradle.kts" \
  "Android Kotlin gradle 回退值" \
  "s/(findProperty\\(\"sdkVersion\"\\)\\?\\.toString\\(\\)[[:space:]]*\\?:[[:space:]]*)\"[^\"]*\"/\\1\"${VERSION}\"/" \
  "\\?:[[:space:]]*\"${VERSION}\""

# Android Java gradle 回退值
stamp \
  "android-java/webview-container/build.gradle" \
  "Android Java gradle 回退值" \
  "s/(project\\.property\\('sdkVersion'\\)[[:space:]]*:[[:space:]]*)'[^']*'/\\1'${VERSION}'/" \
  "project\\.property\\('sdkVersion'\\)[[:space:]]*:[[:space:]]*'${VERSION}'"

# HarmonyOS HAR_VERSION
stamp \
  "harmonyos-arkts/tencentqianwebview/build-profile.json5" \
  "HarmonyOS HAR_VERSION" \
  "s/(\"HAR_VERSION\"[[:space:]]*:[[:space:]]*)\"[^\"]*\"/\\1\"${VERSION}\"/" \
  "\"HAR_VERSION\"[[:space:]]*:[[:space:]]*\"${VERSION}\""

# iOS Swift MARKETING_VERSION
stamp \
  "ios-swift/project.yml" \
  "iOS Swift MARKETING_VERSION" \
  "s/(MARKETING_VERSION:[[:space:]]*)\"[^\"]*\"/\\1\"${VERSION}\"/" \
  "MARKETING_VERSION:[[:space:]]*\"${VERSION}\""

# iOS OC MARKETING_VERSION
stamp \
  "ios-objective-c/project.yml" \
  "iOS OC MARKETING_VERSION" \
  "s/(MARKETING_VERSION:[[:space:]]*)\"[^\"]*\"/\\1\"${VERSION}\"/" \
  "MARKETING_VERSION:[[:space:]]*\"${VERSION}\""

# ---- 完成 --------------------------------------------------------------------
echo ""
echo "🎉 版本号已同步到 ${VERSION}"
echo "   sdkVersion() 函数体：5 处"
echo "   构建配置值：5 处"
echo ""
echo "⚠ 本脚本不修改 Demo app 的 versionName / versionCode（独立维护）"
echo "请提交变更后打 tag。"
