#!/bin/bash
# omarchy:summary=Check AI harness installation, credentials, and endpoint health
# omarchy:examples=omarchycn ai doctor

set -euo pipefail

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

failures=0

profile=$(cn_ai_current_profile 2>/dev/null || true)
if [[ -z $profile ]]; then
  echo "INFO ai: 未设置默认 Profile (omarchycn ai profile use <name>)"
  exit 0
fi
echo "INFO ai: current profile $profile"

if [[ ! -f $CN_AI_PROFILE_DIR/$profile.toml ]]; then
  echo "FAIL ai: 默认 Profile $profile 的文件不存在 (omarchycn ai profile list)"
  exit 1
fi

harness=$(cn_ai_profile_field "$profile" harness)
provider=$(cn_ai_profile_field "$profile" provider)
command=$(cn_ai_harness_field "$harness" command)
proto=$(cn_ai_harness_field "$harness" protocol)

if omarchy-cmd-present "$command"; then
  echo "PASS ai: harness $harness installed ($command)"
else
  install=$(cn_ai_harness_field "$harness" install)
  if [[ $install == doc:* ]]; then
    echo "WARN ai: harness $harness 未安装，需手动安装: ${install#doc:}"
  else
    echo "WARN ai: harness $harness 未安装，首次 launch 时自动安装"
  fi
fi

if [[ $proto == "native" ]]; then
  echo "INFO ai: $harness 自管鉴权，跳过 OmarchyCN Key 检查"
elif cn_ai_static_token "$provider" > /dev/null 2>&1; then
  echo "PASS ai: $provider 使用内置 token，无需存储 Key"
elif omarchy-cn-ai-secret get "$provider" > /dev/null 2>&1; then
  echo "PASS ai: $provider API Key stored"
else
  echo "FAIL ai: $provider API Key 未存储 (omarchycn ai secret set $provider)"
  failures=$((failures + 1))
fi

if [[ $proto != "native" ]]; then
  base=$(cn_ai_endpoint "$provider" "$proto")
  host=$(sed -E 's|https?://([^/:]+).*|\1|' <<<"$base")
  if getent hosts "$host" > /dev/null 2>&1; then
    echo "PASS ai: endpoint DNS resolves ($host)"
  else
    echo "FAIL ai: endpoint DNS 无法解析 ($host)"
    failures=$((failures + 1))
  fi
fi

exit $((failures > 0 ? 1 : 0))
