#!/bin/bash
# omarchy:summary=Check network, pacman mirror, and dev registries; --fix fails over mirrors
# omarchy:args=[network|mirror|dev-mirror] [--fix]
# omarchy:examples=omarchycn doctor | omarchycn doctor mirror --fix

set -euo pipefail

source "$OMARCHY_PATH/cn/lib/mirror.sh"

module="all"
fix="false"
for arg in "$@"; do
  case "$arg" in
  all | network | mirror | dev-mirror | ime) module="$arg" ;;
  --fix) fix="true" ;;
  *)
    echo "Unknown argument: $arg" >&2
    exit 2
    ;;
  esac
done

failures=0

check_network() {
  local host
  for host in mirrors.tuna.tsinghua.edu.cn archlinux.org; do
    if getent hosts "$host" > /dev/null 2>&1; then
      echo "PASS network: DNS resolves $host"
    else
      echo "FAIL network: cannot resolve $host"
      failures=$((failures + 1))
    fi
  done
  if curl -sSf -o /dev/null -m 8 --connect-timeout 5 https://www.baidu.com 2>/dev/null; then
    echo "PASS network: HTTPS reachable (baidu.com)"
  else
    echo "FAIL network: HTTPS unreachable (baidu.com)"
    failures=$((failures + 1))
  fi
}

check_mirror() {
  local primary speed ttfb age

  primary=$(grep -sE '^Server' "$CN_MIRRORLIST" | head -1 | sed -E 's/^Server = //; s|/\$repo/os/\$arch/?$||' || true)
  if [[ -z $primary ]]; then
    echo "FAIL mirror: no Server entries in $CN_MIRRORLIST"
    failures=$((failures + 1))
    return 0
  fi

  echo "INFO mirror: primary $primary"
  read -r speed ttfb age < <(cn_mirror_probe "$primary")
  if (( speed > 0 )) && [[ $age != "stale" ]]; then
    echo "PASS mirror: primary healthy ($((speed / 1024)) KB/s, sync age ${age}s)"
    return 0
  fi

  echo "FAIL mirror: primary unhealthy (speed=$speed age=$age)"
  failures=$((failures + 1))

  if [[ $fix == "true" && -f $CN_PROFILE_FILE && $(<"$CN_PROFILE_FILE") == "china" ]]; then
    echo "INFO mirror: re-applying china profile (auto-failover)"
    if omarchy-cn-mirror-apply china; then
      failures=$((failures - 1))
      omarchy-notification-send "OmarchyCN" "pacman 镜像已自动切换" 2> /dev/null || true
    fi
  fi
}

check_dev_mirror() {
  omarchy-cn-dev-mirror-doctor || failures=$((failures + 1))
}

check_ime() {
  omarchy-cn-ime-status || failures=$((failures + 1))
}

case "$module" in
network) check_network ;;
mirror) check_mirror ;;
dev-mirror) check_dev_mirror ;;
ime) check_ime ;;
all)
  check_network
  check_mirror
  check_dev_mirror
  check_ime
  ;;
esac

if (( failures > 0 )); then
  echo "Doctor: $failures failure(s)"
  exit 1
fi
echo "Doctor: all checks passed"
