# shellcheck shell=bash
# Sourced helpers for omarchy-cn-mirror-* commands

CN_MIRRORS_JSON="$OMARCHY_PATH/cn/mirrors.json"
CN_MIRRORLIST="/etc/pacman.d/mirrorlist"
CN_PROFILE_FILE="$HOME/.config/omarchycn/mirror-profile"

cn_mirror_ids() {
  jq -r '.mirrors[].id' "$CN_MIRRORS_JSON"
}

cn_mirror_url() {
  jq -r --arg id "$1" '.mirrors[] | select(.id == $id) | .url' "$CN_MIRRORS_JSON"
}

cn_mirror_name() {
  jq -r --arg id "$1" '.mirrors[] | select(.id == $id) | .name' "$CN_MIRRORS_JSON"
}

cn_mirror_ids_by_region() {
  jq -r --arg r "$1" '.mirrors[] | select(.region == $r) | .id' "$CN_MIRRORS_JSON"
}

# Probe one mirror: prints "<speed_bytes_s> <ttfb_s> <sync_age_s|stale|unknown>"
cn_mirror_probe() {
  local url="$1"
  local out speed=0 ttfb=0 lastsync age="unknown" now

  if out=$(curl -sSf -o /dev/null -m 12 --connect-timeout 5 \
    -w '%{speed_download} %{time_starttransfer}' \
    "$url/core/os/x86_64/core.db" 2>/dev/null); then
    read -r speed ttfb <<<"$out"
    speed="${speed%%.*}"
  fi

  if lastsync=$(curl -sSf -m 5 --connect-timeout 5 "$url/lastsync" 2>/dev/null); then
    lastsync=$(tr -cd '0-9' <<<"$lastsync")
    if [[ -n $lastsync ]]; then
      now=$(date +%s)
      age=$((now - lastsync))
      if (( age > 86400 )); then
        age="stale"
      fi
    fi
  fi

  echo "$speed $ttfb $age"
}

# Rank ids by probe speed, excluding dead (speed 0) and stale mirrors
cn_mirror_rank() {
  local id url speed ttfb age

  for id in "$@"; do
    url=$(cn_mirror_url "$id")
    read -r speed ttfb age < <(cn_mirror_probe "$url")
    (( speed > 0 )) || continue
    [[ $age == "stale" ]] && continue
    echo "$speed $id"
  done | sort -rn | awk '{print $2}'
}

# Write mirrorlist from mirror ids (first = primary), with timestamped backup
cn_mirror_write_list() {
  local profile="$1"
  shift
  local stamp id url content=""

  stamp=$(date +%Y%m%d-%H%M%S)
  content="## OmarchyCN mirrorlist (profile: $profile, generated $stamp)\n"
  for id in "$@"; do
    url=$(cn_mirror_url "$id")
    content+="## $id: $(cn_mirror_name "$id")\nServer = $url/\$repo/os/\$arch\n"
  done

  sudo cp "$CN_MIRRORLIST" "$CN_MIRRORLIST.omarchycn-bak-$stamp"
  printf '%b' "$content" | sudo tee "$CN_MIRRORLIST" > /dev/null

  mkdir -p "${CN_PROFILE_FILE%/*}"
  echo "$profile" > "$CN_PROFILE_FILE"
  echo "Mirrorlist written ($CN_MIRRORLIST), backup: $CN_MIRRORLIST.omarchycn-bak-$stamp"
}
